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

Getting Started with SwapDK

SwapDK 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.

Before starting, ensure you have:

  • Node.js 18+ or Bun installed
  • Basic knowledge of JavaScript/TypeScript
  • A code editor (VS Code recommended)
Terminal window
bun add @swapdk/sdk
// @noErrorValidation
import { createSwapKit } from "@swapdk/sdk";
const swapDK = createSwapKit();

Try SwapDK Now

Jump into a live environment and experiment with SwapDK right away

For production applications, you’ll want to add your own API keys and custom settings. See our Configuration Guide for detailed setup:

// @noErrorValidation
import { createSwapKit } from "@swapdk/sdk";
const swapDK = createSwapKit({
config: {
apiKeys: {
walletConnectProjectId: "your-project-id",
blockchair: "your-blockchair-key",
swapKit: "your-swapdk-key",
},
rpcUrls: {
ETH: "https://eth-mainnet.g.alchemy.com/v2/your-key",
AVAX: "https://api.avax.network/ext/bc/C/rpc",
},
},
});

SwapDK has several fundamental concepts you should understand. For a detailed explanation, see our Core Concepts guide.

SwapDK supports 20+ blockchain networks with a unified Chain identifier system:

// @noErrorValidation
import { Chain } from "@swapdk/sdk";
const ethereum = Chain.Ethereum;
const bitcoin = Chain.Bitcoin;
const cosmos = Chain.Cosmos;
const thorchain = Chain.THORChain;

AssetValue is SwapDK’s way of representing amounts of any asset:

// @noErrorValidation
import { AssetValue } from "@swapdk/sdk";
const eth = AssetValue.from({ asset: "ETH.ETH", value: 1 });
const btc = AssetValue.from({ asset: "BTC.BTC", value: 0.1 });
const usdc = AssetValue.from({
asset: "ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
value: 1000,
});

SwapDK supports 20+ wallet types:

// @noErrorValidation
import { WalletOption } from "@swapdk/sdk";
const metamask = WalletOption.METAMASK;
const keplr = WalletOption.KEPLR;
const ledger = WalletOption.LEDGER;
const keystore = WalletOption.KEYSTORE;
// @noErrorValidation
import { createSwapKit, Chain, WalletOption } from "@swapdk/sdk";
const swapDK = createSwapKit();
await swapDK.connectKeystore(
[Chain.Ethereum, Chain.Bitcoin],
"your twelve word mnemonic phrase here"
);
await swapDK.connectEVMWallet([Chain.Ethereum], WalletOption.METAMASK);
await swapDK.connectKeplr([Chain.Cosmos, Chain.THORChain]);
await swapDK.connectCosmostation([Chain.Cosmos, Chain.THORChain]);
const wallets = swapDK.getAllWallets();
// @noErrorValidation
import { createSwapKit, Chain } from "@swapdk/sdk";
const swapDK = createSwapKit();
const ethBalance = await swapDK.getBalance(Chain.Ethereum);
const btcBalance = await swapDK.getBalance(Chain.Bitcoin);
const freshBalance = await swapDK.getBalance(Chain.Ethereum, true);
const walletWithBalance = await swapDK.getWalletWithBalance(Chain.Ethereum);
console.log(`Address: ${walletWithBalance.address}`);
console.log(`Balance: ${walletWithBalance.balance}`);

Use the SwapDK API to get quotes and execute swaps:

// @noErrorValidation
import { createSwapKit, Chain, FeeOption, SwapKitApi } from "@swapdk/sdk";
const swapDK = createSwapKit();
const quoteParams = {
sellAsset: "ETH.ETH",
sellAmount: "1000000000000000000",
buyAsset: "BTC.BTC",
sourceAddress: swapDK.getAddress(Chain.Ethereum),
destinationAddress: swapDK.getAddress(Chain.Bitcoin),
slippage: 3,
};
const { routes } = await SwapKitApi.getSwapQuote(quoteParams);
const bestRoute = routes[0];
console.log(`Expected output: ${bestRoute.expectedBuyAmount}`);
console.log(`Fees:`, bestRoute.fee);
const txHash = await swapDK.swap({
route: bestRoute,
feeOptionKey: FeeOption.Fast,
});
console.log(`Swap transaction: ${txHash}`);

🚀 Your First Cross-Chain Swap

Follow this interactive tutorial to perform your first swap with SwapDK

Try in Playground
Step 1 of 4
1

Install and Initialize SwapDK

Set up SwapDK in your project with the required dependencies

Code Example
bun add @swapdk/sdk

import { createSwapKit } from '@swapdk/sdk';

const swapDK = createSwapKit({
config: {
  apiKeys: {
    swapKit: 'your-api-key-here'
  }
}
});
Action Required

Install SwapDK and create your instance

Tips & Best Practices
  • Get your API key from https://api.swapdk.com for enhanced features
  • The SDK works without API keys for basic functionality
  • Consider using environment variables for API keys in production
2

Connect Your Wallet

Connect a wallet to access blockchain functionality

Code Example

await swapDK.connectEVMWallet([Chain.Ethereum]);

await swapDK.connectKeystore(
[Chain.Ethereum, Chain.Bitcoin],
'your twelve word mnemonic phrase'
);

const ethAddress = swapDK.getAddress(Chain.Ethereum);
console.log('Connected:', ethAddress);
Action Required

Connect your preferred wallet type

Tips & Best Practices
  • Different wallet types support different chains
  • Hardware wallets provide enhanced security
  • Always verify addresses before sending transactions
3

Get a Swap Quote

Fetch quotes from multiple DEX aggregators to find the best rate

