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

Advanced Features

This guide covers advanced SwapKit features for building sophisticated DeFi applications.

SwapKit excels at coordinating operations across multiple blockchains simultaneously.

Fetch balances across all connected chains efficiently:

import { 
function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
createSwapKit
, enum ChainChain } from '@swapkit/sdk';
import {
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
} from '@swapkit/helpers/api';
const
const swapKit: {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
swapKit
=
function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
createSwapKit
();
// Connect multiple chains await
const swapKit: {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
swapKit
.
connectKeystore: (chains: Chain[], phrase: string, derivationPathMapOrIndex?: number | {
    ARB?: DerivationPathArray | undefined;
    AVAX?: DerivationPathArray | undefined;
    ... 21 more ...;
    TRX?: DerivationPathArray | undefined;
} | undefined) => Promise<boolean>
connectKeystore
(
[enum ChainChain.function (enum member) Chain.Ethereum = "ETH"Ethereum, enum ChainChain.function (enum member) Chain.Bitcoin = "BTC"Bitcoin, enum ChainChain.function (enum member) Chain.Avalanche = "AVAX"Avalanche, enum ChainChain.function (enum member) Chain.THORChain = "THOR"THORChain], 'your mnemonic phrase' ); // Get all balances in parallel const const chains: Chain[]chains = [enum ChainChain.function (enum member) Chain.Ethereum = "ETH"Ethereum, enum ChainChain.function (enum member) Chain.Bitcoin = "BTC"Bitcoin, enum ChainChain.function (enum member) Chain.Avalanche = "AVAX"Avalanche, enum ChainChain.function (enum member) Chain.THORChain = "THOR"THORChain]; const const balances: AssetValue[][]balances = await var Promise: PromiseConstructor
Represents the completion of an asynchronous operation
Promise
.PromiseConstructor.all<Promise<AssetValue[]>[]>(values: Promise<AssetValue[]>[]): Promise<AssetValue[][]> (+1 overload)
Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected.
@paramvalues An array of Promises.@returnsA new Promise.
all
(
const chains: Chain[]chains.Array<Chain>.map<Promise<AssetValue[]>>(callbackfn: (value: Chain, index: number, array: Chain[]) => Promise<AssetValue[]>, thisArg?: any): Promise<...>[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
(chain: Chainchain =>
const swapKit: {
    chainflip: {
        supportedSwapkitProviders: ProviderName[];
    } & {
        swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
    };
    ... 5 more ...;
    near: {
        ...;
    } & {
        ...;
    };
} & {
    ...;
} & {
    ...;
}
swapKit
.getBalance: <Chain, true>(chain: Chain, refresh?: true | undefined) => Promise<AssetValue[]>getBalance(chain: Chainchain, true))
); // Flatten and filter significant balances const const allAssets: AssetValue[]allAssets = const balances: AssetValue[][]balances .Array<AssetValue[]>.flat<AssetValue[][], 1>(this: AssetValue[][], depth?: 1 | undefined): AssetValue[]
Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
@paramdepth The maximum recursion depth
flat
()
.Array<AssetValue>.filter(predicate: (value: AssetValue, index: number, array: AssetValue[]) => unknown, thisArg?: any): AssetValue[] (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.
@parampredicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
filter
(asset: AssetValueasset => asset: AssetValueasset.BigIntArithmetics.getValue<"number">(type: "number", decimal?: number): numbergetValue('number') > 0.01);
// Calculate total USD value const
const priceData: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        name: string;
        id: string;
        market_cap: number;
        price_change_24h_usd: number;
        price_change_percentage_24h_usd: number;
        sparkline_in_7d: number[];
        timestamp: string;
        total_volume: number;
    } | undefined;
    price_usd?: number | undefined;
}[]
priceData
= await
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
.
function getPrice(body: PriceRequest): Promise<{
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        name: string;
        id: string;
        ... 5 more ...;
        total_volume: number;
    } | undefined;
    price_usd?: number | undefined;
}[]>
getPrice
({
tokens: {
    identifier: string;
}[]
tokens
: const allAssets: AssetValue[]allAssets.
Array<AssetValue>.map<{
    identifier: string;
}>(callbackfn: (value: AssetValue, index: number, array: AssetValue[]) => {
    identifier: string;
}, thisArg?: any): {
    identifier: string;
}[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
(a: AssetValuea => ({ identifier: stringidentifier: a: AssetValuea.
AssetValue.toString({ includeSynthProtocol }?: {
    includeSynthProtocol?: boolean;
}): string
Returns a string representation of an object.
toString
() })),
metadata: booleanmetadata: false }); // Convert array response to a map for easier lookup const const prices: Record<string, number>prices =
const priceData: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        name: string;
        id: string;
        market_cap: number;
        price_change_24h_usd: number;
        price_change_percentage_24h_usd: number;
        sparkline_in_7d: number[];
        timestamp: string;
        total_volume: number;
    } | undefined;
    price_usd?: number | undefined;
}[]
priceData
.
Array<{ provider?: string | undefined; identifier?: string | undefined; timestamp?: number | undefined; cg?: { name: string; id: string; market_cap: number; price_change_24h_usd: number; price_change_percentage_24h_usd: number; sparkline_in_7d: number[]; timestamp: string; total_volume: number; } | undefined; price_usd?: number | undefined; }>.reduce<Record<string, number>>(callbackfn: (previousValue: Record<string, number>, currentValue: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        ...;
    } | undefined;
    price_usd?: number | undefined;
}, currentIndex: number, array: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        ...;
    } | undefined;
    price_usd?: number | undefined;
}[]) => Record<...>, initialValue: Record<...>): Record<...> (+2 overloads)
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@paramcallbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.@paraminitialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
reduce
((acc: Record<string, number>acc,
item: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        name: string;
        id: string;
        market_cap: number;
        price_change_24h_usd: number;
        price_change_percentage_24h_usd: number;
        sparkline_in_7d: number[];
        timestamp: string;
        total_volume: number;
    } | undefined;
    price_usd?: number | undefined;
}
item
) => {
if (
item: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        name: string;
        id: string;
        market_cap: number;
        price_change_24h_usd: number;
        price_change_percentage_24h_usd: number;
        sparkline_in_7d: number[];
        timestamp: string;
        total_volume: number;
    } | undefined;
    price_usd?: number | undefined;
}
item
.identifier?: string | undefinedidentifier &&
item: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        name: string;
        id: string;
        market_cap: number;
        price_change_24h_usd: number;
        price_change_percentage_24h_usd: number;
        sparkline_in_7d: number[];
        timestamp: string;
        total_volume: number;
    } | undefined;
    price_usd?: number | undefined;
}
item
.price_usd?: number | undefinedprice_usd) {
acc: Record<string, number>acc[
item: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        name: string;
        id: string;
        market_cap: number;
        price_change_24h_usd: number;
        price_change_percentage_24h_usd: number;
        sparkline_in_7d: number[];
        timestamp: string;
        total_volume: number;
    } | undefined;
    price_usd?: number | undefined;
}
item
.identifier?: stringidentifier] =
item: {
    provider?: string | undefined;
    identifier?: string | undefined;
    timestamp?: number | undefined;
    cg?: {
        name: string;
        id: string;
        market_cap: number;
        price_change_24h_usd: number;
        price_change_percentage_24h_usd: number;
        sparkline_in_7d: number[];
        timestamp: string;
        total_volume: number;
    } | undefined;
    price_usd?: number | undefined;
}
item
.price_usd?: numberprice_usd;
} return acc: Record<string, number>acc; }, {} as type Record<K extends keyof any, T> = { [P in K]: T; }
Construct a type with a set of properties K of type T
Record
<string, number>);
const const totalValue: numbertotalValue = const allAssets: AssetValue[]allAssets.Array<AssetValue>.reduce<number>(callbackfn: (previousValue: number, currentValue: AssetValue, currentIndex: number, array: AssetValue[]) => number, initialValue: number): number (+2 overloads)
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@paramcallbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.@paraminitialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
reduce
((sum: numbersum, asset: AssetValueasset) => {
const const price: numberprice = const prices: Record<string, number>prices[asset: AssetValueasset.
AssetValue.toString({ includeSynthProtocol }?: {
    includeSynthProtocol?: boolean;
}): string
Returns a string representation of an object.
toString
()] || 0;
return sum: numbersum + (asset: AssetValueasset.BigIntArithmetics.getValue<"number">(type: "number", decimal?: number): numbergetValue('number') * const price: numberprice); }, 0);

