Getting Started with SwapKit
SwapKit is a comprehensive SDK that unifies blockchain interactions across 20+ chains. This guide will walk you through installation, setup, and building your first cross-chain application.
Prerequisites
Section titled “Prerequisites”Before starting, ensure you have:
- Node.js 18+ or Bun installed
- Basic knowledge of JavaScript/TypeScript
- A code editor (VS Code recommended)
Installation
Section titled “Installation”bun add @swapkit/sdk
pnpm add @swapkit/sdk
npm install @swapkit/sdk
yarn add @swapkit/sdk
Basic Setup
Section titled “Basic Setup”1. Import and Initialize SwapKit
Section titled “1. Import and Initialize SwapKit”// @noErrorValidationimport { createSwapKit } from '@swapkit/sdk';
// Create a SwapKit instance with default configurationconst swapKit = createSwapKit();
2. Configure SwapKit (Optional)
Section titled “2. Configure SwapKit (Optional)”For production applications, you’ll want to add your own API keys and custom settings. See our Configuration Guide for detailed setup:
// @noErrorValidationimport { createSwapKit } from '@swapkit/sdk';
const swapKit = createSwapKit({ config: { apiKeys: { walletConnectProjectId: 'your-project-id', // Get from cloud.walletconnect.com blockchair: 'your-blockchair-key', // Get from blockchair.com/api swapKit: 'your-swapkit-key', // Get from api.swapkit.dev }, rpcUrls: { ETH: 'https://eth-mainnet.g.alchemy.com/v2/your-key', AVAX: 'https://api.avax.network/ext/bc/C/rpc', } }});
Core Concepts
Section titled “Core Concepts”SwapKit has several fundamental concepts you should understand. For a detailed explanation, see our Core Concepts guide.
1. Chains
Section titled “1. Chains”SwapKit supports 20+ blockchain networks with a unified Chain identifier system:
// @noErrorValidationimport { Chain } from '@swapkit/sdk';
// Examples of supported chainsconst ethereum = Chain.Ethereum; // "ETH"const bitcoin = Chain.Bitcoin; // "BTC"const cosmos = Chain.Cosmos; // "GAIA"const thorchain = Chain.THORChain; // "THOR"
2. AssetValue
Section titled “2. AssetValue”AssetValue is SwapKit’s way of representing amounts of any asset:
// @noErrorValidationimport { AssetValue } from '@swapkit/sdk';
// Native assetsconst eth = AssetValue.from({ asset: 'ETH.ETH', value: 1 }); // 1 ETHconst btc = AssetValue.from({ asset: 'BTC.BTC', value: 0.1 }); // 0.1 BTC
// Tokens include the contract addressconst usdc = AssetValue.from({ asset: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', value: 1000}); // 1000 USDC on Ethereum
3. Wallets
Section titled “3. Wallets”SwapKit supports 20+ wallet types:
// @noErrorValidationimport { WalletOption } from '@swapkit/sdk';
// Browser extension walletsconst metamask = WalletOption.METAMASK;const keplr = WalletOption.KEPLR;
// Hardware walletsconst ledger = WalletOption.LEDGER;
// Software walletsconst keystore = WalletOption.KEYSTORE;
Common Use Cases
Section titled “Common Use Cases”Connect a Wallet
Section titled “Connect a Wallet”// @noErrorValidationimport { createSwapKit, Chain, WalletOption } from '@swapkit/sdk';
const swapKit = createSwapKit();
// Connect Keystore wallet (mnemonic phrase)await swapKit.connectKeystore( [Chain.Ethereum, Chain.Bitcoin], 'your twelve word mnemonic phrase here');
// Connect MetaMask (EVM chains only)await swapKit.connectEVMWallet([Chain.Ethereum], WalletOption.METAMASK);
// Connect Keplr (Cosmos chains)await swapKit.connectKeplr([Chain.Cosmos, Chain.THORChain]);
// Connect Cosmostation (Cosmos chains)await swapKit.connectCosmostation([Chain.Cosmos, Chain.THORChain]);
// Get all connected walletsconst wallets = swapKit.getAllWallets();
Get Wallet Balances
Section titled “Get Wallet Balances”// @noErrorValidationimport { createSwapKit, Chain } from '@swapkit/sdk';
const swapKit = createSwapKit();
// Get balance for a specific chainconst ethBalance = await swapKit.getBalance(Chain.Ethereum);const btcBalance = await swapKit.getBalance(Chain.Bitcoin);
// Force refresh balance (bypass cache)const freshBalance = await swapKit.getBalance(Chain.Ethereum, true);
// Get wallet with balanceconst walletWithBalance = await swapKit.getWalletWithBalance(Chain.Ethereum);console.log(`Address: ${walletWithBalance.address}`);console.log(`Balance: ${walletWithBalance.balance}`);
Perform a Swap
Section titled “Perform a Swap”Use the SwapKit API to get quotes and execute swaps:
// @noErrorValidationimport { createSwapKit, Chain, FeeOption, SwapKitApi } from '@swapkit/sdk';
const swapKit = createSwapKit();
// Step 1: Get a quoteconst quoteParams = { sellAsset: 'ETH.ETH', sellAmount: '1000000000000000000', // 1 ETH in wei buyAsset: 'BTC.BTC', sourceAddress: swapKit.getAddress(Chain.Ethereum), destinationAddress: swapKit.getAddress(Chain.Bitcoin), slippage: 3, // 3% slippage tolerance};
const { routes } = await SwapKitApi.getSwapQuote(quoteParams);
// Step 2: Review the quoteconst bestRoute = routes[0];console.log(`Expected output: ${bestRoute.expectedBuyAmount}`);console.log(`Fees:`, bestRoute.fee);
// Step 3: Execute the swapconst txHash = await swapKit.swap({ route: bestRoute, feeOptionKey: FeeOption.Fast});
console.log(`Swap transaction: ${txHash}`);
Send Transactions
Section titled “Send Transactions”// @noErrorValidationimport { createSwapKit, AssetValue, FeeOption, Chain } from '@swapkit/sdk';
const swapKit = createSwapKit();
// Simple ETH transferconst ethAmount = AssetValue.from({ asset: 'ETH.ETH', value: '0.1' });
const txHash = await swapKit.transfer({ assetValue: ethAmount, recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E321', memo: 'Payment for services', // Optional feeOptionKey: FeeOption.Fast});
// Bitcoin transfer with custom feeconst btcAmount = AssetValue.from({ asset: 'BTC.BTC', value: '0.001' });
const btcTxHash = await swapKit.transfer({ assetValue: btcAmount, recipient: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', feeOptionKey: FeeOption.Average});
// Ripple (XRP) transferconst xrpAmount = AssetValue.from({ asset: 'XRP.XRP', value: '10' });
const xrpTxHash = await swapKit.transfer({ assetValue: xrpAmount, recipient: 'rBaaxNpAKxELKXkJpSCCJQTkQMTYrcPQPv', memo: 'Invoice #12345', // Optional destination tag or memo feeOptionKey: FeeOption.Fast});
Advanced Usage
Section titled “Advanced Usage”Using Core + Plugins (Modular Approach)
Section titled “Using Core + Plugins (Modular Approach)”For smaller bundle sizes, use only the components you need:
// @noErrorValidationimport { SwapKit, ThorchainPlugin, keystoreWallet, ledgerWallet } from '@swapkit/sdk';
const swapKit = SwapKit({ plugins: { ...ThorchainPlugin, }, wallets: { ...keystoreWallet, ...ledgerWallet, },});
Direct Toolbox Usage
Section titled “Direct Toolbox Usage”For low-level blockchain operations:
// @noErrorValidationimport { getToolbox, Chain } from '@swapkit/sdk';
const address = 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh';const btcToolbox = getToolbox(Chain.Bitcoin);
const isValid = btcToolbox.validateAddress(address);
const balance = await btcToolbox.getBalance(address);
Custom Plugin Development
Section titled “Custom Plugin Development”Create your own plugin to extend SwapKit:
// @noErrorValidationimport { SwapKit } from '@swapkit/sdk';
const MyCustomPlugin = { myCustomMethod: async (params: any) => { // Your custom logic here return { success: true }; },
// Add custom functionality getCustomData: async () => { console.log('Fetching custom data'); return { data: 'custom-data' }; }};
const swapKit = SwapKit({ plugins: { ...MyCustomPlugin, },});
// Use your custom methodawait swapKit.myCustomMethod({ customParam: 'value' });await swapKit.getCustomData();
Error Handling
Section titled “Error Handling”SwapKit uses typed errors for better debugging:
// @noErrorValidationimport { createSwapKit, SwapKitError, FeeOption } from '@swapkit/sdk';
const swapKit = createSwapKit();
try { // Example: attempting a swap with a route object const route = { sellAsset: 'ETH.ETH', buyAsset: 'BTC.BTC', expectedBuyAmount: '0.001', // ... other route properties }; await swapKit.swap({ route, feeOptionKey: FeeOption.Fast });} catch (error) { if (error instanceof SwapKitError) { console.error('SwapKit Error:', error.message); // Error may have additional properties console.error('Full error:', error); } else { console.error('Unexpected error:', error); }}
Next Steps
Section titled “Next Steps”Now that you understand the basics:
Essential Reading
Section titled “Essential Reading”- Core Concepts - Master AssetValue, error handling, and types
- Configuration - Set up API keys and customize settings
- API Reference - Explore all available API methods
Build Your Application
Section titled “Build Your Application”- Connect Wallets - Deep dive into wallet integration
- Perform Swaps - Implement cross-chain swaps
- Send Transactions - Handle transfers and tracking
Advanced Topics
Section titled “Advanced Topics”- THORChain Features - Liquidity, and THORNames
- Advanced Features - Multi-chain ops and synthetics
- Toolbox Usage - Direct blockchain operations
Extend SwapKit
Section titled “Extend SwapKit”- Create Custom Plugin - Add new protocols
- Create Custom Wallet - Integrate new wallets
- Framework Integration - Use with Next.js, Vite, etc.
Need Help?
Section titled “Need Help?”- 💬 Join our Discord for community support
- 🐛 Report issues on GitHub
- 📚 Browse the API Reference for detailed documentation
Happy building with SwapKit! 🚀