Configuration
SwapKit uses a centralized configuration system called SKConfig
that manages all settings across toolboxes, plugins, and integrations. This guide covers how to configure SwapKit for your application.
Configuration Overview
Section titled “Configuration Overview”SwapKit’s configuration is managed through the SKConfig
store, which handles:
- RPC URLs for blockchain connections
- API keys for external services
- Environment settings
- Integration configurations
- Custom API implementations
- Midgard API URLs for THORChain/Maya
- Custom API headers for authentication
Basic Configuration
Section titled “Basic Configuration”When creating a SwapKit instance, you can provide configuration options:
import { createSwapKit } from '@swapkit/sdk';
const swapKit = createSwapKit({ config: { // API keys for various services apiKeys: { walletConnectProjectId: 'your-project-id', blockchair: 'your-blockchair-key', swapKit: 'your-swapkit-key' }, // Custom RPC URLs (optional) rpcUrls: { ETH: 'https://eth-mainnet.g.alchemy.com/v2/your-key', AVAX: 'https://api.avax.network/ext/bc/C/rpc' }, // Custom Midgard URLs (optional) midgardUrls: { THOR: 'https://custom-midgard.com', MAYA: 'https://custom-maya-midgard.com' }, // Custom API headers for authentication apiHeaders: { midgard: { 'Authorization': 'Bearer your-token', 'X-Custom-Header': 'custom-value' } } }});
API Keys
Section titled “API Keys”SwapKit API Key
Section titled “SwapKit API Key”The SwapKit API key unlocks enhanced features:
- Higher rate limits
- Advanced swap routes
- Priority support
Get your key at api.swapkit.dev
apiKeys: { swapKit: 'your-swapkit-api-key'}
WalletConnect Project ID
Section titled “WalletConnect Project ID”Required for WalletConnect v2 integration:
apiKeys: { walletConnectProjectId: 'your-project-id'}
Get your project ID at cloud.walletconnect.com
Blockchair API Key
Section titled “Blockchair API Key”Enables full functionality for UTXO chains (Bitcoin, Litecoin, Dogecoin, etc.):
apiKeys: { blockchair: 'your-blockchair-key'}
Without this key, UTXO chain functionality is limited. Get your key at blockchair.com/api
RPC URLs
Section titled “RPC URLs”SwapKit provides default RPC URLs for all supported chains, but you can override them:
import { createSwapKit, Chain } from '@swapkit/sdk';
const swapKit = createSwapKit({ config: { rpcUrls: { [Chain.Ethereum]: 'https://eth-mainnet.g.alchemy.com/v2/your-key', [Chain.Avalanche]: 'https://api.avax.network/ext/bc/C/rpc', [Chain.BinanceSmartChain]: 'https://bsc-dataseed.binance.org/', [Chain.Polygon]: 'https://polygon-rpc.com' } }});
Midgard API Configuration
Section titled “Midgard API Configuration”Midgard provides historical data and liquidity information for THORChain and Maya. SwapKit allows you to configure custom Midgard endpoints and authentication headers.
Custom Midgard URLs
Section titled “Custom Midgard URLs”Override the default Midgard endpoints:
import { createSwapKit, Chain } from '@swapkit/sdk';
const swapKit = createSwapKit({ config: { midgardUrls: { [Chain.THORChain]: 'https://your-midgard.com', [Chain.Maya]: 'https://your-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// You can override these by setting stagenet-specific URLs in midgardUrls
API Headers for Authentication
Section titled “API Headers for Authentication”Add custom headers for Midgard API authentication:
import { SKConfig } from '@swapkit/sdk';
// Set headers for Midgard APIsSKConfig.setApiHeaders('midgard', { 'X-Client-ID': 'your-client-id'});
// Headers can also be set during initializationconst swapKit = createSwapKit({ config: { apiHeaders: { midgard: { 'X-Client-ID': 'your-client-id' }, thornode: { 'X-Client-ID': 'your-client-id' }, swapkitApi: { 'X-API-Key': 'additional-api-key' // Note: x-api-key is automatically added from apiKeys.swapKit } } }});
Runtime Updates
Section titled “Runtime Updates”Update Midgard configuration at runtime:
import { SKConfig, Chain } from '@swapkit/sdk';
// Update a specific Midgard URLSKConfig.setMidgardUrl(Chain.THORChain, 'https://new-midgard-url.com');
// Update Midgard headersSKConfig.setApiHeaders('midgard', { 'X-Client-ID': 'new-client-id'});
// Get current Midgard configurationconst midgardUrls = SKConfig.get('midgardUrls');const apiHeaders = SKConfig.get('apiHeaders');
API Headers Configuration
Section titled “API Headers Configuration”SwapKit supports custom headers for all API endpoints (Midgard, THORNode, and SwapKit API). This is useful for:
- Authentication with private API instances
- Custom client identification
- Additional API key management
Supported APIs
Section titled “Supported APIs”- Midgard API (
midgard
): Historical data and liquidity information - THORNode API (
thornode
): Direct blockchain node access - SwapKit API (
swapkitApi
): Swap quotes, prices, and token data
Setting Headers
Section titled “Setting Headers”import { SKConfig } from '@swapkit/sdk';
// Set headers for all APIsSKConfig.set({ apiHeaders: { midgard: { 'X-Client-ID': 'your-client-id' }, thornode: { 'X-Client-ID': 'your-client-id' }, swapkitApi: { 'X-API-Key': 'additional-api-key' } }});
// Or set headers for individual APIsSKConfig.setApiHeaders('midgard', { 'X-Client-ID': 'new-client-id'});
Common Use Cases
Section titled “Common Use Cases”Private Instance Access
Section titled “Private Instance Access”// Use your private Midgard instanceSKConfig.setMidgardUrl(Chain.THORChain, 'https://your-midgard.com');SKConfig.setApiHeaders('midgard', { 'X-Client-ID': 'your-client-id'});
// Access your private THORNodeSKConfig.setApiHeaders('thornode', { 'X-Client-ID': 'your-client-id'});
Additional API Keys
Section titled “Additional API Keys”// Add additional API key for SwapKit API// Note: The primary API key is still set via apiKeys.swapKitSKConfig.setApiHeaders('swapkitApi', { 'X-API-Key': 'secondary-api-key'});
Runtime Configuration
Section titled “Runtime Configuration”You can update configuration after initialization using SKConfig
:
import { SKConfig, Chain } from '@swapkit/sdk';
// Update a specific RPC URLSKConfig.setRpcUrl(Chain.Ethereum, 'https://new-rpc-url.com');
// Update an API keySKConfig.setApiKey('blockchair', 'new-api-key');
// Update environment settingsSKConfig.setEnv('isStagenet', true);
// Get current configurationconst currentRpcUrl = SKConfig.get('rpcUrls')[Chain.Ethereum];const apiKeys = SKConfig.get('apiKeys');
Environment Settings
Section titled “Environment Settings”Control SwapKit’s behavior with environment flags:
const swapKit = createSwapKit({ config: { envs: { // Use development API endpoints isDev: true, // Use testnet/stagenet for THORChain/Maya isStagenet: true } }});
Integration Configurations
Section titled “Integration Configurations”Radix Wallet
Section titled “Radix Wallet”For Radix dApp integration:
SKConfig.setIntegrationConfig('radix', { dAppDefinitionAddress: 'account_rdx...', applicationName: 'My dApp', applicationVersion: '1.0.0', network: { networkId: 1, // 1 for mainnet, 2 for testnet networkName: 'mainnet' }});
Chainflip Broker
Section titled “Chainflip Broker”Configure Chainflip integration:
SKConfig.setIntegrationConfig('chainflip', { useSDKBroker: true, brokerUrl: 'https://your-broker-url.com'});
Custom API Implementations
Section titled “Custom API Implementations”Provide custom API implementations for specific chains:
import { Chain } from '@swapkit/sdk';
// Custom Bitcoin API implementationconst customBitcoinApi = { getBalance: async (address: string) => { // Your custom implementation }, getTransactionData: async (txId: string) => { // Your custom implementation }, // ... other required methods};
SKConfig.set({ apis: { [Chain.Bitcoin]: customBitcoinApi }});
Configuration Best Practices
Section titled “Configuration Best Practices”1. Use Environment Variables
Section titled “1. Use Environment Variables”const swapKit = createSwapKit({ config: { apiKeys: { walletConnectProjectId: process.env.WALLETCONNECT_PROJECT_ID, blockchair: process.env.BLOCKCHAIR_API_KEY, swapKit: process.env.SWAPKIT_API_KEY } }});
2. Configure by Environment
Section titled “2. Configure by Environment”const isDevelopment = process.env.NODE_ENV === 'development';
const swapKit = createSwapKit({ config: { envs: { isDev: isDevelopment, isStagenet: isDevelopment }, rpcUrls: isDevelopment ? { ETH: 'https://eth-goerli.g.alchemy.com/v2/your-key' } : { ETH: 'https://eth-mainnet.g.alchemy.com/v2/your-key' } }});
3. Chain-Specific Configuration
Section titled “3. Chain-Specific Configuration”// Configure multiple EVM chains at onceconst evmChains = [Chain.Ethereum, Chain.Avalanche, Chain.Polygon];const evmRpcUrls = evmChains.reduce((acc, chain) => ({ ...acc, [chain]: `https://rpc.example.com/${chain.toLowerCase()}`}), {});
SKConfig.set({ rpcUrls: evmRpcUrls });
// Configure Cosmos chain RPCsSKConfig.setRpcUrl(Chain.Cosmos, 'https://cosmos-rpc.quickapi.com');SKConfig.setRpcUrl(Chain.THORChain, 'https://thornode.thorswap.net');SKConfig.setRpcUrl(Chain.Kujira, 'https://rpc.kaiyo.kujira.setten.io');
// UTXO chains require Blockchair API keyif (!SKConfig.get('apiKeys').blockchair) { console.warn('Blockchair API key not found. UTXO chain functionality will be limited.');}
Complete Example
Section titled “Complete Example”Here’s a production-ready configuration example:
import { createSwapKit, SKConfig, Chain } from '@swapkit/sdk';
// Load environment variablesconst config = { // API Keys apiKeys: { walletConnectProjectId: process.env.WALLETCONNECT_PROJECT_ID!, blockchair: process.env.BLOCKCHAIR_API_KEY, swapKit: process.env.SWAPKIT_API_KEY },
// Environment settings envs: { isDev: process.env.NODE_ENV === 'development', isStagenet: process.env.USE_TESTNET === 'true' },
// Custom RPC URLs for better performance rpcUrls: { [Chain.Ethereum]: process.env.ETH_RPC_URL || 'https://eth.llamarpc.com', [Chain.Avalanche]: process.env.AVAX_RPC_URL || 'https://api.avax.network/ext/bc/C/rpc', [Chain.BinanceSmartChain]: process.env.BSC_RPC_URL || 'https://bsc-dataseed.binance.org' },
// Custom Midgard URLs if using private instances // Note: Stagenet URLs are automatically used when isStagenet is true midgardUrls: process.env.MIDGARD_URL ? { [Chain.THORChain]: process.env.MIDGARD_URL, [Chain.Maya]: process.env.MAYA_MIDGARD_URL || process.env.MIDGARD_URL } : undefined,
// API headers for authenticated endpoints apiHeaders: { midgard: process.env.CLIENT_ID ? { 'X-Client-ID': process.env.CLIENT_ID } : undefined, thornode: process.env.CLIENT_ID ? { 'X-Client-ID': process.env.CLIENT_ID } : undefined, swapkitApi: process.env.ADDITIONAL_API_KEY ? { 'X-API-Key': process.env.ADDITIONAL_API_KEY } : undefined }};
// Initialize SwapKitconst swapKit = createSwapKit({ config });
// Runtime updates based on user preferencesif (userPrefersFastNode) { SKConfig.setRpcUrl(Chain.Ethereum, 'https://premium-eth-rpc.com');}
// Configure Radix if neededif (userHasRadixWallet) { SKConfig.setIntegrationConfig('radix', { dAppDefinitionAddress: process.env.RADIX_DAPP_ADDRESS!, applicationName: 'My SwapKit App', applicationVersion: '1.0.0', network: { networkId: config.envs.isStagenet ? 2 : 1, networkName: config.envs.isStagenet ? 'testnet' : 'mainnet' } });}
Troubleshooting
Section titled “Troubleshooting”RPC Connection Issues
Section titled “RPC Connection Issues”If you’re experiencing connection issues:
// Check current RPC URLconst currentRpc = SKConfig.get('rpcUrls')[Chain.Ethereum];console.log('Current Ethereum RPC:', currentRpc);
// Test with a different RPCSKConfig.setRpcUrl(Chain.Ethereum, 'https://cloudflare-eth.com');
API Key Validation
Section titled “API Key Validation”Verify your API keys are working:
import { SwapKitApi } from '@swapkit/sdk';
// Test SwapKit API keytry { const price = await SwapKitApi.getPrice('ETH'); console.log('SwapKit API key is valid');} catch (error) { console.error('SwapKit API key issue:', error);}
Next Steps
Section titled “Next Steps”Now that you understand configuration:
- Learn about Core Concepts like AssetValue and error handling
- Explore Toolbox Usage for chain-specific operations
- Start Connecting Wallets to your app