Skip to content
SwapKit is a powerful suite of tools for building blockchain applications.

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.

You can use SwapKit in two ways:

  1. Granular approach - Import only what you need from individual packages (recommended for frontend):

    import { SwapKit, ThorchainPlugin, evmWallet } from "@swapkit/sdk";
  2. All-in-one approach - Import everything from the SDK (better for backend/Node.js):

    import { createSwapKit } from "@swapkit/sdk";

The typical flow for performing a swap consists of these steps:

  1. Initialize SwapKit and connect wallets
  2. Get a quote for the swap
  3. Approve tokens (if needed)
  4. Execute the swap transaction
// @noErrorValidation
import { Chain, SwapKit, evmWallet, keystoreWallet, ThorchainPlugin, EVMPlugin } from "@swapkit/sdk";
// Initialize SwapKit with necessary plugins and wallets
const 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 wallets
async 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());
}
// @noErrorValidation
import { Chain, createSwapKit } from "@swapkit/sdk";
// Initialize SwapKit with all plugins and wallets included
const swapKit = createSwapKit({
config: {
apiKeys: {
swapKit: "your-swapkit-api-key",
blockchair: "your-blockchair-api-key",
walletConnectProjectId: "your-walletconnect-project-id",
},
},
});
// Connect necessary wallets
async function connectWallets() {
// Connect wallets for the chains involved in the swap
await swapKit.connectKeystore(
[Chain.Ethereum, Chain.Bitcoin],
"your secret phrase here"
);
}

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:

// @noErrorValidation
import { SwapKitApi } from "@swapkit/helpers/api";
// Basic swap quote
async 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 provider
async 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 || [];
}

Once you have a quote, you can execute the swap:

// @noErrorValidation
import {
AssetValue,
Chain,
FeeOption,
ProviderName,
SwapKitApi,
SwapKit,
evmWallet,
EVMPlugin,
} from "@swapkit/sdk";
// Initialize SwapKit with necessary plugins and wallets
const swapKit = SwapKit({
plugins: { ...EVMPlugin },
wallets: { ...evmWallet },
});
// Connect wallet
await swapKit.connectEVMWallet([Chain.Ethereum]);
// Complete swap flow
async 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;
}
}
// @noErrorValidation
import {
AssetValue,
Chain,
FeeOption,
SwapKitApi,
createSwapKit,
} from "@swapkit/sdk";
// Initialize SwapKit
const swapKit = createSwapKit();
// Connect wallet
await swapKit.connectKeystore([Chain.Ethereum], "your secret phrase here");
// Execute swap
async 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;
}
}

SwapKit supports cross-chain swaps through Chainflip:

// @noErrorValidation
import {
Chain,
FeeOption,
ProviderName,
SwapKitApi,
SwapKit,
evmWallet,
ChainflipPlugin,
} from "@swapkit/sdk";
// Initialize SwapKit with necessary plugins
const 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 BTC
async 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;
}
}

SwapKit also supports swaps through THORChain:

// @noErrorValidation
import {
Chain,
FeeOption,
ProviderName,
SwapKitApi,
SwapKit,
evmWallet,
keystoreWallet,
ThorchainPlugin,
} from "@swapkit/sdk";
// Initialize SwapKit
const swapKit = SwapKit({
plugins: { ...ThorchainPlugin },
wallets: { ...evmWallet, ...keystoreWallet },
});
// Setup for THORChain swap
async 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;
}
}

Before executing a swap, you can estimate the transaction fees:

// @noErrorValidation
import {
AssetValue,
Chain,
FeeOption,
SwapKitApi,
SwapKit,
evmWallet,
EVMPlugin,
} from "@swapkit/sdk";
// Initialize SwapKit
const swapKit = SwapKit({
plugins: { ...EVMPlugin },
wallets: { ...evmWallet },
});
// Connect wallet
await swapKit.connectEVMWallet([Chain.Ethereum]);
// Estimate swap fees
async 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;
}
}

For more advanced use cases, you can customize swap parameters:

// @noErrorValidation
import {
Chain,
FeeOption,
ProviderName,
SwapKitApi,
SwapKit,
evmWallet,
ThorchainPlugin,
ChainflipPlugin,
} from "@swapkit/sdk";
// Initialize SwapKit
const swapKit = SwapKit({
plugins: { ...ThorchainPlugin, ...ChainflipPlugin },
wallets: { ...evmWallet },
});
// Connect wallets
await swapKit.connectEVMWallet([Chain.Ethereum, Chain.BinanceSmartChain]);
// Advanced swap with custom parameters
async 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;
}
}