Skip to main content

Swap Tokens

Swap Tokens

To exchange one token for another, use the swapTokens() method. This method swaps the token with the contract address specified in the currencyIn parameter for the token with the contract address specified in the currencyOut parameter at the current market price.

Additionally, this method relays the transaction and covers the gas fees for the user, so they don't need to worry about those fees.

The method requires a TradeRequestBody parameter with the following properties:

ParameterTypeDescription
currencyInaddressThe contract address of the token to be swapped.
currencyOutaddressThe contract address of the token to swap for.
amountInnumberThe amount of currencyIn to swap.
recipientaddressThe recipient address for the swapped tokens.

To ensure your transfer request is successful, subscribe to the transactionStarted, transactionHash, transactionSucceeded, and transactionFailed events of the FuseWalletSDK instance. This will allow you to monitor the transaction as it progresses through the network and handle any errors that may occur.

const nativeTokenAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
const usdcTokenAddress = "0x28C3d1cD466Ba22f6cae51b1a4692a831696391A";
const res = await fuseSDK.swapTokens(
new TradeRequestBody({
amountIn: "0.1",
currencyIn: nativeTokenAddress,
currencyOut: usdcTokenAddress,
recipient: fuseSDK.wallet.getSender(),
})
);

console.log(`UserOpHash: ${res?.userOpHash}`);
console.log("Waiting for transaction...");
const ev = await res?.wait();
console.log(
`Transaction hash: https://explorer.fuse.io/tx/${ev?.transactionHash}`
);

Was this page helpful?