Core Concepts
Before diving into SwapKit’s features, it’s essential to understand its core concepts. These building blocks are used throughout the SDK and understanding them will make your development experience much smoother.
AssetValue
Section titled “AssetValue”AssetValue
is SwapKit’s primary way of representing amounts of any asset across all supported chains. It handles decimal precision, formatting, and arithmetic operations automatically.
Creating AssetValue
Section titled “Creating AssetValue”import { AssetValue } from '@swapkit/sdk';
// From decimal value (what users see)const oneEth = AssetValue.from({ asset: 'ETH.ETH', value: 1});
// From base units (wei, satoshi, etc.)const oneEthInWei = AssetValue.from({ asset: 'ETH.ETH', value: '1000000000000000000', fromBaseDecimal: true});
// Both create the same AssetValue representing 1 ETH
Asset Notation
Section titled “Asset Notation”SwapKit uses a consistent format for identifying assets:
// Native assets: CHAIN.SYMBOL'ETH.ETH' // Native Ethereum'BTC.BTC' // Native Bitcoin'AVAX.AVAX' // Native Avalanche
// Tokens: CHAIN.SYMBOL-CONTRACT'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // USDC on Ethereum'AVAX.USDC-0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E' // USDC on Avalanche
// Synthetic assets (THORChain)'ETH/ETH' // Synthetic ETH'BTC/BTC' // Synthetic BTC
Arithmetic Operations
Section titled “Arithmetic Operations”AssetValue provides safe arithmetic operations:
const amount1 = AssetValue.from({ asset: 'ETH.ETH', value: 1.5 });const amount2 = AssetValue.from({ asset: 'ETH.ETH', value: 0.5 });
// Additionconst sum = amount1.add(amount2); // 2 ETH
// Subtractionconst difference = amount1.sub(amount2); // 1 ETH
// Multiplicationconst doubled = amount1.mul(2); // 3 ETH
// Divisionconst halved = amount1.div(2); // 0.75 ETH
Comparisons
Section titled “Comparisons”Compare AssetValue instances safely:
const amount1 = AssetValue.from({ asset: 'BTC.BTC', value: 1 });const amount2 = AssetValue.from({ asset: 'BTC.BTC', value: 0.5 });
amount1.gt(amount2); // true - greater thanamount1.gte(amount2); // true - greater than or equalamount1.lt(amount2); // false - less thanamount1.lte(amount2); // false - less than or equalamount1.eq(amount2); // false - equal
Formatting
Section titled “Formatting”Format values for display:
const btcAmount = AssetValue.from({ asset: 'BTC.BTC', value: 0.00123456 });
// Format with significant digitsbtcAmount.toSignificant(4); // "0.001235"
// Format as currencybtcAmount.toCurrency('USD', 45000); // "$55.56"
// Format with abbreviationconst largeAmount = AssetValue.from({ asset: 'ETH.ETH', value: 1234567 });largeAmount.toAbbreviation(); // "1.23M"
// Get raw valuesbtcAmount.getValue('string'); // "0.00123456"btcAmount.getBaseValue('string'); // "123456" (in satoshis)
Type Checks
Section titled “Type Checks”Check asset properties:
const ethAmount = AssetValue.from({ asset: 'ETH.ETH', value: 1 });const usdcAmount = AssetValue.from({ asset: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', value: 100});const synthEth = AssetValue.from({ asset: 'ETH/ETH', value: 1 });
ethAmount.isGasAsset(); // true - native assetusdcAmount.isGasAsset(); // false - tokensynthEth.isSynthetic(); // true - synthetic asset
SwapKitNumber
Section titled “SwapKitNumber”SwapKitNumber
provides utilities for safe numeric operations with BigInt support:
import { SwapKitNumber } from '@swapkit/sdk';
// Create from various inputsconst num1 = new SwapKitNumber(123.456);const num2 = new SwapKitNumber('789.012');const num3 = new SwapKitNumber({ value: 100, decimal: 18 });
// Arithmetic operationsconst sum = num1.add(num2);const product = num1.mul(num2);
// Formattingnum1.toSignificant(4); // "123.5"num1.toFixed(2); // "123.46"
Chain Types
Section titled “Chain Types”SwapKit uses consistent chain identifiers across the entire SDK:
import { Chain } from '@swapkit/sdk';
// EVM ChainsChain.Ethereum // "ETH"Chain.Avalanche // "AVAX"Chain.BinanceSmartChain // "BSC"Chain.Polygon // "MATIC"Chain.Arbitrum // "ARB"Chain.Optimism // "OP"Chain.Base // "BASE"
// UTXO ChainsChain.Bitcoin // "BTC"Chain.BitcoinCash // "BCH"Chain.Litecoin // "LTC"Chain.Dogecoin // "DOGE"Chain.Dash // "DASH"Chain.Zcash // "ZEC"
// Cosmos ChainsChain.Cosmos // "GAIA"Chain.THORChain // "THOR"Chain.Maya // "MAYA"Chain.Kujira // "KUJI"
// Other ChainsChain.Solana // "SOL"Chain.Polkadot // "DOT"Chain.Chainflip // "FLIP"Chain.Radix // "XRD"Chain.Ripple // "XRP"
Error Handling
Section titled “Error Handling”SwapKit uses a typed error system for better debugging:
SwapKitError
Section titled “SwapKitError”The base error class with additional context:
import { SwapKitError } from '@swapkit/sdk';
try { await swapKit.swap({ route });} catch (error) { if (error instanceof SwapKitError) { // Access error details console.error('Error:', error.message); console.error('Code:', error.code); console.error('Details:', error.details); }}
Common Error Codes
Section titled “Common Error Codes”SwapKit uses standardized error codes:
// Wallet errors"wallet_not_found""wallet_connection_failed""wallet_insufficient_funds"
// Transaction errors"transaction_failed""transaction_rejected""transaction_timeout"
// API errors"api_request_failed""api_rate_limit""api_invalid_response"
// Validation errors"invalid_address""invalid_amount""invalid_chain"
Error Context
Section titled “Error Context”Errors include helpful context:
catch (error) { if (error instanceof SwapKitError) { // Error might include: // - Transaction hash // - Chain information // - Wallet address // - API response console.log('Context:', error.info); }}
Wallet Types
Section titled “Wallet Types”SwapKit supports various wallet types through the WalletOption
enum:
import { WalletOption } from '@swapkit/sdk';
WalletOption.METAMASKWalletOption.COINBASEWalletOption.OKXWalletOption.BITGETWalletOption.EXODUSWalletOption.KEPLRWalletOption.LEAPWalletOption.COSMOSTATIONWalletOption.LEDGERWalletOption.TREZORWalletOption.KEEPKEYWalletOption.WALLETCONNECTWalletOption.KEYSTOREWalletOption.POLKADOTJSWalletOption.TALISMANWalletOption.PHANTOMWalletOption.ONEKEYWalletOption.RADIX_MOBILEWalletOption.BRAVEWalletOption.TRUSTWALLETWalletOption.XDEFI
Fee Options
Section titled “Fee Options”Control transaction fees with the FeeOption
enum:
import { FeeOption } from '@swapkit/sdk';
// Available fee optionsFeeOption.Average // Standard feeFeeOption.Fast // 1.5x standardFeeOption.Fastest // 2x standard
// Usageawait swapKit.transfer({ assetValue, recipient, feeOptionKey: FeeOption.Fast});
Provider Types
Section titled “Provider Types”SwapKit integrates with multiple swap providers:
import { ProviderName } from '@swapkit/sdk';
ProviderName.THORCHAINProviderName.CHAINFLIPProviderName.ONEINCHProviderName.UNISWAPProviderName.SUSHISWAPProviderName.PANCAKESWAP
Best Practices
Section titled “Best Practices”1. Always Use AssetValue for Amounts
Section titled “1. Always Use AssetValue for Amounts”// ✅ Goodconst amount = AssetValue.from({ asset: 'ETH.ETH', value: 1 });await swapKit.transfer({ assetValue: amount, recipient });
// ❌ Bad - Don't use raw numbersawait swapKit.transfer({ value: 1, recipient });
2. Handle Decimal Precision
Section titled “2. Handle Decimal Precision”// AssetValue handles decimals automaticallyconst usdcAmount = AssetValue.from({ asset: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', value: 100 // This is 100 USDC, not 100 * 10^6});
// For base units, specify fromBaseDecimalconst weiAmount = AssetValue.from({ asset: 'ETH.ETH', value: '1000000000000000000', fromBaseDecimal: true // This is 1 ETH in wei});
3. Compare Assets Safely
Section titled “3. Compare Assets Safely”// ✅ Good - Use AssetValue comparison methodsif (balance.gte(requiredAmount)) { await performTransaction();}
// ❌ Bad - Don't compare raw valuesif (Number(balance.getValue()) >= Number(requiredAmount.getValue())) { await performTransaction();}
4. Format for Display
Section titled “4. Format for Display”// Use formatting methods for UI displayconst btcBalance = AssetValue.from({ asset: 'BTC.BTC', value: 0.00123456 });
// For displayconst displayValue = btcBalance.toSignificant(6); // "0.00123456"
// For USD valueconst usdValue = btcBalance.toCurrency('USD', btcPrice); // "$55.56"
Next Steps
Section titled “Next Steps”Now that you understand the core concepts:
- Set up your Configuration
- Learn about Toolbox Usage for direct chain operations
- Start Building Your First App