Swaps
In this brief guide we will use the Checkout SDK to quote and execute a swap transaction.
Swaps Overview
The SDK provides methods to facilitate both obtaining a swap quote and executing the swap transaction.
Quote a Swap: You can use the
swapQuote()
function to get swap quote, and the necessary transactions to be executed. This allows you to understand the quote upfront, and control when and how to execute theapproval
andswap
transactions. This function returns aSwapQuoteResult
.Execute a Swap: The SDK
swap()
function allows for headless execution of a swap, enabling programmatic execution without a user interface. The only user interactions required involve signing theapproval
andswap
transactions with their wallets. This function returns aSwapResult
.
SwapParams
Prepare the required SwapParams
.
Parameter | Description | Required? |
---|---|---|
provider * | The provider used to get the wallet address. | yes |
fromToken * | The token to swap from. | yes |
toToken * | The token to swap to. | yes |
fromAmount | The amount to swap from. | required if not toAmount |
toAmount | The amount to swap to. | required if not fromAmount |
slippagePercent | The percentage of slippage tolerance (default = 0.1, max = 50, min = 0). | no |
maxHops | Maximum hops allowed in the optimal route (default is 2). | no |
deadline | Latest time the swap can execute (default is 15 minutes). | no |
Quote a Swap
Quote the swap first, then execute the swap transaction.
// Import the checkout module from the Immutable SDK package
import { checkout } from '@imtbl/sdk';
// Instantiate the Checkout SDKs with the default configurations
const checkoutSDK = new checkout.Checkout();
(async () => {
// Create provider
const { provider } = await checkoutSDK.createProvider({
walletProviderName: checkout.WalletProviderName.METAMASK,
});
// Connect provider
checkoutSDK.connect({ provider });
// Validate is connected
const { isConnected } = await checkoutSDK.checkIsWalletConnected({
provider,
});
if (!isConnected) {
throw new Error('Not connected');
}
// get a quote
const quoteResult = await checkoutSDK.swapQuote({
provider: provider,
fromToken: {
icon: '',
name: 'USDC',
symbol: 'USDC',
decimals: 6,
address: '0x3B2d8A1931736Fc321C24864BceEe981B11c3c57',
},
toToken: {
icon: '',
name: 'IMX',
symbol: 'IMX',
decimals: 18,
address: 'native',
},
fromAmount: '10', // swap 10 USDC to receive IMX
// toAmount: // omit since `fromAmount` is set
slippagePercent: 1, // 1% slippage
maxHops: 2, // ie: USDC -> ETH -> IMX
deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from now
});
// use the quote result
const { quote, approval, swap } = quoteResult;
console.log('Swap quote:', quote);
// Execute the swap
try {
// Get signer
const signer = provider.getSigner();
// send the approval transaction, if needed
if (approval) {
const approvalTx = await signer.sendTransaction(approval.transaction);
await approvalTx.wait(); // wait for the transaction to be mined
const approvalReceipt = await approvalTx.wait();
if (approvalReceipt.status === 0) {
throw new Error('Approval transaction failed and was reverted');
}
console.log('Token approved:', approvalReceipt.transactionHash);
}
// send the swap transaction
const swapTx = await provider
.getSigner()
.sendTransaction(swap.transaction);
const swapReceipt = await swapTx.wait();
if (swapReceipt.status === 0) {
throw new Error('Swap transaction failed and was reverted');
}
console.log('Swap executed:', swapReceipt.transactionHash);
} catch (error) {
console.error('Error executing swap:', error);
}
})();
Execute a Swap
The quote estimated gas amount covers the approval cost as well as the cost of performing the swap operation.
// Import the checkout module from the Immutable SDK package
import { Web3Provider } from '@ethersproject/providers';
import { checkout } from '@imtbl/sdk';
// Instantiate the Checkout SDKs with the default configurations
const checkoutSDK = new checkout.Checkout();
(async () => {
// Ensure you have a connected provider (as shown in the previous example)
const provider = {} as Web3Provider;
// Execute the swap
try {
const swapResult = await checkoutSDK.swap({
provider,
fromToken: {
icon: '',
name: 'IMX',
symbol: 'IMX',
decimals: 18,
address: 'native',
},
toToken: {
icon: '',
name: 'USDC',
symbol: 'USDC',
decimals: 6,
address: '0x3B2d8A1931736Fc321C24864BceEe981B11c3c57',
},
toAmount: '100', // swap IMX to receive 100 USDC
// fromAmount: '', // omit since `fromAmount` is set
slippagePercent: 1, // 1% slippage
maxHops: 2, // ie: USDC -> ETH -> IMX
deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from now
});
// Use the swap result
const { quote, swap, swapReceipt } = swapResult;
console.log('Swap quote:', quote);
console.log('Swap transaction:', swap);
console.log('Swap transaction receipt:', swapReceipt);
} catch (error) {
console.error('Error executing swap:', error);
}
})();