Performing Swaps
SwapKit provides a unified interface for swapping tokens across different chains and protocols. This guide covers how to get quotes and execute swaps using both the granular and all-in-one approaches.
Before starting, make sure you understand Core Concepts like AssetValue and Chain types. For detailed API methods, see the API Reference.
Two Approaches for Using SwapKit
Section titled “Two Approaches for Using SwapKit”You can use SwapKit in two ways:
-
Granular approach - Import only what you need from individual packages (recommended for frontend):
import { SwapKit, ThorchainPlugin, evmWallet } from "@swapkit/sdk"; -
All-in-one approach - Import everything from the SDK (better for backend/Node.js):
import { createSwapKit } from "@swapkit/sdk";
Basic Swap Flow
Section titled “Basic Swap Flow”The typical flow for performing a swap consists of these steps:
- Initialize SwapKit and connect wallets
- Get a quote for the swap
- Approve tokens (if needed)
- Execute the swap transaction
Setting Up SwapKit for Swaps
Section titled “Setting Up SwapKit for Swaps”Granular Approach (Frontend Recommended)
Section titled “Granular Approach (Frontend Recommended)”// @noErrorValidationimport { Chain, SwapKit, evmWallet, keystoreWallet, ThorchainPlugin, EVMPlugin } from "@swapkit/sdk";
// Initialize SwapKit with necessary plugins and walletsconst swapKit = SwapKit({ config: { apiKeys: { swapKit: "your-swapkit-api-key", blockchair: "your-blockchair-api-key", walletConnectProjectId: "your-walletconnect-project-id", }, }, plugins: { ...ThorchainPlugin, ...EVMPlugin }, wallets: { ...evmWallet, ...keystoreWallet },});
// Connect necessary walletsasync function connectWallets() { // Connect EVM wallet for Ethereum await swapKit.connectEVMWallet([Chain.Ethereum]);
// If doing cross-chain swaps, connect other chains as needed // For example, to swap from ETH to BTC: await swapKit.connectKeystore([Chain.Bitcoin], "your secret phrase here");
const connectedWallets = Object.keys(swapKit.getAllWallets());}
All-in-one Approach (Backend)
Section titled “All-in-one Approach (Backend)”// @noErrorValidationimport { Chain, createSwapKit } from "@swapkit/sdk";
// Initialize SwapKit with all plugins and wallets includedconst swapKit = createSwapKit({ config: { apiKeys: { swapKit: "your-swapkit-api-key", blockchair: "your-blockchair-api-key", walletConnectProjectId: "your-walletconnect-project-id", }, },});
// Connect necessary walletsasync function connectWallets() { // Connect wallets for the chains involved in the swap await swapKit.connectKeystore( [Chain.Ethereum, Chain.Bitcoin], "your secret phrase here" );}
Getting a Swap Quote
Section titled “Getting a Swap Quote”Before executing a swap, you need to get a quote to see available routes, prices, and fees. See getSwapQuote in the API Reference for all available parameters:
// @noErrorValidationimport { SwapKitApi } from "@swapkit/helpers/api";
// Basic swap quoteasync function getSwapQuote() { // Define the assets to swap const sellAsset = "ETH.ETH"; // Ethereum on Ethereum chain const buyAsset = "ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; // USDC on Ethereum const sellAmount = "0.1"; // 0.1 ETH
try { // Get quotes from all available providers const quoteResponse = await SwapKitApi.getSwapQuote({ sellAsset, buyAsset, sellAmount, sourceAddress: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", slippage: 1, });
if (!quoteResponse.success) { throw new Error(`Failed to get quote: ${quoteResponse.error}`); }
// Routes sorted by best rate const routes = quoteResponse.data.routes;
// Found ${routes.length} routes for swapping ${sellAmount} ${sellAsset} to ${buyAsset}` // Best rate: 1 ETH = ${Number(routes[0].buyAmount) / Number(sellAmount)} USDC`
return routes; } catch (error) { throw error; }}
// Get quotes from a specific providerasync function getProviderQuote() { const { ProviderName } = await import("@swapkit/sdk"); const { SwapKitApi } = await import("@swapkit/helpers/api");
// For example, get quotes only from Uniswap V3 const quoteResponse = await SwapKitApi.getSwapQuote({ sellAsset: "ETH.ETH", buyAsset: "ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", sellAmount: "0.1", providers: [ProviderName.UNISWAP_V3], // Specify provider(s) sourceAddress: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", });
return quoteResponse.data?.routes || [];}
Executing a Swap
Section titled “Executing a Swap”Once you have a quote, you can execute the swap:
Granular Approach
Section titled “Granular Approach”// @noErrorValidationimport { AssetValue, Chain, FeeOption, ProviderName, SwapKitApi, SwapKit, evmWallet, EVMPlugin,} from "@swapkit/sdk";
// Initialize SwapKit with necessary plugins and walletsconst swapKit = SwapKit({ plugins: { ...EVMPlugin }, wallets: { ...evmWallet },});
// Connect walletawait swapKit.connectEVMWallet([Chain.Ethereum]);
// Complete swap flowasync function executeSwap() { try { // 1. Get quotes const quoteResponse = await SwapKitApi.getSwapQuote({ sellAsset: "ETH.ETH", buyAsset: "ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", sellAmount: "0.1", sourceAddress: swapKit.getAddress(Chain.Ethereum), slippage: 1, });
if (!quoteResponse.success || !quoteResponse.data.routes.length) { throw new Error("No swap routes available"); }
// 2. Select the best route (first one is usually best rate) const selectedRoute = quoteResponse.data.routes[0];
// 3. Create asset value for approvals const assetValue = await AssetValue.from({ asset: selectedRoute.sellAsset, value: selectedRoute.sellAmount, asyncTokenLookup: true, });
// 4. Check if we need to approve tokens (for ERC20 tokens) if (!assetValue.isGasAsset && selectedRoute.tx) { const isApproved = await swapKit.isAssetValueApproved( assetValue, selectedRoute.tx.from );
if (!isApproved) { // "Approval needed, approving tokens..." await swapKit.approveAssetValue(assetValue, selectedRoute.tx.from); // "Tokens approved!" } }
// 5. Execute the swap const txHash = await swapKit.swap({ route: selectedRoute, feeOptionKey: FeeOption.Fast, }) as string;
// 6. Get transaction URL const txUrl = swapKit.getExplorerTxUrl({ chain: assetValue.chain as Chain, txHash });
return { txHash, txUrl }; } catch (error) { throw error; }}
All-in-one Approach
Section titled “All-in-one Approach”// @noErrorValidationimport { AssetValue, Chain, FeeOption, SwapKitApi, createSwapKit,} from "@swapkit/sdk";
// Initialize SwapKitconst swapKit = createSwapKit();
// Connect walletawait swapKit.connectKeystore([Chain.Ethereum], "your secret phrase here");
// Execute swapasync function executeSwap() { try { // 1. Get quotes const quoteResponse = await SwapKitApi.getSwapQuote({ sellAsset: "ETH.ETH", buyAsset: "ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", sellAmount: "0.1", sourceAddress: swapKit.getAddress(Chain.Ethereum), });
if (!quoteResponse.success || !quoteResponse.data.routes.length) { throw new Error("No swap routes available"); }
// 2. Select the best route const selectedRoute = quoteResponse.data.routes[0];
// 3. Execute the swap const txHash = await swapKit.swap({ route: selectedRoute, feeOptionKey: FeeOption.Fast, });
return txHash; } catch (error) { throw error; }}
Cross-Chain Swaps with Chainflip
Section titled “Cross-Chain Swaps with Chainflip”SwapKit supports cross-chain swaps through Chainflip:
// @noErrorValidationimport { Chain, FeeOption, ProviderName, SwapKitApi, SwapKit, evmWallet, ChainflipPlugin,} from "@swapkit/sdk";
// Initialize SwapKit with necessary pluginsconst swapKit = SwapKit({ plugins: { ...ChainflipPlugin }, wallets: { ...evmWallet }, config: { integrations: { chainflip: { brokerUrl: "https://broker.chainflip.io", // Chainflip broker URL }, }, },});
// Connect source chain wallet (Ethereum)await swapKit.connectEVMWallet([Chain.Ethereum]);
// Perform a cross-chain swap from ETH to BTCasync function crossChainSwap() { try { // Get cross-chain quotes const quoteResponse = await SwapKitApi.getSwapQuote({ sellAsset: "ETH.ETH", // Ethereum buyAsset: "BTC.BTC", // Bitcoin sellAmount: "0.1", // 0.1 ETH providers: [ProviderName.CHAINFLIP], // Use Chainflip for cross-chain sourceAddress: swapKit.getAddress(Chain.Ethereum), destinationAddress: "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", // BTC destination });
if (!quoteResponse.success || !quoteResponse.data.routes.length) { throw new Error("No cross-chain swap routes available"); }
// Select the route const route = quoteResponse.data.routes[0];
// Execute the cross-chain swap const txHash = await swapKit.swap({ route, feeOptionKey: FeeOption.Fast, // Optional: provide maxBoostFeeBps to speed up the swap if needed });
return { txHash }; } catch (error) { throw error; }}
THORChain Swaps
Section titled “THORChain Swaps”SwapKit also supports swaps through THORChain:
// @noErrorValidationimport { Chain, FeeOption, ProviderName, SwapKitApi, SwapKit, evmWallet, keystoreWallet, ThorchainPlugin,} from "@swapkit/sdk";
// Initialize SwapKitconst swapKit = SwapKit({ plugins: { ...ThorchainPlugin }, wallets: { ...evmWallet, ...keystoreWallet },});
// Setup for THORChain swapasync function setupAndSwap() { // Connect source chain wallet (e.g., Ethereum) await swapKit.connectEVMWallet([Chain.Ethereum]);
// Connect THORChain wallet if doing a swap to RUNE await swapKit.connectKeystore([Chain.THORChain], "your secret phrase here");
// Perform a swap through THORChain try { // Get quotes from THORChain const quoteResponse = await SwapKitApi.getSwapQuote({ sellAsset: "ETH.ETH", // Ethereum buyAsset: "THOR.RUNE", // RUNE on THORChain sellAmount: "0.1", // 0.1 ETH providers: [ProviderName.THORCHAIN], // Use THORChain sourceAddress: swapKit.getAddress(Chain.Ethereum), destinationAddress: swapKit.getAddress(Chain.THORChain), });
if (!quoteResponse.success || !quoteResponse.data.routes.length) { throw new Error("No THORChain swap routes available"); }
// Select the route const route = quoteResponse.data.routes[0];
// Execute the THORChain swap const txHash = await swapKit.swap({ route, feeOptionKey: FeeOption.Fast, });
return { txHash }; } catch (error) { throw error; }}
Fee Estimation
Section titled “Fee Estimation”Before executing a swap, you can estimate the transaction fees:
// @noErrorValidationimport { AssetValue, Chain, FeeOption, SwapKitApi, SwapKit, evmWallet, EVMPlugin,} from "@swapkit/sdk";
// Initialize SwapKitconst swapKit = SwapKit({ plugins: { ...EVMPlugin }, wallets: { ...evmWallet },});
// Connect walletawait swapKit.connectEVMWallet([Chain.Ethereum]);
// Estimate swap feesasync function estimateSwapFees() { try { // 1. Get quotes const quoteResponse = await SwapKitApi.getSwapQuote({ sellAsset: "ETH.ETH", buyAsset: "ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", sellAmount: "0.1", sourceAddress: swapKit.getAddress(Chain.Ethereum), });
if (!quoteResponse.success || !quoteResponse.data.routes.length) { throw new Error("No swap routes available"); }
// 2. Select a route const route = quoteResponse.data.routes[0];
// 3. Create asset value const assetValue = await AssetValue.from({ asset: route.sellAsset, value: route.sellAmount, asyncTokenLookup: true, });
// 4. Estimate the swap fee const estimatedFee = await swapKit.estimateTransactionFee({ type: "swap", feeOptionKey: FeeOption.Fast, params: { route, assetValue, }, });
return estimatedFee; } catch (error) { throw error; }}
Advanced: Swap with Custom Parameters
Section titled “Advanced: Swap with Custom Parameters”For more advanced use cases, you can customize swap parameters:
// @noErrorValidationimport { Chain, FeeOption, ProviderName, SwapKitApi, SwapKit, evmWallet, ThorchainPlugin, ChainflipPlugin,} from "@swapkit/sdk";
// Initialize SwapKitconst swapKit = SwapKit({ plugins: { ...ThorchainPlugin, ...ChainflipPlugin }, wallets: { ...evmWallet },});
// Connect walletsawait swapKit.connectEVMWallet([Chain.Ethereum, Chain.BinanceSmartChain]);
// Advanced swap with custom parametersasync function advancedSwap() { try { // Custom quote parameters const quoteResponse = await SwapKitApi.getSwapQuote({ sellAsset: "ETH.ETH", buyAsset: "BNB.BNB", sellAmount: "0.5", // Specific providers to use providers: [ ProviderName.THORCHAIN, ProviderName.CHAINFLIP, ], // Custom addresses sourceAddress: swapKit.getAddress(Chain.Ethereum), destinationAddress: swapKit.getAddress(Chain.BinanceSmartChain), // Custom slippage tolerance (2.5%) slippage: 2.5, // Affiliate fee (optional) // affiliateBps: 20, // 0.2% fee // affiliateAddress: "thor1youraffiliateaddresshere", });
if (!quoteResponse.success || !quoteResponse.data.routes.length) { throw new Error("No advanced swap routes available"); }
// Get the best route const route = quoteResponse.data.routes[0];
// Execute the swap with custom parameters const txHash = await swapKit.swap({ route, feeOptionKey: FeeOption.Fast, // Additional Chainflip-specific parameters // maxBoostFeeBps: 5, // 0.05% max fee boost });
return { txHash }; } catch (error) { throw error; }}