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 inputToken parameter for the token with the contract address specified in the outputToken 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 TradeRequest parameter with the following properties:

ParameterTypeDescription
inputTokenaddressThe contract address of the token to be swapped.
outputTokenaddressThe contract address of the token to swap for.
inputAmountnumberThe amount of the input token to be traded.
exactInbooleanDetermines the type of trade (exact input or exact output).

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 TradeRequest(
nativeTokenAddress,
usdcTokenAddress,
parseUnits('1', 18),
true,
),
);

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}`
);