# Swap USDT0 to FXRP

> Swap USDT0 to FXRP using Uniswap V3 router

> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.

Source: https://dev.flare.network/fxrp/token-interactions/usdt0-fxrp-swap

## Overview[​](#overview "Direct link to Overview")

In this guide, you will learn how to swap USDT0 to FXRP using the Uniswap V3 router (SparkDEX). FXRP is the ERC-20 representation of XRP used by [FAssets](/fassets/overview).

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

Before starting, make sure you have:

-   Basic understanding of the [FAssets system](/fassets/overview).
-   [Flare Network Periphery Contracts](https://www.npmjs.com/package/@flarenetwork/flare-periphery-contracts) package installed.
-   Familiarity with [Uniswap V3 swaps](https://docs.uniswap.org/contracts/v3/guides/swaps/single-swaps).

## Required Addresses on Flare Mainnet[​](#required-addresses-on-flare-mainnet "Direct link to Required Addresses on Flare Mainnet")

-   V3 SwapRouter (SparkDEX): [0x8a1E35F5c98C4E85B36B7B253222eE17773b2781](https://flare-explorer.flare.network/address/0x8a1E35F5c98C4E85B36B7B253222eE17773b2781?tab=contract).
-   USDT0: [0xe7cd86e13AC4309349F30B3435a9d337750fC82D](https://flare-explorer.flare.network/address/0xe7cd86e13AC4309349F30B3435a9d337750fC82D).
-   FXRP: [resolved dynamically from the Asset Manager](/fxrp/token-interactions/fxrp-address).

## Solidity Uniswap V3 Wrapper Contract[​](#solidity-uniswap-v3-wrapper-contract "Direct link to Solidity Uniswap V3 Wrapper Contract")

This Solidity contract wraps the Uniswap V3 router, providing safe token transfers, pool checks, and event logging for debugging.

contracts/fassets/UniswapV3Wrapper.sol

```
// SPDX-License-Identifier: MITpragma solidity ^0.8.19;import "@openzeppelin/contracts/token/ERC20/IERC20.sol";import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";import "@openzeppelin/contracts/access/Ownable.sol";// 1. Defines Uniswap V3 router functions for swaps// https://github.com/Uniswap/v3-periphery// https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISwapRouter.solinterface ISwapRouter {    struct ExactInputSingleParams {        address tokenIn;        address tokenOut;        uint24 fee;        address recipient;        uint256 deadline;        uint256 amountIn;        uint256 amountOutMinimum;        uint160 sqrtPriceLimitX96;    }    struct ExactInputParams {        bytes path;        address recipient;        uint256 deadline;        uint256 amountIn;        uint256 amountOutMinimum;    }    function exactInputSingle(        ExactInputSingleParams calldata params    ) external payable returns (uint256 amountOut);    function factory() external view returns (address);}// 2. Uniswap V3 factory interface// https://github.com/Uniswap/v3-peripheryinterface IUniswapV3Factory {    function getPool(        address tokenA,        address tokenB,        uint24 fee    ) external view returns (address pool);}// 3. Uniswap V3 pool interfaceinterface IUniswapV3Pool {    function liquidity() external view returns (uint128);    function token0() external view returns (address);    function token1() external view returns (address);    function fee() external view returns (uint24);}// 4. UniswapV3Wrapper contractcontract UniswapV3Wrapper {    using SafeERC20 for IERC20;    // 5. Existing Uniswap V3 SwapRouter on Flare (SparkDEX)    ISwapRouter public immutable swapRouter;    // 6. Uniswap V3 factory    IUniswapV3Factory public immutable factory;    // 7. Events    event SwapExecuted(        address indexed user,        address indexed tokenIn,        address indexed tokenOut,        uint256 amountIn,        uint256 amountOut,        uint256 deadline,        string method    );    event PoolChecked(        address indexed tokenA,        address indexed tokenB,        uint24 fee,        address poolAddress,        uint128 liquidity    );    event TokensApproved(        address indexed token,        address indexed spender,        uint256 amount    );    // 8. Constructor that initializes the swap router and factory    constructor(address _swapRouter) {        swapRouter = ISwapRouter(_swapRouter);        factory = IUniswapV3Factory(ISwapRouter(_swapRouter).factory());    }    // 9. Check if pool exists and has liquidity    function checkPool(        address tokenA,        address tokenB,        uint24 fee    )        external        view        returns (address poolAddress, bool hasLiquidity, uint128 liquidity)    {        poolAddress = factory.getPool(tokenA, tokenB, fee);        if (poolAddress != address(0)) {            IUniswapV3Pool pool = IUniswapV3Pool(poolAddress);            liquidity = pool.liquidity();            hasLiquidity = liquidity > 0;        }    }    // 10. Swap exact input single function    // https://docs.uniswap.org/contracts/v3/reference/periphery/interfaces/ISwapRouter#exactinputsingle    function swapExactInputSingle(        address tokenIn,        address tokenOut,        uint24 fee,        uint256 amountIn,        uint256 amountOutMinimum,        uint256 deadline,        uint160 sqrtPriceLimitX96    ) external returns (uint256 amountOut) {        // 10.1. Check if pool exists        address poolAddress = factory.getPool(tokenIn, tokenOut, fee);        require(poolAddress != address(0), "Pool does not exist");        // 10.2. Check if the pool has liquidity        IUniswapV3Pool pool = IUniswapV3Pool(poolAddress);        require(pool.liquidity() > 0, "Pool has no liquidity");        // 10.3. Transfer tokens from the user to this contract        IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);        // 10.4 Approve router to spend tokens using SafeERC20        IERC20(tokenIn).approve(address(swapRouter), amountIn);        emit TokensApproved(tokenIn, address(swapRouter), amountIn);        // 10.5. Prepare swap parameters        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter            .ExactInputSingleParams({                tokenIn: tokenIn,                tokenOut: tokenOut,                fee: fee,                recipient: msg.sender,                deadline: deadline,                amountIn: amountIn,                amountOutMinimum: amountOutMinimum,                sqrtPriceLimitX96: sqrtPriceLimitX96            });        // 10.6. Execute swap        amountOut = swapRouter.exactInputSingle(params);        // 10.7. Emit swap executed event        emit SwapExecuted(            msg.sender,            tokenIn,            tokenOut,            amountIn,            amountOut,            deadline,            "exactInputSingle"        );    }}
```

[Open in Remix](https://remix.ethereum.org/#url=https://github.com/flare-foundation/developer-hub/blob/main/examples/developer-hub-solidity/UniswapV3Wrapper.sol&version=builtin&evmVersion=cancun&optimize=true&runs=200)

  

### Code Explanation[​](#code-explanation "Direct link to Code Explanation")

1.  Define the Uniswap V3 router function for swaps, which allows interaction with the Uniswap V3 protocol. It comes from the [Uniswap V3 periphery](https://github.com/Uniswap/v3-periphery).
    
2.  Use the Uniswap V3 factory interface to locate a specific pool for a token pair and the fee tier.
    
3.  Define the Uniswap V3 pool interface that provides liquidity and token details for a given pool.
    
4.  Create the `UniswapV3Wrapper` contract, which acts as a wrapper around Uniswap V3 to simplify swaps and add safety checks.
    
5.  Use the existing Uniswap V3 SwapRouter on Flare (SparkDEX) as the main entry point for executing swaps.
    
6.  Store the Uniswap V3 factory in the contract for looking up pools.
    
7.  Define events that log important actions such as swaps executed, pools checked, and tokens approved.
    
8.  Create a constructor that initializes the swap router and factory.
    
9.  Check if the pool exists and has liquidity, preventing the swaps execution in empty or non-existent pools.
    
10.  Create a swap exact input single function that executes a single-hop swap through the Uniswap V3 router protocol.
     
     10.1.
     
     Check if pool exists, ensuring a valid pool address is returned.
     
     10.2.
     
     Check if the pool has liquidity, requiring the available liquidity is greater than zero.
     
     10.3.
     
     Transfer tokens from the user to this contract, using SafeERC20 for secure transfers.
     
     10.4.
     
     Approve the router to spend tokens using the `SafeERC20` library, allowing the router to perform the swap.
     
     10.5.
     
     Prepare swap parameters, filling the `ExactInputSingleParams` struct with all necessary details.
     
     10.6.
     
     Execute the swap, calling the `swapRouter.exactInputSingle` function to perform the transaction.
     
     10.7.
     
     Emit the swap executed event, logging details about the user, tokens, and amounts.
     

## Execute the Swap with Hardhat[​](#execute-the-swap-with-hardhat "Direct link to Execute the Swap with Hardhat")

To execute a swap, you need to deploy the wrapper contract and call `swapExactInputSingle` with the swap parameters.

scripts/fassets/swapExactInputSingle.ts

```
import { ethers, run } from "hardhat";import { web3 } from "hardhat";import type { UniswapV3WrapperInstance } from "../../typechain-types";import { getAssetManagerFXRP } from "../utils/getters";import type { ERC20Instance } from "../../typechain-types/@openzeppelin/contracts/token/ERC20/ERC20";// yarn hardhat run scripts/fassets/uniswapV3Wrapper.ts --network flare// 1. Contract artifactsconst UniswapV3Wrapper = artifacts.require("UniswapV3Wrapper");const ERC20 = artifacts.require("ERC20");// 2. Flare Uniswap V3 addresses (SparkDEX)// https://docs.sparkdex.ai/additional-information/smart-contract-overview/v2-v3.1-dexconst SWAP_ROUTER = "0x8a1E35F5c98C4E85B36B7B253222eE17773b2781";// 3. USDT0 token addresses on Flare// https://docs.usdt0.to/technical-documentation/developer#flare-eid-30295const USDT0 = "0xe7cd86e13AC4309349F30B3435a9d337750fC82D";// 4. Pool fee tierconst FEE = 500; // 0.05%// 5. Swap parametersconst AMOUNT_IN = ethers.parseUnits("1.0", 6); // 1 USDT0 (6 decimals)const AMOUNT_OUT_MIN = ethers.parseUnits("0.3", 6); // 0.3 FXRP minimum expected (6 decimals)// 6. Function to deploy and verify the smart contractasync function deployAndVerifyContract() {  const args = [SWAP_ROUTER];  const uniswapV3Wrapper: UniswapV3WrapperInstance = await UniswapV3Wrapper.new(    ...args,  );  const uniswapV3WrapperAddress = await uniswapV3Wrapper.address;  try {    await run("verify:verify", {      address: uniswapV3WrapperAddress,      constructorArguments: args,    });  } catch (e: unknown) {    console.log(e);  }  console.log("UniswapV3Wrapper deployed to:", uniswapV3WrapperAddress);  return uniswapV3Wrapper;}// 7. Function to setup and initialize tokensasync function setUpAndInitializeTokens() {  const accounts = await web3.eth.getAccounts();  const deployer = accounts[0];  console.log("Deployer:", deployer);  console.log("Total accounts available:", accounts.length);  // FXRP address on Flare (from asset manager)  const assetManager = await getAssetManagerFXRP();  const FXRP = await assetManager.fAsset();  console.log("USDT0:", USDT0);  console.log("FXRP:", FXRP);  console.log("Fee:", FEE);  console.log("Amount In:", AMOUNT_IN.toString());  console.log("Amount Out Min:", AMOUNT_OUT_MIN.toString());  console.log("");  const usdt0: ERC20Instance = await ERC20.at(USDT0);  const fxrp: ERC20Instance = await ERC20.at(FXRP);  // Check initial balances  const initialUsdt0Balance = BigInt(    (await usdt0.balanceOf(deployer)).toString(),  );  const initialFxrpBalance = BigInt(    (await fxrp.balanceOf(deployer)).toString(),  );  console.log("Initial USDT0 balance:", initialUsdt0Balance.toString());  console.log("Initial FXRP balance:", initialFxrpBalance.toString());  // Check if there are enough USDT0  const amountInBN = AMOUNT_IN;  if (initialUsdt0Balance < amountInBN) {    console.log(      "❌ Insufficient USDT0 balance. Need:",      AMOUNT_IN.toString(),      "Have:",      initialUsdt0Balance.toString(),    );    console.log(      "Please ensure you have sufficient USDT0 tokens to perform the swap.",    );    throw new Error("Insufficient USDT0 balance");  }  return { deployer, usdt0, fxrp, initialUsdt0Balance, initialFxrpBalance };}// 8. Function to verify the pool and liquidityasync function verifyPoolAndLiquidity(  uniswapV3Wrapper: UniswapV3WrapperInstance,) {  console.log("\n=== Pool Verification ===");  const assetManager = await getAssetManagerFXRP();  const FXRP = await assetManager.fAsset();  const poolInfo = await uniswapV3Wrapper.checkPool(USDT0, FXRP, FEE);  console.log("Pool info:", poolInfo);  const poolAddress = poolInfo.poolAddress;  const hasLiquidity = poolInfo.hasLiquidity;  const liquidity = poolInfo.liquidity;  console.log("Pool Address:", poolAddress);  console.log("Has Liquidity:", hasLiquidity);  console.log("Liquidity:", liquidity.toString());  if (poolAddress === "0x0000000000000000000000000000000000000000") {    console.log("❌ Pool does not exist for this token pair and fee tier");    console.log("Please check if the USDT0/FXRP pool exists on SparkDEX");    throw new Error("Pool does not exist");  }  if (!hasLiquidity) {    console.log("❌ Pool exists but has no liquidity");    throw new Error("Pool has no liquidity");  }  console.log("✅ Pool verification successful!");  return { poolAddress, hasLiquidity, liquidity };}// 9. Function to approve USDT0 for the swapasync function approveUsdt0ForSwap(  usdt0: ERC20Instance,  uniswapV3WrapperAddress: string,) {  console.log("\n=== Token Approval ===");  const approveTx = await usdt0.approve(    uniswapV3WrapperAddress,    AMOUNT_IN.toString(),  );  console.log("✅ USDT0 approved to wrapper contract", approveTx);  return approveTx;}// 10. Function to execute the SparkDEX swapasync function executeSparkDexSwap(uniswapV3Wrapper: UniswapV3WrapperInstance) {  console.log("\n=== Execute SparkDEX Swap ===");  const assetManager = await getAssetManagerFXRP();  const FXRP = await assetManager.fAsset();  const deadline = Math.floor(Date.now() / 1000) + 20 * 60; // 20 minutes  console.log("Deadline:", deadline);  console.log("Executing SparkDEX swap using wrapper...");  const swapTx = await uniswapV3Wrapper.swapExactInputSingle(    USDT0,    FXRP,    FEE,    AMOUNT_IN.toString(),    AMOUNT_OUT_MIN.toString(),    deadline,    0, // sqrtPriceLimitX96 = 0 (no limit for the price)    // https://docs.uniswap.org/contracts/v3/guides/swaps/single-swaps#swap-input-parameters  );  console.log("Transaction submitted:", swapTx);  const swapReceipt = await swapTx.receipt;  console.log("✅ SparkDEX swap executed successfully!");  return { swapTx, swapReceipt };}// 11. Function to check the final balancesasync function checkFinalBalances(  usdt0: ERC20Instance,  fxrp: ERC20Instance,  deployer: string,  initialUsdt0Balance: bigint,  initialFxrpBalance: bigint,) {  console.log("\n=== Final Balances ===");  const finalUsdt0Balance = BigInt(    (await usdt0.balanceOf(deployer)).toString(),  );  const finalFxrpBalanceAfter = BigInt(    (await fxrp.balanceOf(deployer)).toString(),  );  console.log("Final USDT0 balance:", finalUsdt0Balance.toString());  console.log("Final FXRP balance:", finalFxrpBalanceAfter.toString());  console.log(    "USDT0 spent:",    (initialUsdt0Balance - finalUsdt0Balance).toString(),  );  console.log(    "FXRP received:",    (finalFxrpBalanceAfter - initialFxrpBalance).toString(),  );  return { finalUsdt0Balance, finalFxrpBalanceAfter };}// 12. The main function to execute the complete swap logic and verify the resultsasync function main() {  const uniswapV3Wrapper: UniswapV3WrapperInstance =    await deployAndVerifyContract();  const { deployer, usdt0, fxrp, initialUsdt0Balance, initialFxrpBalance } =    await setUpAndInitializeTokens();  await verifyPoolAndLiquidity(uniswapV3Wrapper);  await approveUsdt0ForSwap(usdt0, uniswapV3Wrapper.address);  await executeSparkDexSwap(uniswapV3Wrapper);  await checkFinalBalances(    usdt0,    fxrp,    deployer,    initialUsdt0Balance,    initialFxrpBalance,  );}main().catch((error) => {  console.error(error);  process.exitCode = 1;});
```

### Code Breakdown[​](#code-breakdown "Direct link to Code Breakdown")

1.  Import contract artifacts, including `IAssetManager`, `UniswapV3Wrapper`, and `ERC20`, which provide access to the deployed contracts.
    
2.  Define Flare Uniswap V3 addresses (SparkDEX), specifying the SwapRouter address used for executing swaps.
    
3.  Set the USDT0 token address on Flare Mainnet, which represents the stablecoin used as the input asset for the swap.
    
4.  Set the pool fee tier to 500 (0.05%), which defines the fee level of the pool to use on the Uniswap V3 router (SparkDEX).
    
5.  Define swap parameters.
    
6.  Define the function `deployAndVerifyContract()` that deploys the UniswapV3Wrapper contract and verifies it on the blockchain explorer.
    
7.  Create the `setupAndInitializeTokens()` function that prepares accounts and ERC20 contracts.
    
8.  Define the `verifyPoolAndLiquidity()` function which ensures the USDT0/FXRP pool exists and is usable.
    
9.  Create the `approveUsdt0ForSwap()` function that approves the wrapper contract to spend USDT0 on behalf of the deployer.
    
10.  Create the `executeSparkDexSwap()` function that executes the swap on SparkDEX using the Uniswap V3 wrapper.
     
11.  Create the `checkFinalBalances()` function that verifies the swap results.
     
12.  Create the `main()` function that orchestrates the entire flow of the swap.
     

### Run the Script[​](#run-the-script "Direct link to Run the Script")

To run the script, you need to execute the following command:

```
yarn hardhat run scripts/fassets/uniswapV3Wrapper.ts --network flare
```

info

This script is included in the [Flare Hardhat Starter Kit](/network/guides/hardhat-foundry-starter-kit).

## Summary[​](#summary "Direct link to Summary")

In this guide, you learned how to swap USDT0 to FXRP using the Uniswap V3 router (SparkDEX).

tip

To continue your FAssets development journey, you can:

-   Learn how to [mint FXRP](/fassets/developer-guides/fassets-direct-minting).
-   Understand how to [redeem FXRP](/fassets/developer-guides/fassets-redeem).
-   Explore [FAssets system settings](/fassets/operational-parameters).