Code Example
import { SwapKitApi } from '@swapdk/sdk';

const quoteResponse = await SwapKitApi.getSwapQuote({
sellAsset: 'ETH.ETH',
buyAsset: 'BTC.BTC',
sellAmount: '0.1',
sourceAddress: swapDK.getAddress(Chain.Ethereum),
destinationAddress: swapDK.getAddress(Chain.Bitcoin),
slippage: 1
});

const bestRoute = quoteResponse.data.routes[0];
console.log('Expected output:', bestRoute.expectedBuyAmount);
Action Required

Fetch swap quotes from the API

Tips & Best Practices
  • Compare multiple routes for the best rate
  • Consider transaction fees in your calculations
  • Slippage tolerance affects the final amount received
4

Execute the Swap

Perform the cross-chain swap using the selected route

Code Example
import { FeeOption } from '@swapdk/sdk';

const txHash = await swapDK.swap({
route: bestRoute,
feeOptionKey: FeeOption.Fast
});

console.log('Transaction hash:', txHash);

const txUrl = swapDK.getExplorerTxUrl({
chain: Chain.Ethereum,
txHash
});
Action Required

Execute your first cross-chain swap

Tips & Best Practices
  • Save the transaction hash for tracking
  • Cross-chain swaps may take several minutes to complete
  • Use block explorers to monitor transaction status
// @noErrorValidation
import { createSwapKit, AssetValue, FeeOption, Chain } from "@swapdk/sdk";
const swapDK = createSwapKit();
const ethAmount = AssetValue.from({ asset: "ETH.ETH", value: "0.1" });
const txHash = await swapDK.transfer({
assetValue: ethAmount,
recipient: "0x742d35Cc6634C0532925a3b844Bc9e7595f6E321",
memo: "Payment for services",
feeOptionKey: FeeOption.Fast,
});
const btcAmount = AssetValue.from({ asset: "BTC.BTC", value: "0.001" });
const btcTxHash = await swapDK.transfer({
assetValue: btcAmount,
recipient: "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
feeOptionKey: FeeOption.Average,
});
const xrpAmount = AssetValue.from({ asset: "XRP.XRP", value: "10" });
const xrpTxHash = await swapDK.transfer({
assetValue: xrpAmount,
recipient: "rBaaxNpAKxELKXkJpSCCJQTkQMTYrcPQPv",
memo: "Invoice #12345",
feeOptionKey: FeeOption.Fast,
});

For smaller bundle sizes, use only the components you need:

// @noErrorValidation
import {
SwapKit,
ThorchainPlugin,
keystoreWallet,
ledgerWallet,
} from "@swapdk/sdk";
const swapDK = SwapKit({
plugins: {
...ThorchainPlugin,
},
wallets: {
...keystoreWallet,
...ledgerWallet,
},
});

For low-level blockchain operations:

// @noErrorValidation
import { getToolbox, Chain } from "@swapdk/sdk";
const address = "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh";
const btcToolbox = getToolbox(Chain.Bitcoin);
const isValid = btcToolbox.validateAddress(address);
const balance = await btcToolbox.getBalance(address);

Create your own plugin to extend SwapDK:

// @noErrorValidation
import { SwapKit } from "@swapdk/sdk";
const MyCustomPlugin = {
myCustomMethod: async (params: any) => {
return { success: true };
},
getCustomData: async () => {
console.log("Fetching custom data");
return { data: "custom-data" };
},
};
const swapDK = SwapKit({
plugins: {
...MyCustomPlugin,
},
});
await swapDK.myCustomMethod({ customParam: "value" });
await swapDK.getCustomData();

SwapDK uses typed errors for better debugging:

// @noErrorValidation
import { createSwapKit, SwapKitError, FeeOption } from "@swapdk/sdk";
const swapDK = createSwapKit();
try {
const route = {
sellAsset: "ETH.ETH",
buyAsset: "BTC.BTC",
expectedBuyAmount: "0.001",
};
await swapDK.swap({
route,
feeOptionKey: FeeOption.Fast,
});
} catch (error) {
if (error instanceof SwapKitError) {
console.error("SwapDK Error:", error.message);
console.error("Full error:", error);
} else {
console.error("Unexpected error:", error);
}
}

Now that you understand the basics, here’s your recommended learning path:

📚 Essential Foundation (Complete First)

Section titled “📚 Essential Foundation (Complete First)”

Core Concepts

Master AssetValue, error handling, and TypeScript types that power every SwapDK operation. Learn Core Concepts →

Configuration

Set up API keys, RPC URLs, and customize settings for your production environment. Configure SwapDK →

⚡ Essential Actions (Build Your First App)

Section titled “⚡ Essential Actions (Build Your First App)”

Connect Wallets

Deep dive into wallet integration across 20+ supported wallets and chains. Wallet Integration →

Send Transactions

Handle transfers, fee estimation, and transaction tracking across all chains. Transaction Guide →

EVM Chains

Ethereum, Arbitrum, Polygon, and other EVM-compatible networks. EVM Integration →

Other Networks

Solana, Cosmos, Ripple, and specialized blockchain integrations. All Chains →

Best Practices

Production deployment, security, performance, and error handling. Production Guide →

THORChain Features

Leverage THORChain’s native liquidity and advanced DeFi features. THORChain Guide →

Advanced Features

Multi-chain operations, synthetic assets, and enterprise features. Advanced Guide →

Framework Integration

Use SwapDK with Next.js, Vite, React Native, and other frameworks. Framework Guides →

If you’re upgrading from v3 or want to explore the latest features:


Happy building with SwapDK! 🚀