API Reference
The SwapKitApi
provides access to swap quotes, price feeds, token lists, and other essential data. All methods are available through the @swapkit/helpers/api
import.
Getting Started
Section titled “Getting Started”import { SwapKitApi } from '@swapkit/helpers/api';
// All methods are static - no initialization neededconst price = await SwapKitApi.getPrice({ identifier: 'ETH.ETH', currency: 'USD'});
Swap Quotes
Section titled “Swap Quotes”getSwapQuote
Section titled “getSwapQuote”Get swap quotes from multiple providers with best route selection:
const { routes } = await SwapKitApi.getSwapQuote({ sellAsset: 'ETH.ETH', sellAmount: '1000000000000000000', // 1 ETH in base units buyAsset: 'BTC.BTC', sourceAddress: '0x...', // Your ETH address destinationAddress: 'bc1q...', // Your BTC address slippage: 3, // 3% slippage tolerance providers: ['thorchain', 'chainflip', '1inch'], // Optional: specific providers affiliate: 'your-affiliate-id', // Optional: affiliate tracking affiliateFee: 100 // Optional: basis points (100 = 1%)});
// Response structure{ routes: [{ providers: ['THORCHAIN'], sellAsset: 'ETH.ETH', sellAmount: '1000000000000000000', buyAsset: 'BTC.BTC', expectedBuyAmount: '62500000', // 0.625 BTC expectedBuyAmountMaxSlippage: '60625000', // With 3% slippage sourceAddress: '0x...', destinationAddress: 'bc1q...', targetAddress: '0x...', // Contract to send to memo: 'SWAP:BTC.BTC:bc1q...', expiration: '2024-01-01T00:00:00Z', fee: { asset: 'ETH.ETH', networkFee: '5000000000000000', // Network fee affiliateFee: '10000000000000000', // Affiliate fee totalFee: '15000000000000000' // Total fees }, estimatedTime: { inbound: 600, // 10 minutes inbound outbound: 600, // 10 minutes outbound total: 1200 // 20 minutes total } }]}
Price Data
Section titled “Price Data”getPrice
Section titled “getPrice”Get current asset prices:
// Single asset priceconst priceData = await SwapKitApi.getPrice({ identifier: 'ETH.ETH', currency: 'USD' // Optional, defaults to USD});// Returns: [{ identifier: 'ETH.ETH', price: 2500.50 }]
// Multiple assetsconst prices = await SwapKitApi.getPrice({ identifiers: ['ETH.ETH', 'BTC.BTC', 'AVAX.AVAX'], currency: 'USD'});// Returns: [// { identifier: 'ETH.ETH', price: 2500.50 },// { identifier: 'BTC.BTC', price: 45000.00 },// { identifier: 'AVAX.AVAX', price: 35.20 }// ]
// With specific token addressesconst tokenPrice = await SwapKitApi.getPrice({ identifier: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'});
Balance Operations
Section titled “Balance Operations”getChainBalance
Section titled “getChainBalance”Get all token balances for an address on a specific chain with scam filtering:
const balances = await SwapKitApi.getChainBalance({ chain: 'ETH', address: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E321', scamFilter: true // Optional, defaults to true});
// Response includes native and token balances[ { identifier: 'ETH.ETH', value: '1500000000000000000', // 1.5 ETH decimal: 18 }, { identifier: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', value: '1000000000', // 1000 USDC decimal: 6 }]
Gas Rates
Section titled “Gas Rates”getGasRate
Section titled “getGasRate”Get current gas rates for supported chains:
// Get gas rates for all chainsconst gasRates = await SwapKitApi.getGasRate();
// Response format{ ETH: { low: '20', // Gwei average: '25', // Gwei high: '30' // Gwei }, BTC: { low: '5', // Satoshis per byte average: '10', // Satoshis per byte high: '15' // Satoshis per byte }, AVAX: { low: '25', // nAVAX average: '30', // nAVAX high: '35' // nAVAX }}
Token Lists
Section titled “Token Lists”getTokenList
Section titled “getTokenList”Get comprehensive token metadata from a specific provider:
// Get tokens from a specific providerconst tokens = await SwapKitApi.getTokenList('UNISWAP_V2');
// Response structure[ { chain: 'ETH', symbol: 'USDC', ticker: 'USDC', identifier: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', decimals: 6, logoURL: 'https://...', name: 'USD Coin' }]
getTokenListProviders
Section titled “getTokenListProviders”Get list of available token list providers:
const providers = await SwapKitApi.getTokenListProviders();
// Returns available providers[ { name: '1inch', url: 'https://...' }, { name: 'coingecko', url: 'https://...' }, { name: 'uniswap', url: 'https://...' }]
Transaction Tracking
Section titled “Transaction Tracking”getTrackerDetails
Section titled “getTrackerDetails”Track transaction status and progress:
const status = await SwapKitApi.getTrackerDetails({ txHash: '0x123...', chain: 'ETH', provider: 'thorchain', // Optional: specific provider actionId: 'swap_123' // Optional: action identifier});
// Response for swap transactions{ status: 'completed', startTime: 1234567890, endTime: 1234568490, legs: [{ chain: 'ETH', hash: '0x123...', status: 'completed', inAmount: '1000000000000000000', outAmount: '62500000' }]}
Static Asset Data
Section titled “Static Asset Data”getStaticTokenList
Section titled “getStaticTokenList”Get token list from static CDN:
// Get specific token listconst tokens = await SwapKitApi.getStaticTokenList('UNISWAP_V2');
// Response contains comprehensive token data[ { chain: 'ETH', symbol: 'USDC', ticker: 'USDC', identifier: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', decimals: 6, logoURL: 'https://static.thorswap.net/token-list/images/eth.usdc.png', name: 'USD Coin' }]
getLogoForAsset
Section titled “getLogoForAsset”Get logo URL for any asset:
// Get asset logoconst logoUrl = SwapKitApi.getLogoForAsset('ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');// Returns: 'https://static.thorswap.net/token-list/images/eth.usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48.png'
// Native assetsconst ethLogo = SwapKitApi.getLogoForAsset('ETH.ETH');// Returns: 'https://static.thorswap.net/token-list/images/eth.eth.png'
getChainLogoForAsset
Section titled “getChainLogoForAsset”Get chain logo for any asset:
// Get chain logoconst chainLogo = SwapKitApi.getChainLogoForAsset('ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');// Returns: 'https://static.thorswap.net/token-list/images/eth.png'
getProviderLogo
Section titled “getProviderLogo”Get logo URL for token list providers:
const providerLogo = await SwapKitApi.getProviderLogo('1inch');// Returns: 'https://...'
Provider-Specific APIs
Section titled “Provider-Specific APIs”Microgard API
Section titled “Microgard API”Access THORChain microgard services:
// Get THORName detailsconst thorname = await SwapKitApi.microgard.getTHORNameDetails('myname');
// Get THORNames by ownerconst names = await SwapKitApi.microgard.getTHORNamesByOwner('thor1...');
// Get THORNames by addressconst names = await SwapKitApi.microgard.getTHORNamesByAddress('0x...');
// Get THORChain poolsconst pools = await SwapKitApi.microgard.getTHORChainPools('7d'); // '1h', '24h', '7d', '30d', '365d'
// Get liquidity positionsconst positions = await SwapKitApi.microgard.getLiquidityPositions(['thor1...', 'thor2...']);
// Get TNS chain addressconst address = await SwapKitApi.microgard.getTNSChainAddress({ chain: 'ETH', tns: 'myname'});
THORNode API
Section titled “THORNode API”Direct access to THORChain node data:
// Get last blockconst lastBlock = await SwapKitApi.thornode.getLastBlock('thorchain'); // or 'mayachain'
// Get THORChain queueconst queue = await SwapKitApi.thornode.getThorchainQueue();
// Get node listconst nodes = await SwapKitApi.thornode.getNodes();
// Get Mimir settingsconst mimir = await SwapKitApi.thornode.getMimirInfo();
// Get inbound addressesconst inboundAddresses = await SwapKitApi.thornode.getInboundAddresses();
// Get THORNode TNS detailsconst tnsDetails = await SwapKitApi.thornode.getTHORNodeTNSDetails({ name: 'myname', type: 'thorchain' // or 'mayachain'});
// Get TNS preferred assetconst preferredAsset = await SwapKitApi.thornode.getTNSPreferredAsset({ tns: 'myname', type: 'thorchain'});
// Get RUNEPool infoconst runePool = await SwapKitApi.thornode.getRunePoolInfo();
// Get RUNEPool provider infoconst providerInfo = await SwapKitApi.thornode.getRunePoolProviderInfo({ thorAddress: 'thor1...'});
Midgard APIs
Section titled “Midgard APIs”Access THORChain and Maya midgard data:
// THORChain Midgard// Get liquidity positionconst thorLiquidity = await SwapKitApi.thorchainMidgard.getLiquidityPosition('thor1...');
// Get THORName detailsconst thorName = await SwapKitApi.thorchainMidgard.getNameDetails('myname');
// Get THORNames by addressconst namesByAddress = await SwapKitApi.thorchainMidgard.getNamesByAddress('0x...');
// Get THORNames by ownerconst namesByOwner = await SwapKitApi.thorchainMidgard.getNamesByOwner('thor1...');
// Maya Midgard - same methods availableconst mayaLiquidity = await SwapKitApi.mayachainMidgard.getLiquidityPosition('maya1...');const mayaName = await SwapKitApi.mayachainMidgard.getNameDetails('myname');
Chainflip
Section titled “Chainflip”Create deposit channels for Chainflip swaps:
const channel = await SwapKitApi.getChainflipDepositChannel({ sellAsset: { chain: 'ETH', asset: 'ETH' }, buyAsset: { chain: 'BTC', asset: 'BTC' }, destinationAddress: 'bc1q...', brokerCommissionBps: 100, // Optional: 1% commission affiliateFees: [ // Optional: affiliate fees { brokerAddress: '0x...', feeBps: 50 } ], channelMetadata: { // Optional: additional parameters cfParameters: '...', gasBudget: '1000000', message: 'Swap via SwapKit' }, refundParameters: { // Optional: refund settings minPrice: '0.01', refundAddress: '0x...', retryDuration: 3600 }, dcaParameters: { // Optional: DCA settings numberOfChunks: 10, chunkInterval: 600 }, maxBoostFeeBps: 200 // Optional: max boost fee});
// Response{ depositChannelId: '123456', depositAddress: '0x...', // Send funds here brokerCommissionBps: 100, estimatedExpiryTime: 1234567890, expiryBlock: 123456, issuedBlock: 123400, sourceChainExpiryBlock: 234567}
Rate Limits
Section titled “Rate Limits”The SwapKit API has rate limits that vary by endpoint:
- Without API key: 10 requests per minute
- With API key: 100 requests per minute
Configure your API key in Configuration:
import { createSwapKit } from '@swapkit/sdk';
const swapKit = createSwapKit({ config: { apiKeys: { swapKit: 'your-api-key' } }});
Error Handling
Section titled “Error Handling”All API methods can throw errors that should be handled:
import { SwapKitError } from '@swapkit/sdk';
try { const quote = await SwapKitApi.getSwapQuote({...});} catch (error) { if (error instanceof SwapKitError) { // Handle SwapKit-specific errors console.error('API Error:', error.message);
// Check for rate limiting if (error.code === 'api_rate_limit') { // Wait and retry } }}
Common Patterns
Section titled “Common Patterns”Best Route Selection
Section titled “Best Route Selection”When getting swap quotes, the first route is typically the best:
import { AssetValue } from '@swapkit/sdk';
const { routes } = await SwapKitApi.getSwapQuote({...});
if (routes.length > 0) { const bestRoute = routes[0];
// Check if route meets your requirements const minOutput = AssetValue.from({ asset: bestRoute.buyAsset, value: bestRoute.expectedBuyAmountMaxSlippage, fromBaseDecimal: true });
if (minOutput.gte(requiredAmount)) { await swapKit.swap({ route: bestRoute }); }}
Price Impact Calculation
Section titled “Price Impact Calculation”Calculate price impact for large swaps:
const quote = await SwapKitApi.getSwapQuote({...});const route = quote.routes[0];
// Get current pricesconst sellPrice = await SwapKitApi.getPrice(route.sellAsset);const buyPrice = await SwapKitApi.getPrice(route.buyAsset);
// Calculate expected valueconst sellValue = Number(route.sellAmount) * sellPrice;const buyValue = Number(route.expectedBuyAmount) * buyPrice;
// Calculate price impactconst priceImpact = ((sellValue - buyValue) / sellValue) * 100;console.log(`Price impact: ${priceImpact.toFixed(2)}%`);
Token Validation
Section titled “Token Validation”Validate tokens before swapping:
async function validateToken(identifier: string) { try { const token = await SwapKitApi.getTokenList(identifier); return { valid: true, decimals: token.decimals, name: token.name, logo: token.logoURL }; } catch { return { valid: false }; }}
Configuration Management
Section titled “Configuration Management”SKConfig API
Section titled “SKConfig API”The SKConfig
API provides methods to manage SwapKit’s configuration at runtime. This includes RPC URLs, API keys, custom headers, and environment settings:
Core Methods
Section titled “Core Methods”import { SKConfig } from '@swapkit/sdk';
// Get configuration valuesconst rpcUrls = SKConfig.get('rpcUrls');const apiKeys = SKConfig.get('apiKeys');const midgardUrls = SKConfig.get('midgardUrls');const apiHeaders = SKConfig.get('apiHeaders');
// Set complete configurationSKConfig.set({ rpcUrls: { ETH: 'https://new-rpc.com' }, apiKeys: { swapKit: 'new-key' }, midgardUrls: { THOR: 'https://custom-midgard.com' }, apiHeaders: { midgard: { 'X-API-Key': 'secret' } }});
API Keys
Section titled “API Keys”// Set individual API keysSKConfig.setApiKey('swapKit', 'your-swapkit-key');SKConfig.setApiKey('blockchair', 'your-blockchair-key');SKConfig.setApiKey('walletConnectProjectId', 'your-wc-id');
RPC URLs
Section titled “RPC URLs”import { Chain } from '@swapkit/sdk';
// Set RPC URL for specific chainSKConfig.setRpcUrl(Chain.Ethereum, 'https://eth-mainnet.g.alchemy.com/v2/key');SKConfig.setRpcUrl(Chain.Avalanche, 'https://api.avax.network/ext/bc/C/rpc');
Midgard URLs
Section titled “Midgard URLs”import { Chain } from '@swapkit/sdk';
// Set custom Midgard URLsSKConfig.setMidgardUrl(Chain.THORChain, 'https://custom-midgard.com');SKConfig.setMidgardUrl(Chain.Maya, 'https://maya-midgard.com');
// Note: When isStagenet is true, SwapKit automatically uses stagenet URLs:// - THORChain: https://stagenet-midgard.ninerealms.com// - Maya: https://stagenet-midgard.mayachain.info
API Headers
Section titled “API Headers”// Set headers for specific APIsSKConfig.setApiHeaders('midgard', { 'X-Client-ID': 'your-client-id'});
// Headers for THORNode APISKConfig.setApiHeaders('thornode', { 'X-Client-ID': 'your-client-id'});
// Headers for SwapKit API (in addition to automatic x-api-key)SKConfig.setApiHeaders('swapkitApi', { 'X-API-Key': 'additional-api-key'});
Environment Settings
Section titled “Environment Settings”// Set environment flagsSKConfig.setEnv('isDev', true);SKConfig.setEnv('isStagenet', true);
// API URLsSKConfig.setEnv('apiUrl', 'https://api.swapkit.dev');SKConfig.setEnv('devApiUrl', 'https://dev-api.swapkit.dev');
Integration Configurations
Section titled “Integration Configurations”// Radix configurationSKConfig.setIntegrationConfig('radix', { dAppDefinitionAddress: 'account_rdx...', applicationName: 'My dApp', applicationVersion: '1.0.0', network: { networkId: 1, networkName: 'mainnet', dashboardBase: 'https://dashboard.radixdlt.com' }});
// Chainflip configurationSKConfig.setIntegrationConfig('chainflip', { useSDKBroker: true, brokerUrl: 'https://broker.chainflip.io'});
Explorer URLs
Section titled “Explorer URLs”// Set custom explorer URLsSKConfig.setExplorerUrl(Chain.Ethereum, 'https://etherscan.io');SKConfig.setExplorerUrl(Chain.Bitcoin, 'https://blockstream.info');
Complete Example
Section titled “Complete Example”import { SKConfig, Chain, StagenetChain } from '@swapkit/sdk';
// Configure multiple settings at onceSKConfig.set({ apiKeys: { swapKit: process.env.SWAPKIT_API_KEY, blockchair: process.env.BLOCKCHAIR_API_KEY }, rpcUrls: { [Chain.Ethereum]: 'https://eth-mainnet.g.alchemy.com/v2/key', [Chain.Polygon]: 'https://polygon-rpc.com' }, midgardUrls: { [Chain.THORChain]: 'https://private-midgard.com', [StagenetChain.THORChain]: 'https://stagenet-midgard.com' }, apiHeaders: { midgard: { 'X-Client-ID': process.env.CLIENT_ID }, thornode: { 'X-Client-ID': process.env.CLIENT_ID } }, envs: { isDev: process.env.NODE_ENV === 'development', isStagenet: false }});
// Later, update individual settingsif (userPrefersTestnet) { SKConfig.setEnv('isStagenet', true); // Midgard URLs automatically switch to stagenet when isStagenet is true}
Fee Multiplier System
Section titled “Fee Multiplier System”SwapKit provides a unified fee multiplier system across all chains:
import { FeeOption, getFeeMultiplier } from '@swapkit/sdk';
// Get fee multiplier for different optionsconst slowMultiplier = getFeeMultiplier(FeeOption.Slow); // 0.75xconst avgMultiplier = getFeeMultiplier(FeeOption.Average); // 1x (default)const fastMultiplier = getFeeMultiplier(FeeOption.Fast); // 1.5xconst fastestMultiplier = getFeeMultiplier(FeeOption.Fastest); // 2.25x
// Apply to fee calculationsconst baseFee = 1000000; // Base fee in smallest unitconst fastFee = Math.floor(baseFee * getFeeMultiplier(FeeOption.Fast));
// Use in transfersawait wallet.transfer({ recipient: "0x...", assetValue: AssetValue.from({ chain: Chain.Ethereum, value: "1" }), feeOptionKey: FeeOption.Fast // Automatically applies 1.5x multiplier});
Key Features
Section titled “Key Features”- Automatic Stagenet Support: When
isStagenet
is true, appropriate stagenet URLs are used automatically - Custom Headers: Set authentication headers for Midgard, THORNode, and SwapKit APIs
- Runtime Updates: All configuration can be updated dynamically without recreating SwapKit instances
- Environment-Based Config: Easily switch between development, staging, and production environments
- Unified Fee System: Consistent fee multipliers across all supported chains
Next Steps
Section titled “Next Steps”- Implement Cross-Chain Swaps using the quote API
- Set up Transaction Tracking for better UX
- Explore THORChain Features for advanced DeFi