Execute multiple transactions across different chains:

import { class AssetValueAssetValue, enum FeeOptionFeeOption } from '@swapkit/sdk';

// Prepare multiple transactions
const 
const transactions: {
    chain: any;
    assetValue: AssetValue;
    recipient: string;
}[]
transactions
= [
{ chain: anychain:
Cannot find name 'Chain'. Did you mean 'Chai'?
Chain
.Ethereum,
assetValue: AssetValueassetValue: class AssetValueAssetValue.
AssetValue.from<{
    asset: "ETH.ETH";
    value: number;
}>({ value, fromBaseDecimal, asyncTokenLookup, ...fromAssetOrChain }: {
    asset: "ETH.ETH";
    value: number;
} & AssetValueFromParams): AssetValue
from
({ asset: "ETH.ETH"asset: 'ETH.ETH', value: numbervalue: 0.1 }),
recipient: stringrecipient: '0x...' }, { chain: anychain:
Cannot find name 'Chain'. Did you mean 'Chai'?
Chain
.Bitcoin,
assetValue: AssetValueassetValue: class AssetValueAssetValue.
AssetValue.from<{
    asset: "BTC.BTC";
    value: number;
}>({ value, fromBaseDecimal, asyncTokenLookup, ...fromAssetOrChain }: {
    asset: "BTC.BTC";
    value: number;
} & AssetValueFromParams): AssetValue
from
({ asset: "BTC.BTC"asset: 'BTC.BTC', value: numbervalue: 0.001 }),
recipient: stringrecipient: 'bc1q...' }, { chain: anychain:
Cannot find name 'Chain'. Did you mean 'Chai'?
Chain
.Avalanche,
assetValue: AssetValueassetValue: class AssetValueAssetValue.
AssetValue.from<{
    asset: string;
    value: number;
}>({ value, fromBaseDecimal, asyncTokenLookup, ...fromAssetOrChain }: {
    asset: string;
    value: number;
} & AssetValueFromParams): AssetValue
from
({ asset: stringasset: 'AVAX.AVAX', value: numbervalue: 1 }),
recipient: stringrecipient: '0x...' } ]; // Execute all transactions const const results: PromiseSettledResult<any>[]results = await var Promise: PromiseConstructor
Represents the completion of an asynchronous operation
Promise
.PromiseConstructor.allSettled<any[]>(values: any[]): Promise<PromiseSettledResult<any>[]> (+1 overload)
Creates a Promise that is resolved with an array of results when all of the provided Promises resolve or reject.
@paramvalues An array of Promises.@returnsA new Promise.
allSettled
(
const transactions: {
    chain: any;
    assetValue: AssetValue;
    recipient: string;
}[]
transactions
.
Array<{ chain: any; assetValue: AssetValue; recipient: string; }>.map<any>(callbackfn: (value: {
    chain: any;
    assetValue: AssetValue;
    recipient: string;
}, index: number, array: {
    chain: any;
    assetValue: AssetValue;
    recipient: string;
}[]) => any, thisArg?: any): any[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
(
tx: {
    chain: any;
    assetValue: AssetValue;
    recipient: string;
}
tx
=>
Cannot find name 'swapKit'.
swapKit
.transfer({
...
tx: {
    chain: any;
    assetValue: AssetValue;
    recipient: string;
}
tx
,
feeOptionKey: FeeOptionfeeOptionKey: enum FeeOptionFeeOption.function (enum member) FeeOption.Fast = "fast"Fast }) ) ); // Handle results const results: PromiseSettledResult<any>[]results.Array<PromiseSettledResult<any>>.forEach(callbackfn: (value: PromiseSettledResult<any>, index: number, array: PromiseSettledResult<any>[]) => void, thisArg?: any): void
Performs the specified action for each element in an array.
@paramcallbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
forEach
((result: PromiseSettledResult<any>result, index: numberindex) => {
if (result: PromiseSettledResult<any>result.status: "rejected" | "fulfilled"status === 'fulfilled') { console.Console.log(message?: any, ...optionalParams: any[]): void (+3 overloads)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(`${
const transactions: {
    chain: any;
    assetValue: AssetValue;
    recipient: string;
}[]
transactions
[index: numberindex].chain: anychain} tx: ${result: PromiseFulfilledResult<any>result.PromiseFulfilledResult<any>.value: anyvalue}`);
} else { console.Console.error(message?: any, ...optionalParams: any[]): void (+3 overloads)
Prints to `stderr` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr ``` If formatting elements (e.g. `%d`) are not found in the first string then [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
error
(`${
const transactions: {
    chain: any;
    assetValue: AssetValue;
    recipient: string;
}[]
transactions
[index: numberindex].chain: anychain} failed:`, result: PromiseRejectedResultresult.PromiseRejectedResult.reason: anyreason);
} });

THORChain synthetic assets provide instant swaps without waiting for L1 confirmations.

Synthetic assets are represented with / notation:

  • BTC/BTC - Synthetic Bitcoin
  • ETH/ETH - Synthetic Ethereum
  • AVAX/AVAX - Synthetic Avalanche

Convert L1 assets to synthetics for faster swaps:

import { 
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
} from '@swapkit/helpers/api';
// Get quote for minting synthetic BTC const
const mintQuote: {
    quoteId: string;
    routes: {
        sellAsset: string;
        buyAsset: string;
        destinationAddress: string;
        providers: ProviderName[];
        sellAmount: string;
        expectedBuyAmount: string;
        expectedBuyAmountMaxSlippage: string;
        ... 12 more ...;
        estimatedTime?: {
            ...;
        } | undefined;
    }[];
    error?: string | undefined;
    providerErrors?: {
        ...;
    }[] | undefined;
}
mintQuote
= await
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
.
function getSwapQuote(json: QuoteRequest): Promise<{
    quoteId: string;
    routes: {
        sellAsset: string;
        buyAsset: string;
        destinationAddress: string;
        providers: ProviderName[];
        ... 15 more ...;
        estimatedTime?: {
            ...;
        } | undefined;
    }[];
    error?: string | undefined;
    providerErrors?: {
        ...;
    }[] | undefined;
}>
getSwapQuote
({
sellAsset: stringsellAsset: 'BTC.BTC', sellAmount: stringsellAmount: '10000000', // 0.1 BTC buyAsset: stringbuyAsset: 'BTC/BTC', // Synthetic BTC sourceAddress?: string | undefinedsourceAddress:
Cannot find name 'swapKit'.
swapKit
Cannot find name 'Chain'. Did you mean 'Chai'?
.getAddress(Chain.Bitcoin),
destinationAddress?: string | undefineddestinationAddress:
Cannot find name 'swapKit'.
swapKit
Cannot find name 'Chain'. Did you mean 'Chai'?
.getAddress(Chain.THORChain),
slippage?: number | undefinedslippage: 3 }); // Execute mint const const mintTx: anymintTx = await
Cannot find name 'swapKit'.
swapKit
.swap({
route: {
    sellAsset: string;
    buyAsset: string;
    destinationAddress: string;
    providers: ProviderName[];
    sellAmount: string;
    expectedBuyAmount: string;
    expectedBuyAmountMaxSlippage: string;
    ... 12 more ...;
    estimatedTime?: {
        ...;
    } | undefined;
}
route
:
const mintQuote: {
    quoteId: string;
    routes: {
        sellAsset: string;
        buyAsset: string;
        destinationAddress: string;
        providers: ProviderName[];
        sellAmount: string;
        expectedBuyAmount: string;
        expectedBuyAmountMaxSlippage: string;
        ... 12 more ...;
        estimatedTime?: {
            ...;
        } | undefined;
    }[];
    error?: string | undefined;
    providerErrors?: {
        ...;
    }[] | undefined;
}
mintQuote
.
routes: {
    sellAsset: string;
    buyAsset: string;
    destinationAddress: string;
    providers: ProviderName[];
    sellAmount: string;
    expectedBuyAmount: string;
    expectedBuyAmountMaxSlippage: string;
    ... 12 more ...;
    estimatedTime?: {
        ...;
    } | undefined;
}[]
routes
[0]
});

Swap between synthetics instantly:

// Instant swap between synthetics (no L1 wait)
const const synthSwapQuote: anysynthSwapQuote = await 
Cannot find name 'SwapKitApi'.
SwapKitApi
.getSwapQuote({
sellAsset: stringsellAsset: 'BTC/BTC', // Synthetic BTC sellAmount: stringsellAmount: '10000000', buyAsset: stringbuyAsset: 'ETH/ETH', // Synthetic ETH sourceAddress: anysourceAddress:
Cannot find name 'swapKit'.
swapKit
Cannot find name 'Chain'. Did you mean 'Chai'?
.getAddress(Chain.THORChain),
destinationAddress: anydestinationAddress:
Cannot find name 'swapKit'.
swapKit
Cannot find name 'Chain'. Did you mean 'Chai'?
.getAddress(Chain.THORChain),
slippage: numberslippage: 1 // Lower slippage for synth swaps }); // This swap is instant! const const swapTx: anyswapTx = await
Cannot find name 'swapKit'.
swapKit
.swap({
route: anyroute: const synthSwapQuote: anysynthSwapQuote.routes[0] });

Convert synthetics back to L1 assets:

// Redeem synthetic ETH to real ETH
const const redeemQuote: anyredeemQuote = await 
Cannot find name 'SwapKitApi'.
SwapKitApi
.getSwapQuote({
sellAsset: stringsellAsset: 'ETH/ETH', // Synthetic ETH sellAmount: stringsellAmount: '1000000000000000000', buyAsset: stringbuyAsset: 'ETH.ETH', // L1 ETH sourceAddress: anysourceAddress:
Cannot find name 'swapKit'.
swapKit
Cannot find name 'Chain'. Did you mean 'Chai'?
.getAddress(Chain.THORChain),
destinationAddress: anydestinationAddress:
Cannot find name 'swapKit'.
swapKit
Cannot find name 'Chain'. Did you mean 'Chai'?
.getAddress(Chain.Ethereum),
slippage: numberslippage: 3 }); const const redeemTx: anyredeemTx = await
Cannot find name 'swapKit'.
swapKit
.swap({
route: anyroute: const redeemQuote: anyredeemQuote.routes[0] });

THORChain and Maya use transaction memos for protocol instructions.

// Swap memo
const const swapMemo: "SWAP:BTC.BTC:bc1q..."swapMemo = 'SWAP:BTC.BTC:bc1q...';

// Add liquidity memo
const const addLiquidityMemo: "+:BTC.BTC:bc1q..."addLiquidityMemo = '+:BTC.BTC:bc1q...';

// Withdraw liquidity memo
const const withdrawMemo: "-:BTC.BTC:10000"withdrawMemo = '-:BTC.BTC:10000'; // Basis points

// THORName registration
const const thornameeMemo: "~:name:chain:address"thornameeMemo = '~:name:chain:address';
import { 
function getMemoForDeposit({ chain, symbol, address, ...affiliate }: WithAffiliate<{
    chain: Chain;
    symbol: string;
    address?: string;
}>): string
getMemoForDeposit
, function getMemoForWithdraw({ chain, symbol, ticker, basisPoints, targetAsset, }: WithdrawParams): string
Withdraw
getMemoForWithdraw
, enum MemoTypeMemoType } from '@swapkit/sdk';
// Build deposit (liquidity) memo const const depositMemo: stringdepositMemo =
function getMemoForDeposit({ chain, symbol, address, ...affiliate }: WithAffiliate<{
    chain: Chain;
    symbol: string;
    address?: string;
}>): string
getMemoForDeposit
({
chain: Chainchain:
Cannot find name 'Chain'. Did you mean 'Chai'?
Chain
.Bitcoin,
symbol: stringsymbol: 'BTC', address?: string | undefinedaddress: 'bc1q...', // Optional: asymmetric add affiliateAddress?: string | undefinedaffiliateAddress: 'ss', affiliateBasisPoints?: number | undefinedaffiliateBasisPoints: 50 // 0.5% fee }); // Build withdraw memo const const withdrawMemo: stringwithdrawMemo = function getMemoForWithdraw({ chain, symbol, ticker, basisPoints, targetAsset, }: WithdrawParams): string
Withdraw
getMemoForWithdraw
({
chain: Chainchain:
Cannot find name 'Chain'. Did you mean 'Chai'?
Chain
.Bitcoin,
symbol: stringsymbol: 'BTC', ticker: stringticker: 'BTC', basisPoints: numberbasisPoints: 10000, // 100% targetAsset?: string | undefinedtargetAsset: 'ETH.ETH' // Optional: withdraw to different asset });

Build custom swap routes for specific requirements:

// Get all available routes
const { const routes: anyroutes } = await 
Cannot find name 'SwapKitApi'.
SwapKitApi
.getSwapQuote({
sellAsset: stringsellAsset: 'ETH.ETH', sellAmount: stringsellAmount: '1000000000000000000', buyAsset: stringbuyAsset: 'BTC.BTC', sourceAddress: anysourceAddress:
Cannot find name 'swapKit'.
swapKit
Cannot find name 'Chain'. Did you mean 'Chai'?
.getAddress(Chain.Ethereum),
destinationAddress: anydestinationAddress:
Cannot find name 'swapKit'.
swapKit
Cannot find name 'Chain'. Did you mean 'Chai'?
.getAddress(Chain.Bitcoin),
slippage: numberslippage: 3, providers: string[]providers: ['thorchain', 'chainflip', '1inch'] }); // Filter routes by criteria const const customRoute: anycustomRoute = const routes: anyroutes.find(
Parameter 'route' implicitly has an 'any' type.
route
=> {
// Prefer THORChain for cross-chain if (route: anyroute.providers.includes('THORCHAIN')) return true; // Use 1inch for same-chain swaps if (route: anyroute.providers.includes('1INCH') && route: anyroute.sellAsset.split('.')[0] === route: anyroute.buyAsset.split('.')[0]) { return true; } return false; }); // Add custom parameters const const modifiedRoute: anymodifiedRoute = { ...const customRoute: anycustomRoute, memo: stringmemo: const customRoute: anycustomRoute.memo + ':ss:50', // Add affiliate expiration: stringexpiration: new
var Date: DateConstructor
new (value: number | string | Date) => Date (+4 overloads)
Date
(var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date
.DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now
() + 10 * 60 * 1000).Date.toISOString(): string
Returns a date as a string value in ISO format.
toISOString
() // 10 min expiry
}; // Execute custom route await
Cannot find name 'swapKit'.
swapKit
.swap({ route: anyroute: const modifiedRoute: anymodifiedRoute });

Optimize gas usage across different chains:

import { 
const ChainToChainId: {
    ARB: ChainId;
    AVAX: ChainId;
    BASE: ChainId;
    BSC: ChainId;
    BTC: ChainId;
    BCH: ChainId;
    GAIA: ChainId;
    DASH: ChainId;
    ... 15 more ...;
    TRX: ChainId;
}
ChainToChainId
, enum ChainChain } from '@swapkit/sdk';
import {
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
} from '@swapkit/helpers/api';
// Get current gas rates const
const gasRatesArray: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}[]
gasRatesArray
= await
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
.
function getGasRate(): Promise<{
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}[]>
getGasRate
();
// Convert to a map for easier lookup const
const gasRates: Record<string, {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}>
gasRates
=
const gasRatesArray: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}[]
gasRatesArray
.
Array<{ value: string; id: number; chainId: string; unit: string; createdAt: string; }>.reduce<Record<string, {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}>>(callbackfn: (previousValue: Record<string, {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}>, currentValue: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}, currentIndex: number, array: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}[]) => Record<...>, initialValue: Record<...>): Record<...> (+2 overloads)
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@paramcallbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.@paraminitialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
reduce
((
acc: Record<string, {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}>
acc
,
rate: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}
rate
) => {
acc: Record<string, {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}>
acc
[
rate: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}
rate
.chainId: stringchainId] =
rate: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}
rate
;
return
acc: Record<string, {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}>
acc
;
}, {} as type Record<K extends keyof any, T> = { [P in K]: T; }
Construct a type with a set of properties K of type T
Record
<string, typeof
const gasRatesArray: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}[]
gasRatesArray
[0]>);
// Dynamic fee calculation async function
function getOptimalFeeOption(chain: Chain, urgency: "low" | "medium" | "high"): Promise<{
    maxFeePerGas: number;
    maxPriorityFeePerGas: number;
    feeRate?: undefined;
} | {
    feeRate: number;
    maxFeePerGas?: undefined;
    maxPriorityFeePerGas?: undefined;
} | undefined>
getOptimalFeeOption
(chain: Chainchain: enum ChainChain, urgency: "low" | "medium" | "high"urgency: 'low' | 'medium' | 'high') {
const const chainId: ChainIdchainId =
const ChainToChainId: {
    ARB: ChainId;
    AVAX: ChainId;
    BASE: ChainId;
    BSC: ChainId;
    BTC: ChainId;
    BCH: ChainId;
    GAIA: ChainId;
    DASH: ChainId;
    ... 15 more ...;
    TRX: ChainId;
}
ChainToChainId
[chain: Chainchain];
const
const gasRate: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}
gasRate
=
const gasRates: Record<string, {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}>
gasRates
[const chainId: ChainIdchainId];
if (!
const gasRate: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}
gasRate
) {
throw new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+2 overloads)
Error
(`Gas rate not found for chain ${chain: Chainchain}`);
} // Custom fee multipliers const
const multipliers: {
    low: number;
    medium: number;
    high: number;
}
multipliers
= {
low: numberlow: 0.8, medium: numbermedium: 1.0, high: numberhigh: 1.5 }; const const baseRate: numberbaseRate =
var Number: NumberConstructor
(value?: any) => number
An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.
Number
(
const gasRate: {
    value: string;
    id: number;
    chainId: string;
    unit: string;
    createdAt: string;
}
gasRate
.value: stringvalue);
return
Property 'XRP' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'XRD' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'TRX' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'THOR' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'SOL' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'OP' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'NEAR' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'MAYA' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'MATIC' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'LTC' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'KUJI' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'GAIA' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'FLIP' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'FIAT' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'DOT' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'DOGE' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'DASH' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'BSC' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'BCH' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'BASE' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'AVAX' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
Property 'ARB' does not exist on type '{ ETH: { maxFeePerGas: number; maxPriorityFeePerGas: number; }; BTC: { feeRate: number; }; }'.
{
[enum ChainChain.function (enum member) Chain.Ethereum = "ETH"Ethereum]: { maxFeePerGas: numbermaxFeePerGas: var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math
.Math.floor(x: number): number
Returns the greatest integer less than or equal to its numeric argument.
@paramx A numeric expression.
floor
(const baseRate: numberbaseRate *
const multipliers: {
    low: number;
    medium: number;
    high: number;
}
multipliers
[urgency: "low" | "medium" | "high"urgency]),
maxPriorityFeePerGas: numbermaxPriorityFeePerGas: var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math
.Math.floor(x: number): number
Returns the greatest integer less than or equal to its numeric argument.
@paramx A numeric expression.
floor
(const baseRate: numberbaseRate * 0.1 *
const multipliers: {
    low: number;
    medium: number;
    high: number;
}
multipliers
[urgency: "low" | "medium" | "high"urgency])
}, [enum ChainChain.function (enum member) Chain.Bitcoin = "BTC"Bitcoin]: { feeRate: numberfeeRate: var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math
.Math.floor(x: number): number
Returns the greatest integer less than or equal to its numeric argument.
@paramx A numeric expression.
floor
(const baseRate: numberbaseRate *
const multipliers: {
    low: number;
    medium: number;
    high: number;
}
multipliers
[urgency: "low" | "medium" | "high"urgency])
} }[chain: Chainchain]; } // Use optimized fees const
const customFees: {
    maxFeePerGas: number;
    maxPriorityFeePerGas: number;
    feeRate?: undefined;
} | {
    feeRate: number;
    maxFeePerGas?: undefined;
    maxPriorityFeePerGas?: undefined;
} | undefined
customFees
= await
function getOptimalFeeOption(chain: Chain, urgency: "low" | "medium" | "high"): Promise<{
    maxFeePerGas: number;
    maxPriorityFeePerGas: number;
    feeRate?: undefined;
} | {
    feeRate: number;
    maxFeePerGas?: undefined;
    maxPriorityFeePerGas?: undefined;
} | undefined>
getOptimalFeeOption
(enum ChainChain.function (enum member) Chain.Ethereum = "ETH"Ethereum, 'low');
const const tx: anytx = await
Cannot find name 'swapKit'.
swapKit
.transfer({
No value exists in scope for the shorthand property 'assetValue'. Either declare one or provide an initializer.
assetValue
,
No value exists in scope for the shorthand property 'recipient'. Either declare one or provide an initializer.
recipient
,
customTxFee: {
    maxFeePerGas: number;
    maxPriorityFeePerGas: number;
    feeRate?: undefined;
} | {
    feeRate: number;
    maxFeePerGas?: undefined;
    maxPriorityFeePerGas?: undefined;
} | undefined
customTxFee
:
const customFees: {
    maxFeePerGas: number;
    maxPriorityFeePerGas: number;
    feeRate?: undefined;
} | {
    feeRate: number;
    maxFeePerGas?: undefined;
    maxPriorityFeePerGas?: undefined;
} | undefined
customFees
});

Manage custom token lists and metadata:

import { class AssetValueAssetValue, enum ProviderNameProviderName } from '@swapkit/sdk';
import { 
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
} from '@swapkit/helpers/api';
// Get token lists from providers async function function loadTokenList(provider: ProviderName): Promise<TokenV2[]>loadTokenList(provider: ProviderNameprovider: enum ProviderNameProviderName) { const const tokenList: TokensResponseV2tokenList = await
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
.function getTokenList(provider: ProviderName): Promise<TokensResponseV2>getTokenList(provider: ProviderNameprovider);
return const tokenList: TokensResponseV2tokenList.tokens: TokenV2[]tokens; } // Custom token registry with caching class class TokenRegistryTokenRegistry { private TokenRegistry.tokens: Map<string, any>tokens: interface Map<K, V>Map<string, any> = new
var Map: MapConstructor
new () => Map<any, any> (+3 overloads)
Map
();
private
TokenRegistry.cache: Map<string, {
    data: any;
    timestamp: number;
}>
cache
: interface Map<K, V>Map<string, { data: anydata: any; timestamp: numbertimestamp: number }> = new
var Map: MapConstructor
new () => Map<any, any> (+3 overloads)
Map
();
private TokenRegistry.cacheTTL: numbercacheTTL = 3600000; // 1 hour async TokenRegistry.loadProviderTokens(provider: ProviderName): Promise<any>loadProviderTokens(provider: ProviderNameprovider: enum ProviderNameProviderName) { const const cacheKey: stringcacheKey = `provider_${provider: ProviderNameprovider}`; const
const cached: {
    data: any;
    timestamp: number;
} | undefined
cached
= this.
TokenRegistry.cache: Map<string, {
    data: any;
    timestamp: number;
}>
cache
.
Map<string, { data: any; timestamp: number; }>.get(key: string): {
    data: any;
    timestamp: number;
} | undefined
Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
@returnsReturns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
get
(const cacheKey: stringcacheKey);
if (
const cached: {
    data: any;
    timestamp: number;
} | undefined
cached
&& var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date
.DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now
() -
const cached: {
    data: any;
    timestamp: number;
}
cached
.timestamp: numbertimestamp < this.TokenRegistry.cacheTTL: numbercacheTTL) {
return
const cached: {
    data: any;
    timestamp: number;
}
cached
.data: anydata;
} const const tokenList: TokensResponseV2tokenList = await
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
.function getTokenList(provider: ProviderName): Promise<TokensResponseV2>getTokenList(provider: ProviderNameprovider);
this.
TokenRegistry.cache: Map<string, {
    data: any;
    timestamp: number;
}>
cache
.
Map<string, { data: any; timestamp: number; }>.set(key: string, value: {
    data: any;
    timestamp: number;
}): Map<string, {
    data: any;
    timestamp: number;
}>
Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
set
(const cacheKey: stringcacheKey, { data: anydata: const tokenList: TokensResponseV2tokenList, timestamp: numbertimestamp: var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date
.DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now
() });
// Index tokens by identifier const tokenList: TokensResponseV2tokenList.tokens: TokenV2[]tokens.Array<TokenV2>.forEach(callbackfn: (value: TokenV2, index: number, array: TokenV2[]) => void, thisArg?: any): void
Performs the specified action for each element in an array.
@paramcallbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
forEach
(token: TokenV2token => {
this.TokenRegistry.tokens: Map<string, any>tokens.Map<string, any>.set(key: string, value: any): Map<string, any>
Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
set
(token: TokenV2token.identifier: stringidentifier, token: TokenV2token);
}); return const tokenList: TokensResponseV2tokenList; }
TokenRegistry.addCustomToken(token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}): void
addCustomToken
(
token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}
token
: {
chain: stringchain: string; identifier: stringidentifier: string; symbol: stringsymbol: string; decimals: numberdecimals: number; name?: string | undefinedname?: string; logoURI?: string | undefinedlogoURI?: string; address?: string | undefinedaddress?: string; }) { this.TokenRegistry.tokens: Map<string, any>tokens.Map<string, any>.set(key: string, value: any): Map<string, any>
Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
set
(
token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}
token
.identifier: stringidentifier,
token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}
token
);
// Register with AssetValue for proper decimal handling class AssetValueAssetValue.
AssetValue.setStaticAssets(tokenMap: Map<string, {
    tax?: TokenTax;
    identifier: string;
    chain: Chain;
} & ({
    decimal: number;
} | {
    decimals: number;
})>): boolean
setStaticAssets
(new
var Map: MapConstructor
new <string, {
    identifier: string;
    chain: any;
    decimal: number;
}>(iterable?: Iterable<readonly [string, {
    identifier: string;
    chain: any;
    decimal: number;
}]> | null | undefined) => Map<string, {
    identifier: string;
    chain: any;
    decimal: number;
}> (+3 overloads)
Map
([[
token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}
token
.identifier: stringidentifier, {
identifier: stringidentifier:
token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}
token
.identifier: stringidentifier,
chain: anychain:
token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}
token
.chain: stringchain as any,
decimal: numberdecimal:
token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}
token
.decimals: numberdecimals
}]])); } TokenRegistry.getToken(identifier: string): anygetToken(identifier: stringidentifier: string) { return this.TokenRegistry.tokens: Map<string, any>tokens.Map<string, any>.get(key: string): any
Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
@returnsReturns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
get
(identifier: stringidentifier);
} } // Usage const const registry: TokenRegistryregistry = new constructor TokenRegistry(): TokenRegistryTokenRegistry(); // Load tokens from a provider await const registry: TokenRegistryregistry.TokenRegistry.loadProviderTokens(provider: ProviderName): Promise<any>loadProviderTokens(enum ProviderNameProviderName.
Property 'UNISWAP' does not exist on type 'typeof ProviderName'.
UNISWAP
);
// Add custom token const registry: TokenRegistryregistry.
TokenRegistry.addCustomToken(token: {
    chain: string;
    identifier: string;
    symbol: string;
    decimals: number;
    name?: string;
    logoURI?: string;
    address?: string;
}): void
addCustomToken
({
chain: stringchain: 'ETH', identifier: stringidentifier: 'ETH.CUSTOM-0x1234567890123456789012345678901234567890', symbol: stringsymbol: 'CUSTOM', decimals: numberdecimals: 18, name?: string | undefinedname: 'Custom Token', logoURI?: string | undefinedlogoURI: 'https://example.com/token.png' });

Implement advanced transaction tracking:

import { 
const ChainToChainId: {
    ARB: ChainId;
    AVAX: ChainId;
    BASE: ChainId;
    BSC: ChainId;
    BTC: ChainId;
    BCH: ChainId;
    GAIA: ChainId;
    DASH: ChainId;
    ... 15 more ...;
    TRX: ChainId;
}
ChainToChainId
} from '@swapkit/sdk';
import {
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
} from '@swapkit/helpers/api';
class class TransactionTrackerTransactionTracker { private TransactionTracker.pendingTxs: Map<string, any>pendingTxs: interface Map<K, V>Map<string, any> = new
var Map: MapConstructor
new () => Map<any, any> (+3 overloads)
Map
();
async TransactionTracker.trackTransaction(txHash: string, chain: Chain): Promise<void>trackTransaction(txHash: stringtxHash: string, chain: Chainchain:
Cannot find name 'Chain'.
Chain
) {
this.TransactionTracker.pendingTxs: Map<string, any>pendingTxs.Map<string, any>.set(key: string, value: any): Map<string, any>
Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
set
(txHash: stringtxHash, { chain: Chainchain, status: stringstatus: 'pending' });
// Poll for updates const const interval: NodeJS.Timeoutinterval = function setInterval<[]>(callback: () => void, delay?: number): NodeJS.Timeout (+4 overloads)
Schedules repeated execution of `callback` every `delay` milliseconds. When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. If `callback` is not a function, a `TypeError` will be thrown. This method has a custom variant for promises that is available using `timersPromises.setInterval()`.
@sincev0.0.1@paramcallback The function to call when the timer elapses.@paramdelay The number of milliseconds to wait before calling the `callback`. **Default:** `1`.@paramargs Optional arguments to pass when the `callback` is called.@returnsfor use with `clearInterval()`
setInterval
(async () => {
try { const const chainId: anychainId =
Element implicitly has an 'any' type because expression of type 'Chain' can't be used to index type '{ ARB: ChainId; AVAX: ChainId; BASE: ChainId; BSC: ChainId; BTC: ChainId; BCH: ChainId; GAIA: ChainId; DASH: ChainId; ... 15 more ...; TRX: ChainId; }'.
ChainToChainId[chain]
;
const const status: TrackerResponsestatus = await
const SwapKitApi: {
    mayachainMidgard: {
        getLiquidityPositionRaw: (address: string) => Promise<MemberDetailsMayachain>;
        getNameDetails: (name: string) => Promise<THORNameDetails>;
        getNamesByAddress: (address: string) => Promise<...>;
        getNamesByOwner: (address: string) => Promise<...>;
        getLiquidityPosition: (address: string) => Promise<...>;
    };
    ... 14 more ...;
    getChainflipDepositChannel(body: BrokerDepositChannelParams): Promise<...>;
}
SwapKitApi
.function getTrackerDetails(json: TrackerParams): Promise<TrackerResponse>getTrackerDetails({ hash: stringhash: txHash: stringtxHash, chainId: ChainIdchainId });
if (const status: TrackerResponsestatus.TransactionProps.status?: TxnStatus | undefinedstatus === 'completed') { this.TransactionTracker.pendingTxs: Map<string, any>pendingTxs.Map<string, any>.set(key: string, value: any): Map<string, any>
Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
set
(txHash: stringtxHash, { ...const status: TrackerResponsestatus, chain: Chainchain });
function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void (+3 overloads)
Cancels a `Timeout` object created by `setInterval()`.
@sincev0.0.1@paramtimeout A `Timeout` object as returned by `setInterval()` or the primitive of the `Timeout` object as a string or a number.
clearInterval
(const interval: NodeJS.Timeoutinterval);
this.TransactionTracker.onComplete(txHash: string, status: any): voidonComplete(txHash: stringtxHash, const status: TrackerResponsestatus); } else if (
This comparison appears to be unintentional because the types 'TxnStatus.unknown | TxnStatus.not_started | TxnStatus.pending | TxnStatus.swapping | undefined' and '"failed"' have no overlap.
status.status === 'failed'
) {
this.TransactionTracker.pendingTxs: Map<string, any>pendingTxs.Map<string, any>.delete(key: string): boolean
@returnstrue if an element in the Map existed and has been removed, or false if the element does not exist.
delete
(txHash: stringtxHash);
function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void (+3 overloads)
Cancels a `Timeout` object created by `setInterval()`.
@sincev0.0.1@paramtimeout A `Timeout` object as returned by `setInterval()` or the primitive of the `Timeout` object as a string or a number.
clearInterval
(const interval: NodeJS.Timeoutinterval);
this.TransactionTracker.onFailed(txHash: string, status: any): voidonFailed(txHash: stringtxHash, const status: TrackerResponsestatus); } } catch (error) { // Continue polling } }, 10000); // Check every 10 seconds } private TransactionTracker.onComplete(txHash: string, status: any): voidonComplete(txHash: stringtxHash: string, status: anystatus: any) { console.Console.log(message?: any, ...optionalParams: any[]): void (+3 overloads)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(`Transaction ${txHash: stringtxHash} completed!`);
// Update UI, send notifications, etc. } private TransactionTracker.onFailed(txHash: string, status: any): voidonFailed(txHash: stringtxHash: string, status: anystatus: any) { console.Console.error(message?: any, ...optionalParams: any[]): void (+3 overloads)
Prints to `stderr` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr ``` If formatting elements (e.g. `%d`) are not found in the first string then [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
error
(`Transaction ${txHash: stringtxHash} failed!`);
// Handle failure } } // Usage const const tracker: TransactionTrackertracker = new constructor TransactionTracker(): TransactionTrackerTransactionTracker(); // Track a swap const const txHash: anytxHash = await
Cannot find name 'swapKit'.
swapKit
No value exists in scope for the shorthand property 'route'. Either declare one or provide an initializer.
.swap({ route });
await const tracker: TransactionTrackertracker.TransactionTracker.trackTransaction(txHash: string, chain: Chain): Promise<void>trackTransaction(const txHash: anytxHash,
Cannot find name 'Chain'. Did you mean 'Chai'?
Chain
.Ethereum);

Implement robust error handling and recovery:

import { class SwapKitErrorSwapKitError } from '@swapkit/sdk';

class class SwapKitRetrySwapKitRetry {
  async SwapKitRetry.executeWithRetry<T>(operation: () => Promise<T>, maxRetries?: number, backoff?: number): Promise<T>executeWithRetry<function (type parameter) T in SwapKitRetry.executeWithRetry<T>(operation: () => Promise<T>, maxRetries?: number, backoff?: number): Promise<T>T>(
    operation: () => Promise<T>operation: () => interface Promise<T>
Represents the completion of an asynchronous operation
Promise
<function (type parameter) T in SwapKitRetry.executeWithRetry<T>(operation: () => Promise<T>, maxRetries?: number, backoff?: number): Promise<T>T>,
maxRetries: numbermaxRetries = 3, backoff: numberbackoff = 1000 ): interface Promise<T>
Represents the completion of an asynchronous operation
Promise
<function (type parameter) T in SwapKitRetry.executeWithRetry<T>(operation: () => Promise<T>, maxRetries?: number, backoff?: number): Promise<T>T> {
let let lastError: ErrorlastError: Error; for (let let i: numberi = 0; let i: numberi < maxRetries: numbermaxRetries; let i: numberi++) { try { return await operation: () => Promise<T>operation(); } catch (error) { let lastError: ErrorlastError = error as Error; // Don't retry user rejections if (error instanceof class SwapKitErrorSwapKitError && function (local var) error: SwapKitErrorerror.Error.message: stringmessage === 'wallet_connection_rejected_by_user') { throw function (local var) error: SwapKitErrorerror; } // Wait before retry with exponential backoff if (let i: numberi < maxRetries: numbermaxRetries - 1) { await new
var Promise: PromiseConstructor
new <unknown>(executor: (resolve: (value: unknown) => void, reject: (reason?: any) => void) => void) => Promise<unknown>
Creates a new Promise.
@paramexecutor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.
Promise
(resolve: (value: unknown) => voidresolve =>
function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout (+4 overloads)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)
setTimeout
(resolve: (value: unknown) => voidresolve, backoff: numberbackoff * var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math
.Math.pow(x: number, y: number): number
Returns the value of a base expression taken to a specified power.
@paramx The base value of the expression.@paramy The exponent value of the expression.
pow
(2, let i: numberi))
); } } } throw let lastError: ErrorlastError!; } } // Usage const const retry: SwapKitRetryretry = new constructor SwapKitRetry(): SwapKitRetrySwapKitRetry(); const const result: anyresult = await const retry: SwapKitRetryretry.SwapKitRetry.executeWithRetry<any>(operation: () => Promise<any>, maxRetries?: number, backoff?: number): Promise<any>executeWithRetry(async () => { return await
Cannot find name 'swapKit'.
swapKit
No value exists in scope for the shorthand property 'route'. Either declare one or provide an initializer.
.swap({ route });
});
class class SwapKitCacheSwapKitCache {
  private 
SwapKitCache.cache: Map<string, {
    data: any;
    timestamp: number;
}>
cache
= new
var Map: MapConstructor
new <string, {
    data: any;
    timestamp: number;
}>(iterable?: Iterable<readonly [string, {
    data: any;
    timestamp: number;
}]> | null | undefined) => Map<string, {
    data: any;
    timestamp: number;
}> (+3 overloads)
Map
<string, { data: anydata: any, timestamp: numbertimestamp: number }>();
private SwapKitCache.ttl: numberttl = 60000; // 1 minute SwapKitCache.set(key: string, data: any): voidset(key: stringkey: string, data: anydata: any) { this.
SwapKitCache.cache: Map<string, {
    data: any;
    timestamp: number;
}>
cache
.
Map<string, { data: any; timestamp: number; }>.set(key: string, value: {
    data: any;
    timestamp: number;
}): Map<string, {
    data: any;
    timestamp: number;
}>
Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
set
(key: stringkey, { data: anydata, timestamp: numbertimestamp: var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date
.DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now
() });
} SwapKitCache.get(key: string): anyget(key: stringkey: string) { const
const entry: {
    data: any;
    timestamp: number;
} | undefined
entry
= this.
SwapKitCache.cache: Map<string, {
    data: any;
    timestamp: number;
}>
cache
.
Map<string, { data: any; timestamp: number; }>.get(key: string): {
    data: any;
    timestamp: number;
} | undefined
Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
@returnsReturns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
get
(key: stringkey);
if (!
const entry: {
    data: any;
    timestamp: number;
} | undefined
entry
) return null;
if (var Date: DateConstructor
Enables basic storage and retrieval of dates and times.
Date
.DateConstructor.now(): number
Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
now
() -
const entry: {
    data: any;
    timestamp: number;
}
entry
.timestamp: numbertimestamp > this.SwapKitCache.ttl: numberttl) {
this.
SwapKitCache.cache: Map<string, {
    data: any;
    timestamp: number;
}>
cache
.Map<string, { data: any; timestamp: number; }>.delete(key: string): boolean
@returnstrue if an element in the Map existed and has been removed, or false if the element does not exist.
delete
(key: stringkey);
return null; } return
const entry: {
    data: any;
    timestamp: number;
}
entry
.data: anydata;
} } // Use cache for quotes const const cache: SwapKitCachecache = new constructor SwapKitCache(): SwapKitCacheSwapKitCache(); async function function getCachedQuote(params: any): Promise<any>getCachedQuote(params: anyparams: any) { const const key: stringkey = var JSON: JSON
An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON
.JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)
Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
@paramvalue A JavaScript value, usually an object or array, to be converted.@paramreplacer A function that transforms the results.@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
stringify
(params: anyparams);
const const cached: anycached = const cache: SwapKitCachecache.SwapKitCache.get(key: string): anyget(const key: stringkey); if (const cached: anycached) return const cached: anycached; const const quote: anyquote = await
Cannot find name 'SwapKitApi'.
SwapKitApi
.getSwapQuote(params: anyparams);
const cache: SwapKitCachecache.SwapKitCache.set(key: string, data: any): voidset(const key: stringkey, const quote: anyquote); return const quote: anyquote; }