Production Best Practices
Building production-ready applications with SwapKit requires careful attention to security, performance, and user experience. This guide covers essential best practices.
Security
Section titled “Security”API Key Management
Section titled “API Key Management”For frontend applications, use a backend proxy to keep API keys secure:
// Frontend
const const quote: any
quote = await function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+3 overloads)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch)fetch('/api/swap-quote', {
RequestInit.method?: string | undefined
A string to set request's method.method: 'POST',
RequestInit.body?: BodyInit | null | undefined
A BodyInit object or null to set request's body.body: 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.stringify(Cannot find name 'quoteParams'.quoteParams)
}).Promise<Response>.then<any, never>(onfulfilled?: ((value: Response) => any) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<any>
Attaches callbacks for the resolution and/or rejection of the Promise.then(r: Response
r => r: Response
r.Body.json(): Promise<any> (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)json());
// Backend API route
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';
export async function function POST(request: Request): Promise<Response>
POST(request: Request
request: Request) {
const const params: any
params = await request: Request
request.Body.json(): Promise<any> (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)json();
// Add API key server-side
const const quote: {
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;
}
quote = 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({
...const params: any
params,
apiKey: string | undefined
apiKey: var process: NodeJS.Process
process.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.env.string | undefined
SWAPKIT_API_KEY
});
return var Response: {
new (body?: BodyInit | null, init?: ResponseInit): Response;
prototype: Response;
error(): Response;
json(data: any, init?: ResponseInit): Response;
redirect(url: string | URL, status?: number): Response;
}
This Fetch API interface represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response.function json(data: any, init?: ResponseInit): Response
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)json(const quote: {
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;
}
quote);
}
Private Key Handling
Section titled “Private Key Handling”Always use secure wallet connections instead of handling private keys directly:
import { function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
createSwapKit, enum Chain
Chain } from '@swapkit/sdk';
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();
// ✅ Use secure wallet connections
await const swapKit: {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
swapKit.connectEVMWallet: (chains: Chain[], walletType?: EVMWalletOptions | undefined, eip1193Provider?: Eip1193Provider | undefined) => Promise<boolean>
connectEVMWallet([enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum]); // MetaMask
await const swapKit: {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
swapKit.connectLedger: (chains: Chain[], derivationPath?: DerivationPathArray | undefined) => Promise<boolean>
connectLedger([enum Chain
Chain.function (enum member) Chain.Bitcoin = "BTC"
Bitcoin]); // Hardware wallet
await const swapKit: {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
swapKit.Expected 2 arguments, but got 1.connectTrezor([enum Chain
Chain.function (enum member) Chain.Bitcoin = "BTC"
Bitcoin]); // Trezor wallet
Input Validation
Section titled “Input Validation”Always validate user inputs:
import { function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
createSwapKit, class SwapKitError
SwapKitError } from '@swapkit/sdk';
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();
function function validateSwapInput(params: any): void
validateSwapInput(params: any
params: any): void {
// Validate addresses
if (!const swapKit: {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
swapKit.Property 'validateAddress' does not exist on type '{ chainflip: { supportedSwapkitProviders: ProviderName[]; } & { swap: (swapParams: RequestSwapDepositAddressParams) => Promise<string>; }; ... 5 more ...; near: { ...; } & { ...; }; } & { ...; } & { ...; }'.validateAddress(params: any
params.recipient, params: any
params.chain)) {
throw new new SwapKitError(errorOrErrorKey: ErrorKeys | {
errorKey: ErrorKeys;
info?: Record<string, any>;
}, sourceErrorOrInfo?: any): SwapKitError
SwapKitError('core_swap_invalid_params', {
message: string
message: 'Invalid recipient address'
});
}
// Validate amounts
const const amount: number
amount = 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(params: any
params.amount);
if (function isNaN(number: number): boolean
Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).isNaN(const amount: number
amount) || const amount: number
amount <= 0) {
throw new new SwapKitError(errorOrErrorKey: ErrorKeys | {
errorKey: ErrorKeys;
info?: Record<string, any>;
}, sourceErrorOrInfo?: any): SwapKitError
SwapKitError('core_swap_invalid_params', {
message: string
message: 'Invalid amount'
});
}
// Validate slippage
if (params: any
params.slippage < 0 || params: any
params.slippage > 50) {
throw new new SwapKitError(errorOrErrorKey: ErrorKeys | {
errorKey: ErrorKeys;
info?: Record<string, any>;
}, sourceErrorOrInfo?: any): SwapKitError
SwapKitError('core_swap_invalid_params', {
message: string
message: 'Slippage must be between 0 and 50%'
});
}
}
Performance Optimization
Section titled “Performance Optimization”Bundle Size Reduction
Section titled “Bundle Size Reduction”Use the modular approach for smaller bundles:
// Import only what you need
import { function SwapKit<Plugins extends ReturnType<typeof createPlugin>, Wallets extends ReturnType<typeof createWallet>>({ config, plugins, wallets, }?: {
config?: SKConfigState;
plugins?: Plugins;
wallets?: Wallets;
}): { [key in keyof Plugins]: ReturnType<...>; } & ... 1 more ... & {
...;
}
SwapKit, const ThorchainPlugin: {
thorchain: (pluginParams: SwapKitPluginParams) => {
supportedSwapkitProviders: ProviderName[];
} & {
addLiquidity: ({ baseAssetValue, assetValue, baseAssetAddr, assetAddr, isPendingSymmAsset, mode, }: AddLiquidityParams) => Promise<...>;
... 11 more ...;
withdraw: ({ memo, assetValue, percent, from, to }: WithdrawParams) => Promise<...>;
};
}
ThorchainPlugin, const evmWallet: {
connectEVMWallet: {
connectWallet: (connectParams: {
addChain: AddChainType;
}) => (chains: Chain[], walletType?: EVMWalletOptions | undefined, eip1193Provider?: Eip1193Provider | undefined) => Promise<boolean>;
supportedChains: EVMChain[];
};
}
evmWallet } from '@swapkit/sdk';
const const swapKit: {
thorchain: {
supportedSwapkitProviders: ProviderName[];
} & {
addLiquidity: ({ baseAssetValue, assetValue, baseAssetAddr, assetAddr, isPendingSymmAsset, mode, }: AddLiquidityParams) => Promise<{
baseAssetTx: string | undefined;
assetTx: string | undefined;
}>;
... 11 more ...;
withdraw: ({ memo, assetValue, percent, from, to }: WithdrawParams) => Promise<...>;
};
} & {
...;
} & {
...;
}
swapKit = SwapKit<{
thorchain: (pluginParams: SwapKitPluginParams) => {
supportedSwapkitProviders: ProviderName[];
} & {
addLiquidity: ({ baseAssetValue, assetValue, baseAssetAddr, assetAddr, isPendingSymmAsset, mode, }: AddLiquidityParams) => Promise<...>;
... 11 more ...;
withdraw: ({ memo, assetValue, percent, from, to }: WithdrawParams) => Promise<...>;
};
}, {
...;
}>({ config, plugins, wallets, }?: {
...;
}): {
...;
} & ... 1 more ... & {
...;
}
SwapKit({
plugins?: {
thorchain: (pluginParams: SwapKitPluginParams) => {
supportedSwapkitProviders: ProviderName[];
} & {
addLiquidity: ({ baseAssetValue, assetValue, baseAssetAddr, assetAddr, isPendingSymmAsset, mode, }: AddLiquidityParams) => Promise<...>;
... 11 more ...;
withdraw: ({ memo, assetValue, percent, from, to }: WithdrawParams) => Promise<...>;
};
} | undefined
plugins: { ...const ThorchainPlugin: {
thorchain: (pluginParams: SwapKitPluginParams) => {
supportedSwapkitProviders: ProviderName[];
} & {
addLiquidity: ({ baseAssetValue, assetValue, baseAssetAddr, assetAddr, isPendingSymmAsset, mode, }: AddLiquidityParams) => Promise<...>;
... 11 more ...;
withdraw: ({ memo, assetValue, percent, from, to }: WithdrawParams) => Promise<...>;
};
}
ThorchainPlugin },
wallets?: {
connectEVMWallet: {
connectWallet: (connectParams: {
addChain: AddChainType;
}) => (chains: Chain[], walletType?: EVMWalletOptions | undefined, eip1193Provider?: Eip1193Provider | undefined) => Promise<boolean>;
supportedChains: EVMChain[];
};
} | undefined
wallets: { ...const evmWallet: {
connectEVMWallet: {
connectWallet: (connectParams: {
addChain: AddChainType;
}) => (chains: Chain[], walletType?: EVMWalletOptions | undefined, eip1193Provider?: Eip1193Provider | undefined) => Promise<boolean>;
supportedChains: EVMChain[];
};
}
evmWallet }
});
// Imports everything - larger bundle
import { function createSwapKit(config?: Parameters<typeof SwapKit>[0]): {
chainflip: {
supportedSwapkitProviders: ProviderName[];
} & {
swap: (swapParams: RequestSwapDepositAddressParams) => Promise<...>;
};
... 5 more ...;
near: {
...;
} & {
...;
};
} & {
...;
} & {
...;
}
createSwapKit } from '@swapkit/sdk';
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();
Lazy Loading Toolboxes
Section titled “Lazy Loading Toolboxes”Load toolboxes only when needed:
import { enum Chain
Chain } from '@swapkit/sdk';
// Lazy load toolboxes
async function function getToolboxForChain(chain: Chain): Promise<{
estimateTransactionFee: ({ feeOption, chain, ...txObject }: EIP1559TxParams & {
feeOption: FeeOption;
chain: EVMChain;
}) => Promise<...>;
... 20 more ...;
validateAddress: (address: string) => boolean;
} | ... 10 more ... | {
...;
}>
getToolboxForChain(chain: Chain
chain: enum Chain
Chain) {
switch (chain: Chain
chain) {
case enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum:
const { const getEvmToolbox: <T extends EVMChain>(chain: T, params?: EVMToolboxParams) => Promise<{
estimateTransactionFee: ({ feeOption, chain, ...txObject }: EIP1559TxParams & {
feeOption: FeeOption;
chain: EVMChain;
}) => Promise<...>;
... 20 more ...;
validateAddress: (address: string) => boolean;
} | {
...;
} | {
...;
}>
getEvmToolbox } = await import('@swapkit/sdk');
return const getEvmToolbox: <Chain.Ethereum>(chain: Chain.Ethereum, params?: EVMToolboxParams) => Promise<{
estimateTransactionFee: ({ feeOption, chain, ...txObject }: EIP1559TxParams & {
feeOption: FeeOption;
chain: EVMChain;
}) => Promise<...>;
... 20 more ...;
validateAddress: (address: string) => boolean;
} | {
...;
} | {
...;
}>
getEvmToolbox(chain: Chain.Ethereum
chain);
case enum Chain
Chain.function (enum member) Chain.Bitcoin = "BTC"
Bitcoin:
const { const getUtxoToolbox: <T extends keyof UTXOToolboxes>(chain: T, params?: UtxoToolboxParams[T] | {
phrase?: string;
derivationPath?: DerivationPathArray;
index?: number;
}) => Promise<UTXOToolboxes[T]>
getUtxoToolbox } = await import('@swapkit/sdk');
return const getUtxoToolbox: <Chain.Bitcoin>(chain: Chain.Bitcoin, params?: {
signer: ChainSigner<Psbt, Psbt>;
} | {
phrase?: string;
derivationPath?: DerivationPathArray;
index?: number;
} | undefined) => Promise<...>
getUtxoToolbox(chain: Chain.Bitcoin
chain);
default:
const { const getToolbox: <T extends Chain.Radix | Chain.Ripple | Chain.Solana | Chain.Tron | EVMChain | UTXOChain | CosmosChain | SubstrateChain>(chain: T, params?: ToolboxParams[T]) => Promise<Toolboxes[T]>
getToolbox } = await import('@swapkit/sdk');
return const getToolbox: <Chain.Radix | Chain.Ripple | Chain.Solana | Chain.Tron | EVMChain | UTXOChain | CosmosChain | SubstrateChain>(chain: Chain.Radix | ... 6 more ... | SubstrateChain, params?: {} | ... 12 more ... | undefined) => Promise<...>
getToolbox(Argument of type 'Chain.Arbitrum | Chain.Avalanche | Chain.Base | Chain.BinanceSmartChain | Chain.BitcoinCash | Chain.Cosmos | Chain.Dash | Chain.Dogecoin | Chain.Fiat | Chain.Kujira | Chain.Litecoin | Chain.Maya | ... 9 more ... | Chain.Tron' is not assignable to parameter of type 'Chain.Radix | Chain.Ripple | Chain.Solana | Chain.Tron | EVMChain | UTXOChain | CosmosChain | SubstrateChain'.
Type 'Chain.Fiat' is not assignable to type 'Chain.Radix | Chain.Ripple | Chain.Solana | Chain.Tron | EVMChain | UTXOChain | CosmosChain | SubstrateChain'.chain);
}
}
Request Caching
Section titled “Request Caching”Implement caching for frequently accessed data:
class class SwapKitCache
SwapKitCache {
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: any
data: any; timestamp: number
timestamp: number }>();
private SwapKitCache.ttl: Record<string, number>
ttl: type Record<K extends keyof any, T> = { [P in K]: T; }
Construct a type with a set of properties K of type TRecord<string, number> = {
price: number
price: 60_000, // 1 minute
balance: number
balance: 300_000, // 5 minutes
quote: number
quote: 30_000, // 30 seconds
};
async SwapKitCache.get<T>(key: string, type: keyof typeof this.ttl, fetcher: () => Promise<T>): Promise<T>
get<function (type parameter) T in SwapKitCache.get<T>(key: string, type: keyof typeof this.ttl, fetcher: () => Promise<T>): Promise<T>
T>(
key: string
key: string,
type: string
type: keyof typeof this: this
this.SwapKitCache.ttl: Record<string, number>
ttl,
fetcher: () => Promise<T>
fetcher: () => interface Promise<T>
Represents the completion of an asynchronous operationPromise<function (type parameter) T in SwapKitCache.get<T>(key: string, type: keyof typeof this.ttl, fetcher: () => Promise<T>): Promise<T>
T>
): interface Promise<T>
Represents the completion of an asynchronous operationPromise<function (type parameter) T in SwapKitCache.get<T>(key: string, type: keyof typeof this.ttl, fetcher: () => Promise<T>): Promise<T>
T> {
const const cached: {
data: any;
timestamp: number;
} | undefined
cached = 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.get(key: string
key);
const const now: number
now = 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();
if (const cached: {
data: any;
timestamp: number;
} | undefined
cached && const now: number
now - const cached: {
data: any;
timestamp: number;
}
cached.timestamp: number
timestamp < this.SwapKitCache.ttl: Record<string, number>
ttl[type: string
type]) {
return const cached: {
data: any;
timestamp: number;
}
cached.data: any
data;
}
const const data: Awaited<T>
data = await fetcher: () => Promise<T>
fetcher();
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: string
key, { data: any
data, timestamp: number
timestamp: const now: number
now });
return const data: Awaited<T>
data;
}
}
const const cache: SwapKitCache
cache = new constructor SwapKitCache(): SwapKitCache
SwapKitCache();
// Use cache for prices
const const price: {
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
name: string;
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;
}[]
price = await const cache: SwapKitCache
cache.SwapKitCache.get<{
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
name: string;
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;
}[]>(key: string, type: keyof typeof this.ttl, fetcher: () => Promise<...>): Promise<...>
get(
`price_${Cannot find name 'asset'. Did you mean 'Set'?asset}`,
'price',
async () => {
const { 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 } = await import('@swapkit/helpers/api');
return 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<{
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
... 5 more ...;
total_volume: number;
} | undefined;
price_usd?: number | undefined;
}[]>
getPrice(Cannot find name 'asset'. Did you mean 'Set'?asset);
}
);
Batch Operations
Section titled “Batch Operations”Batch multiple operations for efficiency:
import { enum Chain
Chain } from '@swapkit/sdk';
// ❌ Inefficient - multiple sequential calls
const const ethBalance: any
ethBalance = await Cannot find name 'swapKit'.swapKit.getBalance(enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum);
const const btcBalance: any
btcBalance = await Cannot find name 'swapKit'.swapKit.getBalance(enum Chain
Chain.function (enum member) Chain.Bitcoin = "BTC"
Bitcoin);
const const avaxBalance: any
avaxBalance = await Cannot find name 'swapKit'.swapKit.getBalance(enum Chain
Chain.function (enum member) Chain.Avalanche = "AVAX"
Avalanche);
// ✅ Efficient - parallel calls
const const chains: Chain[]
chains = [enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum, enum Chain
Chain.function (enum member) Chain.Bitcoin = "BTC"
Bitcoin, enum Chain
Chain.function (enum member) Chain.Avalanche = "AVAX"
Avalanche];
const const balances: any
balances = await var Promise: PromiseConstructor
Represents the completion of an asynchronous operationPromise.PromiseConstructor.all<any[]>(values: any[]): Promise<any> (+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.all(
const chains: Chain[]
chains.Array<Chain>.map<any>(callbackfn: (value: Chain, index: number, array: Chain[]) => any, thisArg?: any): any[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.map(chain: Chain
chain => Cannot find name 'swapKit'.swapKit.getBalance(chain: Chain
chain))
);
Error Handling
Section titled “Error Handling”Comprehensive Error Handling
Section titled “Comprehensive Error Handling”Handle all error scenarios gracefully:
import { class SwapKitError
SwapKitError } from '@swapkit/sdk';
async function function executeSwap(route: SwapRoute): Promise<{
success: boolean;
txHash: any;
error?: undefined;
} | {
success: boolean;
error: string;
txHash?: undefined;
}>
executeSwap(route: SwapRoute
route: Cannot find name 'SwapRoute'.SwapRoute) {
try {
const const txHash: any
txHash = await Cannot find name 'swapKit'.swapKit.swap({ route: SwapRoute
route });
return { success: boolean
success: true, txHash: any
txHash };
} catch (error) {
if (error instanceof class SwapKitError
SwapKitError) {
// Handle SwapKit-specific errors
switch (function (local var) error: SwapKitError
error.Property 'code' does not exist on type 'SwapKitError'.code) {
case 'wallet_not_connected':
return { success: boolean
success: false, error: string
error: 'Please connect your wallet' };
case 'insufficient_balance':
return { success: boolean
success: false, error: string
error: 'Insufficient balance' };
case 'user_rejected':
return { success: boolean
success: false, error: string
error: 'Transaction cancelled' };
default:
return { success: boolean
success: false, error: string
error: function (local var) error: SwapKitError
error.Error.message: string
message };
}
}
// Handle network errors
if (error instanceof var Error: ErrorConstructor
Error && function (local var) error: Error
error.Error.message: string
message.String.includes(searchString: string, position?: number): boolean
Returns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.includes('network')) {
return { success: boolean
success: false, error: string
error: 'Network error. Please try again.' };
}
// Unknown error
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.error('Unexpected error:', error);
return { success: boolean
success: false, error: string
error: 'An unexpected error occurred' };
}
}
Retry Logic
Section titled “Retry Logic”Implement retry logic for transient failures:
import { class SwapKitError
SwapKitError, 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/sdk';
async function function withRetry<T>(fn: () => Promise<T>, options?: {
maxRetries: number;
delay: number;
}): Promise<T>
withRetry<function (type parameter) T in withRetry<T>(fn: () => Promise<T>, options?: {
maxRetries: number;
delay: number;
}): Promise<T>
T>(
fn: () => Promise<T>
fn: () => interface Promise<T>
Represents the completion of an asynchronous operationPromise<function (type parameter) T in withRetry<T>(fn: () => Promise<T>, options?: {
maxRetries: number;
delay: number;
}): Promise<T>
T>,
options: {
maxRetries: number;
delay: number;
}
options = { maxRetries: number
maxRetries: 3, delay: number
delay: 1000 }
): interface Promise<T>
Represents the completion of an asynchronous operationPromise<function (type parameter) T in withRetry<T>(fn: () => Promise<T>, options?: {
maxRetries: number;
delay: number;
}): Promise<T>
T> {
let let lastError: Error
lastError: Error;
for (let let i: number
i = 0; let i: number
i <= options: {
maxRetries: number;
delay: number;
}
options.maxRetries: number
maxRetries; let i: number
i++) {
try {
return await fn: () => Promise<T>
fn();
} catch (error) {
let lastError: Error
lastError = error as Error;
// Don't retry user rejections
if (error instanceof class SwapKitError
SwapKitError &&
function (local var) error: SwapKitError
error.Property 'code' does not exist on type 'SwapKitError'.code === 'user_rejected') {
throw function (local var) error: SwapKitError
error;
}
// Wait before retry
if (let i: number
i < options: {
maxRetries: number;
delay: number;
}
options.maxRetries: number
maxRetries) {
await new var Promise: PromiseConstructor
new <unknown>(executor: (resolve: (value: unknown) => void, reject: (reason?: any) => void) => void) => Promise<unknown>
Creates a new Promise.Promise(r: (value: unknown) => void
r => function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout (+4 overloads)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)setTimeout(r: (value: unknown) => void
r, options: {
maxRetries: number;
delay: number;
}
options.delay: number
delay * (let i: number
i + 1)));
}
}
}
throw let lastError: Error
lastError!;
}
// Usage
const const quote: {
quoteId: string;
routes: {
sellAsset: string;
buyAsset: string;
destinationAddress: string;
sellAmount: string;
providers: ProviderName[];
sourceAddress: string;
expectedBuyAmount: string;
... 12 more ...;
estimatedTime?: {
...;
} | undefined;
}[];
error?: string | undefined;
providerErrors?: {
...;
}[] | undefined;
}
quote = await function withRetry<{
quoteId: string;
routes: {
sellAsset: string;
buyAsset: string;
destinationAddress: string;
sellAmount: string;
providers: ProviderName[];
sourceAddress: string;
expectedBuyAmount: string;
... 12 more ...;
estimatedTime?: {
...;
} | undefined;
}[];
error?: string | undefined;
providerErrors?: {
...;
}[] | undefined;
}>(fn: () => Promise<...>, options?: {
...;
}): Promise<...>
withRetry(() =>
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;
sellAmount: string;
providers: ProviderName[];
... 14 more ...;
estimatedTime?: {
...;
} | undefined;
}[];
error?: string | undefined;
providerErrors?: {
...;
}[] | undefined;
}>
getSwapQuote(Cannot find name 'params'.params)
);
User Experience
Section titled “User Experience”Loading States
Section titled “Loading States”Provide clear feedback during operations:
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/sdk';
interface SwapState {
SwapState.status: "idle" | "quoting" | "approving" | "swapping" | "success" | "error"
status: 'idle' | 'quoting' | 'approving' | 'swapping' | 'success' | 'error';
SwapState.message?: string | undefined
message?: string;
SwapState.txHash?: string | undefined
txHash?: string;
}
async function function performSwap(params: SwapParams): Promise<void>
performSwap(params: SwapParams
params: Cannot find name 'SwapParams'. Did you mean 'RsaPssParams'?SwapParams) {
const const setState: (update: Partial<SwapState>) => void
setState = (update: Partial<SwapState>
update: type Partial<T> = { [P in keyof T]?: T[P] | undefined; }
Make all properties in T optionalPartial<SwapState>) => {
// Update UI state
};
try {
const setState: (update: Partial<SwapState>) => void
setState({ status?: "idle" | "quoting" | "approving" | "swapping" | "success" | "error" | undefined
status: 'quoting', message?: string | undefined
message: 'Getting best price...' });
const const quote: {
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;
}
quote = 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(params: SwapParams
params);
const setState: (update: Partial<SwapState>) => void
setState({ status?: "idle" | "quoting" | "approving" | "swapping" | "success" | "error" | undefined
status: 'approving', message?: string | undefined
message: 'Approving tokens...' });
await Cannot find name 'swapKit'.swapKitCannot find name 'assetValue'..approveAssetValue(assetValue);
const setState: (update: Partial<SwapState>) => void
setState({ status?: "idle" | "quoting" | "approving" | "swapping" | "success" | "error" | undefined
status: 'swapping', message?: string | undefined
message: 'Executing swap...' });
const const txHash: any
txHash = 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 quote: {
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;
}
quote.routes: {
sellAsset: string;
buyAsset: string;
destinationAddress: string;
providers: ProviderName[];
sellAmount: string;
expectedBuyAmount: string;
expectedBuyAmountMaxSlippage: string;
... 12 more ...;
estimatedTime?: {
...;
} | undefined;
}[]
routes[0] });
const setState: (update: Partial<SwapState>) => void
setState({ status?: "idle" | "quoting" | "approving" | "swapping" | "success" | "error" | undefined
status: 'success', txHash?: string | undefined
txHash });
} catch (error) {
const setState: (update: Partial<SwapState>) => void
setState({
status?: "idle" | "quoting" | "approving" | "swapping" | "success" | "error" | undefined
status: 'error',
message?: string | undefined
message: Cannot find name 'getErrorMessage'.getErrorMessage(error)
});
}
}
Transaction Tracking
Section titled “Transaction Tracking”Track transaction status for better UX:
import { enum Chain
Chain, 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/sdk';
async function function trackTransaction(txHash: string, chain: Chain, onUpdate: (status: string) => void): Promise<TrackerResponse>
trackTransaction(
txHash: string
txHash: string,
chain: Chain
chain: enum Chain
Chain,
onUpdate: (status: string) => void
onUpdate: (status: string
status: string) => void
) {
let let attempts: number
attempts = 0;
const const maxAttempts: 60
maxAttempts = 60; // 5 minutes with 5s intervals
while (let attempts: number
attempts < const maxAttempts: 60
maxAttempts) {
try {
const const status: TrackerResponse
status = 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({ Object literal may only specify known properties, but 'txHash' does not exist in type 'TrackerParams'. Did you mean to write 'hash'?txHash, chain: Chain
chain });
onUpdate: (status: string) => void
onUpdate(Argument of type 'import("/home/runner/work/SwapKit/SwapKit/packages/helpers/src/api/swapkitApi/types").TxnStatus | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.status.status);
if (const status: TrackerResponse
status.TransactionProps.status?: TxnStatus | undefined
status === 'completed' || 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') {
return const status: TrackerResponse
status;
}
} catch (error) {
// Continue polling
}
await new var Promise: PromiseConstructor
new <unknown>(executor: (resolve: (value: unknown) => void, reject: (reason?: any) => void) => void) => Promise<unknown>
Creates a new Promise.Promise(r: (value: unknown) => void
r => function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout (+4 overloads)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)setTimeout(r: (value: unknown) => void
r, 5000));
let attempts: number
attempts++;
}
throw new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+2 overloads)
Error('Transaction tracking timeout');
}
Network Configuration
Section titled “Network Configuration”RPC Failover
Section titled “RPC Failover”Configure multiple RPC endpoints for reliability:
import { enum Chain
Chain } from '@swapkit/sdk';
const const rpcEndpoints: {
ETH: (string | undefined)[];
AVAX: (string | undefined)[];
}
rpcEndpoints = {
[enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum]: [
var process: NodeJS.Process
process.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.env.string | undefined
ALCHEMY_ETH_RPC,
var process: NodeJS.Process
process.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.env.string | undefined
INFURA_ETH_RPC,
'https://eth.llamarpc.com'
].Array<string | undefined>.filter(predicate: (value: string | undefined, index: number, array: (string | undefined)[]) => unknown, thisArg?: any): (string | undefined)[] (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.filter(var Boolean: BooleanConstructor
Boolean),
[enum Chain
Chain.function (enum member) Chain.Avalanche = "AVAX"
Avalanche]: [
var process: NodeJS.Process
process.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.env.string | undefined
AVALANCHE_RPC,
'https://api.avax.network/ext/bc/C/rpc'
].Array<string | undefined>.filter(predicate: (value: string | undefined, index: number, array: (string | undefined)[]) => unknown, thisArg?: any): (string | undefined)[] (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.filter(var Boolean: BooleanConstructor
Boolean)
};
// Failover logic
async function function getRpcUrl(chain: Chain): Promise<string>
getRpcUrl(chain: Chain
chain: enum Chain
Chain): interface Promise<T>
Represents the completion of an asynchronous operationPromise<string> {
const const endpoints: any
endpoints = Element implicitly has an 'any' type because expression of type 'Chain' can't be used to index type '{ ETH: (string | undefined)[]; AVAX: (string | undefined)[]; }'.
Property '[Chain.Arbitrum]' does not exist on type '{ ETH: (string | undefined)[]; AVAX: (string | undefined)[]; }'.rpcEndpoints[chain] || [];
for (const const url: any
url of const endpoints: any
endpoints) {
try {
const const response: Response
response = await function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+3 overloads)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch)fetch(const url: any
url, {
RequestInit.method?: string | undefined
A string to set request's method.method: 'POST',
RequestInit.body?: BodyInit | null | undefined
A BodyInit object or null to set request's body.body: 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.stringify({ method: string
method: 'eth_blockNumber', params: never[]
params: [], id: number
id: 1 })
});
if (const response: Response
response.Response.ok: boolean
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok)ok) return const url: any
url;
} catch {
continue;
}
}
throw new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+2 overloads)
Error(`No working RPC for ${chain: Chain
chain}`);
}
Gas Price Management
Section titled “Gas Price Management”Implement dynamic gas pricing:
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/sdk';
async function function getOptimalGasPrice(chain: Chain, priority: "low" | "medium" | "high"): Promise<{
maxFeePerGas: number;
maxPriorityFeePerGas: number;
}>
getOptimalGasPrice(chain: Chain
chain: Cannot find name 'Chain'.Chain, priority: "low" | "medium" | "high"
priority: 'low' | 'medium' | 'high') {
const const gasRates: {
value: string;
id: number;
chainId: string;
unit: string;
createdAt: string;
}[]
gasRates = 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(Expected 0 arguments, but got 1.chain);
const const multipliers: {
low: number;
medium: number;
high: number;
}
multipliers = {
low: number
low: 0.9,
medium: number
medium: 1.0,
high: number
high: 1.5
};
return {
maxFeePerGas: number
maxFeePerGas: 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.floor(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 gasRates: {
value: string;
id: number;
chainId: string;
unit: string;
createdAt: string;
}[]
gasRates) * const multipliers: {
low: number;
medium: number;
high: number;
}
multipliers[priority: "low" | "medium" | "high"
priority]),
maxPriorityFeePerGas: number
maxPriorityFeePerGas: 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.floor(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 gasRates: {
value: string;
id: number;
chainId: string;
unit: string;
createdAt: string;
}[]
gasRates) * 0.1)
};
}
Monitoring & Analytics
Section titled “Monitoring & Analytics”Error Tracking
Section titled “Error Tracking”Track errors for debugging:
import * as import Sentry
Sentry from Cannot find module '@sentry/browser' or its corresponding type declarations.'@sentry/browser';
// Initialize error tracking
import Sentry
Sentry.init({
dsn: string | undefined
dsn: var process: NodeJS.Process
process.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.env.string | undefined
SENTRY_DSN,
environment: string | undefined
environment: var process: NodeJS.Process
process.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.env.Env.NODE_ENV?: string | undefined
NODE_ENV,
function beforeSend(event: any, hint: any): any
beforeSend(Parameter 'event' implicitly has an 'any' type.eventParameter 'hint' implicitly has an 'any' type., hint) {
// Don't send sensitive data
if (event: any
event.request?.data) {
delete event: any
event.request.data.privateKey;
delete event: any
event.request.data.mnemonic;
}
return event: any
event;
}
});
// Track SwapKit errors
try {
await Cannot find name 'swapKit'.swapKitNo value exists in scope for the shorthand property 'route'. Either declare one or provide an initializer..swap({ route });
} catch (var error: unknown
error) {
import Sentry
Sentry.captureException(var error: unknown
error, {
tags: {
chain: any;
provider: any;
}
tags: {
chain: any
chain: Cannot find name 'route'.route.sellAsset.split('.')[0],
provider: any
provider: Cannot find name 'route'.route.providers[0]
}
});
throw var error: unknown
error;
}
Performance Monitoring
Section titled “Performance Monitoring”Track key metrics:
class class PerformanceTracker
PerformanceTracker {
PerformanceTracker.track(operation: string, fn: () => Promise<any>): Promise<any>
track(operation: string
operation: string, fn: () => Promise<any>
fn: () => interface Promise<T>
Represents the completion of an asynchronous operationPromise<any>) {
const const start: number
start = var performance: Performance
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/performance)
`performance` is a global reference for `import { performance } from 'node:perf_hooks'`performance.Performance.now(): DOMHighResTimeStamp (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now)now();
return fn: () => Promise<any>
fn()
.Promise<any>.then<any, never>(onfulfilled?: ((value: any) => any) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<any>
Attaches callbacks for the resolution and/or rejection of the Promise.then(result: any
result => {
const const duration: number
duration = var performance: Performance
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/performance)
`performance` is a global reference for `import { performance } from 'node:perf_hooks'`performance.Performance.now(): DOMHighResTimeStamp (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now)now() - const start: number
start;
this.PerformanceTracker.report(operation: string, duration: number, status: string): void
report(operation: string
operation, const duration: number
duration, 'success');
return result: any
result;
})
.Promise<any>.catch<never>(onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<any>
Attaches a callback for only the rejection of the Promise.catch(error: any
error => {
const const duration: number
duration = var performance: Performance
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/performance)
`performance` is a global reference for `import { performance } from 'node:perf_hooks'`performance.Performance.now(): DOMHighResTimeStamp (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/now)now() - const start: number
start;
this.PerformanceTracker.report(operation: string, duration: number, status: string): void
report(operation: string
operation, const duration: number
duration, 'error');
throw error: any
error;
});
}
private PerformanceTracker.report(operation: string, duration: number, status: string): void
report(operation: string
operation: string, duration: number
duration: number, status: string
status: string) {
// Send to analytics
Cannot find name 'analytics'.analytics.track('operation_performance', {
operation: string
operation,
duration: number
duration,
status: string
status
});
}
}
const const tracker: PerformanceTracker
tracker = new constructor PerformanceTracker(): PerformanceTracker
PerformanceTracker();
// Track swap performance
const const txHash: any
txHash = await const tracker: PerformanceTracker
tracker.PerformanceTracker.track(operation: string, fn: () => Promise<any>): Promise<any>
track('swap', () =>
Cannot find name 'swapKit'.swapKitNo value exists in scope for the shorthand property 'route'. Either declare one or provide an initializer..swap({ route })
);
Deployment Checklist
Section titled “Deployment Checklist”Before deploying to production:
- Environment Variables: All sensitive data in env vars
- API Keys: Production keys configured, not exposed
- Error Handling: Comprehensive error handling implemented
- Monitoring: Error tracking and analytics configured
- Performance: Bundle optimized, lazy loading implemented
- Security: Input validation, secure wallet handling
- Testing: All features tested on mainnet
- Documentation: User guides and FAQs prepared
- Support: Support channels established
- Compliance: Legal requirements addressed
Testing in Production
Section titled “Testing in Production”Gradual Rollout
Section titled “Gradual Rollout”// Feature flags for gradual rollout
const const features: {
newSwapFlow: boolean;
thorchainSwaps: boolean;
}
features = {
newSwapFlow: boolean
newSwapFlow: var process: NodeJS.Process
process.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.env.string | undefined
ENABLE_NEW_SWAP_FLOW === 'true',
thorchainSwaps: boolean
thorchainSwaps: var process: NodeJS.Process
process.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.env.string | undefined
ENABLE_THORCHAIN === 'true'
};
if (const features: {
newSwapFlow: boolean;
thorchainSwaps: boolean;
}
features.newSwapFlow: boolean
newSwapFlow) {
// New implementation
} else {
// Stable implementation
}
Health Checks
Section titled “Health Checks”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, enum Chain
Chain } from '@swapkit/sdk';
async function function healthCheck(): Promise<HealthStatus>
healthCheck(): interface Promise<T>
Represents the completion of an asynchronous operationPromise<Cannot find name 'HealthStatus'.HealthStatus> {
const const checks: [PromiseSettledResult<{
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
name: string;
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;
}[]>, PromiseSettledResult<...>, PromiseSettledResult<...>]
checks = await var Promise: PromiseConstructor
Represents the completion of an asynchronous operationPromise.PromiseConstructor.allSettled<[Promise<{
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
name: string;
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;
}[]>, any, Promise<...>]>(values: [...]): Promise<...> (+1 overload)
Creates a Promise that is resolved with an array of results when all
of the provided Promises resolve or reject.allSettled([
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<{
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
... 5 more ...;
total_volume: number;
} | undefined;
price_usd?: number | undefined;
}[]>
getPrice(Argument of type 'string' is not assignable to parameter of type '{ tokens: { identifier: string; }[]; metadata: boolean; }'.'ETH'),
Cannot find name 'swapKit'.swapKit.validateAddress('0x...', enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum),
function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+3 overloads)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch)fetch(Cannot find name 'rpcUrls'.rpcUrls[enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum])
]);
return {
api: boolean
api: const checks: [PromiseSettledResult<{
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
name: string;
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;
}[]>, PromiseSettledResult<...>, PromiseSettledResult<...>]
checks[0].status: "rejected" | "fulfilled"
status === 'fulfilled',
sdk: boolean
sdk: const checks: [PromiseSettledResult<{
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
name: string;
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;
}[]>, PromiseSettledResult<...>, PromiseSettledResult<...>]
checks[1].status: "rejected" | "fulfilled"
status === 'fulfilled',
rpc: boolean
rpc: const checks: [PromiseSettledResult<{
identifier?: string | undefined;
provider?: string | undefined;
timestamp?: number | undefined;
cg?: {
id: string;
market_cap: number;
name: string;
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;
}[]>, PromiseSettledResult<...>, PromiseSettledResult<...>]
checks[2].status: "rejected" | "fulfilled"
status === 'fulfilled'
};
}
Next Steps
Section titled “Next Steps”- Review Security considerations
- Implement Advanced Features
- Monitor performance with API Reference