API Reference
The SwapKitApi
provides access to swap quotes, price feeds, token lists, and other essential data. All methods are available through the @swapkit/helpers/api
import.
Getting Started
Section titled “Getting Started”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';
// All methods are static - no initialization needed
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 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({
Object literal may only specify known properties, and 'identifier' does not exist in type '{ tokens: { identifier: string; }[]; metadata: boolean; }'.identifier: 'ETH.ETH',
currency: string
currency: 'USD'
});
Swap Quotes
Section titled “Swap Quotes”getSwapQuote
Section titled “getSwapQuote”Get swap quotes from multiple providers with best route selection:
const { const routes: any
routes } = await Cannot find name 'SwapKitApi'.SwapKitApi.getSwapQuote({
sellAsset: string
sellAsset: 'ETH.ETH',
sellAmount: string
sellAmount: '1000000000000000000', // 1 ETH in base units
buyAsset: string
buyAsset: 'BTC.BTC',
sourceAddress: string
sourceAddress: '0x...', // Your ETH address
destinationAddress: string
destinationAddress: 'bc1q...', // Your BTC address
slippage: number
slippage: 3, // 3% slippage tolerance
providers: string[]
providers: ['thorchain', 'chainflip', '1inch'], // Optional: specific providers
affiliate: string
affiliate: 'your-affiliate-id', // Optional: affiliate tracking
affiliateFee: number
affiliateFee: 100 // Optional: basis points (100 = 1%)
});
// Response structure
{
routes: [{
providers: string[]
providers: ['THORCHAIN'],
sellAsset: string
sellAsset: 'ETH.ETH',
sellAmount: string
sellAmount: '1000000000000000000',
buyAsset: string
buyAsset: 'BTC.BTC',
expectedBuyAmount: string
expectedBuyAmount: '62500000', // 0.625 BTC
expectedBuyAmountMaxSlippage: string
expectedBuyAmountMaxSlippage: '60625000', // With 3% slippage
sourceAddress: string
sourceAddress: '0x...',
destinationAddress: string
destinationAddress: 'bc1q...',
targetAddress: string
targetAddress: '0x...', // Contract to send to
memo: string
memo: 'SWAP:BTC.BTC:bc1q...',
expiration: string
expiration: '2024-01-01T00:00:00Z',
fee: {
asset: string;
networkFee: string;
affiliateFee: string;
totalFee: string;
}
fee: {
asset: string
asset: 'ETH.ETH',
networkFee: string
networkFee: '5000000000000000', // Network fee
affiliateFee: string
affiliateFee: '10000000000000000', // Affiliate fee
totalFee: string
totalFee: '15000000000000000' // Total fees
},
estimatedTime: {
inbound: number;
outbound: number;
total: number;
}
estimatedTime: {
inbound: number
inbound: 600, // 10 minutes inbound
outbound: number
outbound: 600, // 10 minutes outbound
total: number
total: 1200 // 20 minutes total
}
}]
}
Price Data
Section titled “Price Data”getPrice
Section titled “getPrice”Get current asset prices:
// Single asset price
const const priceData: any
priceData = await Cannot find name 'SwapKitApi'.SwapKitApi.getPrice({
identifier: string
identifier: 'ETH.ETH',
currency: string
currency: 'USD' // Optional, defaults to USD
});
// Returns: [{ identifier: 'ETH.ETH', price: 2500.50 }]
// Multiple assets
const const prices: any
prices = await Cannot find name 'SwapKitApi'.SwapKitApi.getPrice({
identifiers: string[]
identifiers: ['ETH.ETH', 'BTC.BTC', 'AVAX.AVAX'],
currency: string
currency: 'USD'
});
// Returns: [
// { identifier: 'ETH.ETH', price: 2500.50 },
// { identifier: 'BTC.BTC', price: 45000.00 },
// { identifier: 'AVAX.AVAX', price: 35.20 }
// ]
// With specific token addresses
const const tokenPrice: any
tokenPrice = await Cannot find name 'SwapKitApi'.SwapKitApi.getPrice({
identifier: string
identifier: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
});
Balance Operations
Section titled “Balance Operations”getChainBalance
Section titled “getChainBalance”Get all token balances for an address on a specific chain with scam filtering:
const const balances: any
balances = await Cannot find name 'SwapKitApi'.SwapKitApi.getChainBalance({
chain: string
chain: 'ETH',
address: string
address: '0x742d35Cc6634C0532925a3b844Bc9e7595f6E321',
scamFilter: boolean
scamFilter: true // Optional, defaults to true
});
// Response includes native and token balances
[
{
identifier: string
identifier: 'ETH.ETH',
value: string
value: '1500000000000000000', // 1.5 ETH
decimal: number
decimal: 18
},
{
identifier: string
identifier: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
value: string
value: '1000000000', // 1000 USDC
decimal: number
decimal: 6
}
]
Gas Rates
Section titled “Gas Rates”getGasRate
Section titled “getGasRate”Get current gas rates for supported chains:
// Get gas rates for all chains
const const gasRates: any
gasRates = await Cannot find name 'SwapKitApi'.SwapKitApi.getGasRate();
// Response format
{
ETH: {
low: Left side of comma operator is unused and has no side effects.'20', // Gwei
Cannot find name 'average'.averageLeft side of comma operator is unused and has no side effects.';' expected.: '25', // Gwei
Cannot find name 'high'.high';' expected.: '30' // Gwei
}Declaration or statement expected.,
BTC: {
low: Left side of comma operator is unused and has no side effects.'5', // Satoshis per byte
Cannot find name 'average'.averageLeft side of comma operator is unused and has no side effects.';' expected.: '10', // Satoshis per byte
Cannot find name 'high'.high';' expected.: '15' // Satoshis per byte
}Declaration or statement expected.,
AVAX: {
low: Left side of comma operator is unused and has no side effects.'25', // nAVAX
Cannot find name 'average'.averageLeft side of comma operator is unused and has no side effects.';' expected.: '30', // nAVAX
Cannot find name 'high'.high';' expected.: '35' // nAVAX
}
}
Token Lists
Section titled “Token Lists”getTokenList
Section titled “getTokenList”Get comprehensive token metadata from a specific provider:
// Get tokens from a specific provider
const const tokens: any
tokens = await Cannot find name 'SwapKitApi'.SwapKitApi.getTokenList('thorswap');
// Response structure
[
{
chain: string
chain: 'ETH',
symbol: string
symbol: 'USDC',
ticker: string
ticker: 'USDC',
identifier: string
identifier: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
address: string
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
decimals: number
decimals: 6,
logoURL: string
logoURL: 'https://...',
name: string
name: 'USD Coin'
}
]
getTokenListProviders
Section titled “getTokenListProviders”Get list of available token list providers:
const const providers: any
providers = await Cannot find name 'SwapKitApi'.SwapKitApi.getTokenListProviders();
// Returns available providers
[
{ name: string
name: 'thorswap', url: string
url: 'https://...' },
{ name: string
name: '1inch', url: string
url: 'https://...' },
{ name: string
name: 'coingecko', url: string
url: 'https://...' },
{ name: string
name: 'uniswap', url: string
url: 'https://...' }
]
Transaction Tracking
Section titled “Transaction Tracking”getTrackerDetails
Section titled “getTrackerDetails”Track transaction status and progress:
const const status: any
status = await Cannot find name 'SwapKitApi'.SwapKitApi.getTrackerDetails({
txHash: string
txHash: '0x123...',
chain: string
chain: 'ETH',
provider: string
provider: 'thorchain', // Optional: specific provider
actionId: string
actionId: 'swap_123' // Optional: action identifier
});
// Response for swap transactions
{
status: Left side of comma operator is unused and has no side effects.'completed',
Cannot find name 'startTime'.startTimeLeft side of comma operator is unused and has no side effects.';' expected.: 1234567890,
Cannot find name 'endTime'.endTimeLeft side of comma operator is unused and has no side effects.';' expected.: 1234568490,
Cannot find name 'legs'.legs';' expected.: [{
chain: string
chain: 'ETH',
hash: string
hash: '0x123...',
status: string
status: 'completed',
inAmount: string
inAmount: '1000000000000000000',
outAmount: string
outAmount: '62500000'
}]
}
Static Asset Data
Section titled “Static Asset Data”getStaticTokenList
Section titled “getStaticTokenList”Get token list from static Thorswap CDN:
// Get specific token list
const const tokens: any
tokens = await Cannot find name 'SwapKitApi'.SwapKitApi.getStaticTokenList('thorswap');
// Response contains comprehensive token data
[
{
chain: string
chain: 'ETH',
symbol: string
symbol: 'USDC',
ticker: string
ticker: 'USDC',
identifier: string
identifier: 'ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
address: string
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
decimals: number
decimals: 6,
logoURL: string
logoURL: 'https://static.thorswap.net/token-list/images/eth.usdc.png',
name: string
name: 'USD Coin'
}
]
getLogoForAsset
Section titled “getLogoForAsset”Get logo URL for any asset:
// Get asset logo
const const logoUrl: any
logoUrl = Cannot find name 'SwapKitApi'.SwapKitApi.getLogoForAsset('ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');
// Returns: 'https://static.thorswap.net/token-list/images/eth.usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48.png'
// Native assets
const const ethLogo: any
ethLogo = Cannot find name 'SwapKitApi'.SwapKitApi.getLogoForAsset('ETH.ETH');
// Returns: 'https://static.thorswap.net/token-list/images/eth.eth.png'
getChainLogoForAsset
Section titled “getChainLogoForAsset”Get chain logo for any asset:
// Get chain logo
const const chainLogo: any
chainLogo = Cannot find name 'SwapKitApi'.SwapKitApi.getChainLogoForAsset('ETH.USDC-0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48');
// Returns: 'https://static.thorswap.net/token-list/images/eth.png'
getProviderLogo
Section titled “getProviderLogo”Get logo URL for token list providers:
const const providerLogo: any
providerLogo = await Cannot find name 'SwapKitApi'.SwapKitApi.getProviderLogo('1inch');
// Returns: 'https://...'
Provider-Specific APIs
Section titled “Provider-Specific APIs”Microgard API
Section titled “Microgard API”Access THORChain microgard services:
// Get THORName details
const const thorname: any
thorname = await Cannot find name 'SwapKitApi'.SwapKitApi.microgard.getTHORNameDetails('myname');
// Get THORNames by owner
const Cannot redeclare block-scoped variable 'names'.namesCannot find name 'SwapKitApi'. = await SwapKitApi.microgard.getTHORNamesByOwner('thor1...');
// Get THORNames by address
const Cannot redeclare block-scoped variable 'names'.namesCannot find name 'SwapKitApi'. = await SwapKitApi.microgard.getTHORNamesByAddress('0x...');
// Get THORChain pools
const const pools: any
pools = await Cannot find name 'SwapKitApi'.SwapKitApi.microgard.getTHORChainPools('7d'); // '1h', '24h', '7d', '30d', '365d'
// Get liquidity positions
const const positions: any
positions = await Cannot find name 'SwapKitApi'.SwapKitApi.microgard.getLiquidityPositions(['thor1...', 'thor2...']);
// Get TNS chain address
const const address: any
address = await Cannot find name 'SwapKitApi'.SwapKitApi.microgard.getTNSChainAddress({
chain: string
chain: 'ETH',
tns: string
tns: 'myname'
});
THORNode API
Section titled “THORNode API”Direct access to THORChain node data:
// Get last block
const const lastBlock: any
lastBlock = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getLastBlock('thorchain'); // or 'mayachain'
// Get THORChain queue
const const queue: any
queue = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getThorchainQueue();
// Get node list
const const nodes: any
nodes = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getNodes();
// Get Mimir settings
const const mimir: any
mimir = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getMimirInfo();
// Get inbound addresses
const const inboundAddresses: any
inboundAddresses = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getInboundAddresses();
// Get THORNode TNS details
const const tnsDetails: any
tnsDetails = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getTHORNodeTNSDetails({
name: string
name: 'myname',
type: string
type: 'thorchain' // or 'mayachain'
});
// Get TNS preferred asset
const const preferredAsset: any
preferredAsset = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getTNSPreferredAsset({
tns: string
tns: 'myname',
type: string
type: 'thorchain'
});
// Get RUNEPool info
const const runePool: any
runePool = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getRunePoolInfo();
// Get RUNEPool provider info
const const providerInfo: any
providerInfo = await Cannot find name 'SwapKitApi'.SwapKitApi.thornode.getRunePoolProviderInfo({
thorAddress: string
thorAddress: 'thor1...'
});
Midgard APIs
Section titled “Midgard APIs”Access THORChain and Maya midgard data:
// THORChain Midgard
// Get liquidity position
const const thorLiquidity: any
thorLiquidity = await Cannot find name 'SwapKitApi'.SwapKitApi.thorchainMidgard.getLiquidityPosition('thor1...');
// Get THORName details
const const thorName: any
thorName = await Cannot find name 'SwapKitApi'.SwapKitApi.thorchainMidgard.getNameDetails('myname');
// Get THORNames by address
const const namesByAddress: any
namesByAddress = await Cannot find name 'SwapKitApi'.SwapKitApi.thorchainMidgard.getNamesByAddress('0x...');
// Get THORNames by owner
const const namesByOwner: any
namesByOwner = await Cannot find name 'SwapKitApi'.SwapKitApi.thorchainMidgard.getNamesByOwner('thor1...');
// Maya Midgard - same methods available
const const mayaLiquidity: any
mayaLiquidity = await Cannot find name 'SwapKitApi'.SwapKitApi.mayachainMidgard.getLiquidityPosition('maya1...');
const const mayaName: any
mayaName = await Cannot find name 'SwapKitApi'.SwapKitApi.mayachainMidgard.getNameDetails('myname');
Chainflip
Section titled “Chainflip”Create deposit channels for Chainflip swaps:
const const channel: any
channel = await Cannot find name 'SwapKitApi'.SwapKitApi.getChainflipDepositChannel({
sellAsset: {
chain: string;
asset: string;
}
sellAsset: {
chain: string
chain: 'ETH',
asset: string
asset: 'ETH'
},
buyAsset: {
chain: string;
asset: string;
}
buyAsset: {
chain: string
chain: 'BTC',
asset: string
asset: 'BTC'
},
destinationAddress: string
destinationAddress: 'bc1q...',
brokerCommissionBps: number
brokerCommissionBps: 100, // Optional: 1% commission
affiliateFees: {
brokerAddress: string;
feeBps: number;
}[]
affiliateFees: [ // Optional: affiliate fees
{
brokerAddress: string
brokerAddress: '0x...',
feeBps: number
feeBps: 50
}
],
channelMetadata: {
cfParameters: string;
gasBudget: string;
message: string;
}
channelMetadata: { // Optional: additional parameters
cfParameters: string
cfParameters: '...',
gasBudget: string
gasBudget: '1000000',
message: string
message: 'Swap via SwapKit'
},
refundParameters: {
minPrice: string;
refundAddress: string;
retryDuration: number;
}
refundParameters: { // Optional: refund settings
minPrice: string
minPrice: '0.01',
refundAddress: string
refundAddress: '0x...',
retryDuration: number
retryDuration: 3600
},
dcaParameters: {
numberOfChunks: number;
chunkInterval: number;
}
dcaParameters: { // Optional: DCA settings
numberOfChunks: number
numberOfChunks: 10,
chunkInterval: number
chunkInterval: 600
},
maxBoostFeeBps: number
maxBoostFeeBps: 200 // Optional: max boost fee
});
// Response
{
depositChannelId: Left side of comma operator is unused and has no side effects.'123456',
Cannot find name 'depositAddress'.depositAddressLeft side of comma operator is unused and has no side effects.';' expected.: '0x...', // Send funds here
Cannot find name 'brokerCommissionBps'.brokerCommissionBpsLeft side of comma operator is unused and has no side effects.';' expected.: 100,
Cannot find name 'estimatedExpiryTime'.estimatedExpiryTimeLeft side of comma operator is unused and has no side effects.';' expected.: 1234567890,
Cannot find name 'expiryBlock'.expiryBlockLeft side of comma operator is unused and has no side effects.';' expected.: 123456,
Cannot find name 'issuedBlock'.issuedBlockLeft side of comma operator is unused and has no side effects.';' expected.: 123400,
Cannot find name 'sourceChainExpiryBlock'.sourceChainExpiryBlock';' expected.: 234567
}
Rate Limits
Section titled “Rate Limits”The SwapKit API has rate limits that vary by endpoint:
- Without API key: 10 requests per minute
- With API key: 100 requests per minute
Configure your API key in Configuration:
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({
config?: SKConfigState | undefined
config: {
apiKeys?: Partial<{
blockchair: string;
keepKey: string;
swapKit: string;
walletConnectProjectId: string;
}> | undefined
apiKeys: {
swapKit?: string | undefined
swapKit: 'your-api-key'
}
}
});
Error Handling
Section titled “Error Handling”All API methods can throw errors that should be handled:
import { class SwapKitError
SwapKitError } from '@swapkit/sdk';
try {
const const quote: any
quote = await Cannot find name 'SwapKitApi'.SwapKitApiExpression expected..getSwapQuote({...});
} catch (var error: unknown
error) {
if (var error: unknown
error instanceof class SwapKitError
SwapKitError) {
// Handle SwapKit-specific errors
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('API Error:', var error: SwapKitError
error.Error.message: string
message);
// Check for rate limiting
if (var error: SwapKitError
error.Property 'code' does not exist on type 'SwapKitError'.code === 'api_rate_limit') {
// Wait and retry
}
}
}
Common Patterns
Section titled “Common Patterns”Best Route Selection
Section titled “Best Route Selection”When getting swap quotes, the first route is typically the best:
import { class AssetValue
AssetValue } from '@swapkit/sdk';
const { const routes: any
routes } = await Cannot find name 'SwapKitApi'.SwapKitApiExpression expected..getSwapQuote({...});
if (const routes: any
routes.length > 0) {
const const bestRoute: any
bestRoute = const routes: any
routes[0];
// Check if route meets your requirements
const const minOutput: AssetValue
minOutput = class AssetValue
AssetValue.AssetValue.from<{
asset: any;
value: any;
fromBaseDecimal: boolean;
}>({ value, fromBaseDecimal, asyncTokenLookup, ...fromAssetOrChain }: never): AssetValue
from({
Type 'any' is not assignable to type 'never'.asset: const bestRoute: any
bestRoute.buyAsset,
Type 'any' is not assignable to type 'never'.value: const bestRoute: any
bestRoute.expectedBuyAmountMaxSlippage,
Type 'true' is not assignable to type 'never'.fromBaseDecimal: true
});
if (const minOutput: AssetValue
minOutput.BigIntArithmetics.gte(value: InitialisationValueType): boolean
gte(Cannot find name 'requiredAmount'.requiredAmount)) {
await Cannot find name 'swapKit'.swapKit.swap({ route: any
route: const bestRoute: any
bestRoute });
}
}
Price Impact Calculation
Section titled “Price Impact Calculation”Calculate price impact for large swaps:
const const quote: any
quote = await Cannot find name 'SwapKitApi'.SwapKitApiExpression expected..getSwapQuote({...});
const const route: any
route = const quote: any
quote.routes[0];
// Get current prices
const const sellPrice: any
sellPrice = await Cannot find name 'SwapKitApi'.SwapKitApi.getPrice(const route: any
route.sellAsset);
const const buyPrice: any
buyPrice = await Cannot find name 'SwapKitApi'.SwapKitApi.getPrice(const route: any
route.buyAsset);
// Calculate expected value
const const sellValue: number
sellValue = 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 route: any
route.sellAmount) * const sellPrice: any
sellPrice;
const const buyValue: number
buyValue = 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 route: any
route.expectedBuyAmount) * const buyPrice: any
buyPrice;
// Calculate price impact
const const priceImpact: number
priceImpact = ((const sellValue: number
sellValue - const buyValue: number
buyValue) / const sellValue: number
sellValue) * 100;
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.log(`Price impact: ${const priceImpact: number
priceImpact.Number.toFixed(fractionDigits?: number): string
Returns a string representing a number in fixed-point notation.toFixed(2)}%`);
Token Validation
Section titled “Token Validation”Validate tokens before swapping:
async function function validateToken(identifier: string): Promise<{
valid: boolean;
decimals: any;
name: any;
logo: any;
} | {
valid: boolean;
decimals?: undefined;
name?: undefined;
logo?: undefined;
}>
validateToken(identifier: string
identifier: string) {
try {
const const token: any
token = await Cannot find name 'SwapKitApi'.SwapKitApi.getTokenList(identifier: string
identifier);
return {
valid: boolean
valid: true,
decimals: any
decimals: const token: any
token.decimals,
name: any
name: const token: any
token.name,
logo: any
logo: const token: any
token.logoURL
};
} catch {
return { valid: boolean
valid: false };
}
}
Configuration Management
Section titled “Configuration Management”SKConfig API
Section titled “SKConfig API”The SKConfig
API provides methods to manage SwapKit’s configuration at runtime. This includes RPC URLs, API keys, custom headers, and environment settings:
Core Methods
Section titled “Core Methods”import { const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig } from '@swapkit/sdk';
// Get configuration values
const const rpcUrls: Record<Chain | StagenetChain, string>
rpcUrls = const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.get: <"rpcUrls">(key: "rpcUrls") => Record<Chain | StagenetChain, string>
get('rpcUrls');
const const apiKeys: {
blockchair: string;
keepKey: string;
swapKit: string;
walletConnectProjectId: string;
}
apiKeys = const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.get: <"apiKeys">(key: "apiKeys") => {
blockchair: string;
keepKey: string;
swapKit: string;
walletConnectProjectId: string;
}
get('apiKeys');
const const midgardUrls: {
ARB: any;
AVAX: any;
BASE: any;
BSC: any;
BTC: any;
BCH: any;
GAIA: any;
DASH: any;
DOGE: any;
ETH: any;
FIAT: any;
KUJI: any;
LTC: any;
MAYA: any;
NEAR: any;
OP: any;
DOT: any;
FLIP: any;
MATIC: any;
XRD: any;
XRP: any;
THOR: any;
SOL: any;
TRX: any;
} | ... 7 more ... | {
...;
}
midgardUrls = const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.get: <"apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations") => {
...;
} | ... 7 more ... | {
...;
}
get(Argument of type '"midgardUrls"' is not assignable to parameter of type '"apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations"'.'midgardUrls');
const const apiHeaders: {
ARB: any;
AVAX: any;
BASE: any;
BSC: any;
BTC: any;
BCH: any;
GAIA: any;
DASH: any;
DOGE: any;
ETH: any;
FIAT: any;
KUJI: any;
LTC: any;
MAYA: any;
NEAR: any;
OP: any;
DOT: any;
FLIP: any;
MATIC: any;
XRD: any;
XRP: any;
THOR: any;
SOL: any;
TRX: any;
} | ... 7 more ... | {
...;
}
apiHeaders = const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.get: <"apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations") => {
...;
} | ... 7 more ... | {
...;
}
get(Argument of type '"apiHeaders"' is not assignable to parameter of type '"apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations"'.'apiHeaders');
// Set complete configuration
const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.set: <{
rpcUrls: {
ETH: string;
};
apiKeys: {
swapKit: string;
};
midgardUrls: {
THOR: string;
};
apiHeaders: {
midgard: {
'X-API-Key': string;
};
};
}>(config: {
rpcUrls: {
ETH: string;
};
apiKeys: {
swapKit: string;
};
midgardUrls: {
THOR: string;
};
apiHeaders: {
midgard: {
'X-API-Key': string;
};
};
}) => void
set({
rpcUrls: {
ETH: string;
}
rpcUrls: { type ETH: string
ETH: 'https://new-rpc.com' },
apiKeys: {
swapKit: string;
}
apiKeys: { swapKit: string
swapKit: 'new-key' },
midgardUrls: {
THOR: string;
}
midgardUrls: { type THOR: string
THOR: 'https://custom-midgard.com' },
apiHeaders: {
midgard: {
'X-API-Key': string;
};
}
apiHeaders: { midgard: {
'X-API-Key': string;
}
midgard: { 'X-API-Key': 'secret' } }
});
API Keys
Section titled “API Keys”// Set individual API keys
Cannot find name 'SKConfig'.SKConfig.setApiKey('swapKit', 'your-swapkit-key');
Cannot find name 'SKConfig'.SKConfig.setApiKey('blockchair', 'your-blockchair-key');
Cannot find name 'SKConfig'.SKConfig.setApiKey('walletConnectProjectId', 'your-wc-id');
RPC URLs
Section titled “RPC URLs”import { enum Chain
Chain } from '@swapkit/sdk';
// Set RPC URL for specific chain
Cannot find name 'SKConfig'.SKConfig.setRpcUrl(enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum, 'https://eth-mainnet.g.alchemy.com/v2/key');
Cannot find name 'SKConfig'.SKConfig.setRpcUrl(enum Chain
Chain.function (enum member) Chain.Avalanche = "AVAX"
Avalanche, 'https://api.avax.network/ext/bc/C/rpc');
Midgard URLs
Section titled “Midgard URLs”import { enum Chain
Chain } from '@swapkit/sdk';
// Set custom Midgard URLs
Cannot find name 'SKConfig'.SKConfig.setMidgardUrl(enum Chain
Chain.function (enum member) Chain.THORChain = "THOR"
THORChain, 'https://custom-midgard.com');
Cannot find name 'SKConfig'.SKConfig.setMidgardUrl(enum Chain
Chain.function (enum member) Chain.Maya = "MAYA"
Maya, 'https://maya-midgard.com');
// Note: When isStagenet is true, SwapKit automatically uses stagenet URLs:
// - THORChain: https://stagenet-midgard.ninerealms.com
// - Maya: https://stagenet-midgard.mayachain.info
API Headers
Section titled “API Headers”// Set headers for specific APIs
Cannot find name 'SKConfig'.SKConfig.setApiHeaders('midgard', {
'X-Client-ID': 'your-client-id'
});
// Headers for THORNode API
Cannot find name 'SKConfig'.SKConfig.setApiHeaders('thornode', {
'X-Client-ID': 'your-client-id'
});
// Headers for SwapKit API (in addition to automatic x-api-key)
Cannot find name 'SKConfig'.SKConfig.setApiHeaders('swapkitApi', {
'X-API-Key': 'additional-api-key'
});
Environment Settings
Section titled “Environment Settings”// Set environment flags
Cannot find name 'SKConfig'.SKConfig.setEnv('isDev', true);
Cannot find name 'SKConfig'.SKConfig.setEnv('isStagenet', true);
// API URLs
Cannot find name 'SKConfig'.SKConfig.setEnv('apiUrl', 'https://api.swapkit.dev');
Cannot find name 'SKConfig'.SKConfig.setEnv('devApiUrl', 'https://dev-api.swapkit.dev');
Integration Configurations
Section titled “Integration Configurations”// Radix configuration
Cannot find name 'SKConfig'.SKConfig.setIntegrationConfig('radix', {
dAppDefinitionAddress: string
dAppDefinitionAddress: 'account_rdx...',
applicationName: string
applicationName: 'My dApp',
applicationVersion: string
applicationVersion: '1.0.0',
network: {
networkId: number;
networkName: string;
dashboardBase: string;
}
network: {
networkId: number
networkId: 1,
networkName: string
networkName: 'mainnet',
dashboardBase: string
dashboardBase: 'https://dashboard.radixdlt.com'
}
});
// Chainflip configuration
Cannot find name 'SKConfig'.SKConfig.setIntegrationConfig('chainflip', {
useSDKBroker: boolean
useSDKBroker: true,
brokerUrl: string
brokerUrl: 'https://broker.chainflip.io'
});
Explorer URLs
Section titled “Explorer URLs”// Set custom explorer URLs
Cannot find name 'SKConfig'.SKConfigCannot find name 'Chain'. Did you mean 'Chai'?.setExplorerUrl(Chain.Ethereum, 'https://etherscan.io');
Cannot find name 'SKConfig'.SKConfigCannot find name 'Chain'. Did you mean 'Chai'?.setExplorerUrl(Chain.Bitcoin, 'https://blockstream.info');
Complete Example
Section titled “Complete Example”import { const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig, enum Chain
Chain, enum StagenetChain
StagenetChain } from '@swapkit/sdk';
// Configure multiple settings at once
const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.set: <{
apiKeys: {
swapKit: string | undefined;
blockchair: string | undefined;
};
rpcUrls: {
ETH: string;
MATIC: string;
};
midgardUrls: {
THOR: string;
THOR_STAGENET: string;
};
apiHeaders: {
midgard: {
...;
};
thornode: {
...;
};
};
envs: {
...;
};
}>(config: {
apiKeys: {
swapKit: string | undefined;
blockchair: string | undefined;
};
rpcUrls: {
ETH: string;
MATIC: string;
};
midgardUrls: {
THOR: string;
THOR_STAGENET: string;
};
apiHeaders: {
midgard: {
...;
};
thornode: {
...;
};
};
envs: {
...;
};
}) => void
set({
apiKeys: {
swapKit: string | undefined;
blockchair: string | undefined;
}
apiKeys: {
swapKit: string | undefined
swapKit: 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,
blockchair: string | undefined
blockchair: 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
BLOCKCHAIR_API_KEY
},
rpcUrls: {
ETH: string;
MATIC: string;
}
rpcUrls: {
[enum Chain
Chain.function (enum member) Chain.Ethereum = "ETH"
Ethereum]: 'https://eth-mainnet.g.alchemy.com/v2/key',
[enum Chain
Chain.function (enum member) Chain.Polygon = "MATIC"
Polygon]: 'https://polygon-rpc.com'
},
midgardUrls: {
THOR: string;
THOR_STAGENET: string;
}
midgardUrls: {
[enum Chain
Chain.function (enum member) Chain.THORChain = "THOR"
THORChain]: 'https://private-midgard.com',
[enum StagenetChain
StagenetChain.function (enum member) StagenetChain.THORChain = "THOR_STAGENET"
THORChain]: 'https://stagenet-midgard.com'
},
apiHeaders: {
midgard: {
'X-Client-ID': string | undefined;
};
thornode: {
'X-Client-ID': string | undefined;
};
}
apiHeaders: {
midgard: {
'X-Client-ID': string | undefined;
}
midgard: {
'X-Client-ID': 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
CLIENT_ID
},
thornode: {
'X-Client-ID': string | undefined;
}
thornode: {
'X-Client-ID': 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
CLIENT_ID
}
},
envs: {
isDev: boolean;
isStagenet: false;
}
envs: {
isDev: boolean
isDev: 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 === 'development',
isStagenet: false
isStagenet: false
}
});
// Later, update individual settings
if (Cannot find name 'userPrefersTestnet'.userPrefersTestnet) {
const SKConfig: {
getState: () => SwapKitConfigStore;
get: <T extends "apiKeys" | "apis" | "chains" | "wallets" | "explorerUrls" | "nodeUrls" | "rpcUrls" | "envs" | "integrations">(key: T) => SwapKitConfigStore[T];
... 6 more ...;
setIntegrationConfig: <T extends keyof SKConfigIntegrations>(integration: T, config: SKConfigIntegrations[T]) => void;
}
SKConfig.setEnv: <"isStagenet">(key: "isStagenet", value: boolean) => void
setEnv('isStagenet', true);
// Midgard URLs automatically switch to stagenet when isStagenet is true
}
Key Features
Section titled “Key Features”- Automatic Stagenet Support: When
isStagenet
is true, appropriate stagenet URLs are used automatically - Custom Headers: Set authentication headers for Midgard, THORNode, and SwapKit APIs
- Runtime Updates: All configuration can be updated dynamically without recreating SwapKit instances
- Environment-Based Config: Easily switch between development, staging, and production environments
Next Steps
Section titled “Next Steps”- Implement Cross-Chain Swaps using the quote API
- Set up Transaction Tracking for better UX
- Explore THORChain Features for advanced DeFi