@swapkit/helpers
Advanced tools
Comparing version 0.0.0-nightly-20240208140027 to 0.0.0-nightly-20240223171610
@@ -1,149 +0,114 @@ | ||
import type { | ||
ChainflipList, | ||
CoinGeckoList, | ||
MayaList, | ||
PancakeswapETHList, | ||
PancakeswapList, | ||
PangolinList, | ||
StargateARBList, | ||
SushiswapList, | ||
ThorchainList, | ||
TraderjoeList, | ||
UniswapList, | ||
WoofiList, | ||
} from '@swapkit/tokens'; | ||
import type { Chain, ChainId, FeeOption, MemoType } from '@swapkit/types'; | ||
import { BaseDecimal } from '@swapkit/types'; | ||
import { Chain } from '@swapkit/types'; | ||
import type { ChainflipList } from '@swapkit/tokens'; | ||
import { ChainId } from '@swapkit/types'; | ||
import type { CoinGeckoList } from '@swapkit/tokens'; | ||
import { FeeOption } from '@swapkit/types'; | ||
import type { MayaList } from '@swapkit/tokens'; | ||
import { MemoType } from '@swapkit/types'; | ||
import type { PancakeswapETHList } from '@swapkit/tokens'; | ||
import type { PancakeswapList } from '@swapkit/tokens'; | ||
import type { PangolinList } from '@swapkit/tokens'; | ||
import type { StargateARBList } from '@swapkit/tokens'; | ||
import type { SushiswapList } from '@swapkit/tokens'; | ||
import type { ThorchainList } from '@swapkit/tokens'; | ||
import type { TraderjoeList } from '@swapkit/tokens'; | ||
import type { UniswapList } from '@swapkit/tokens'; | ||
import type { WoofiList } from '@swapkit/tokens'; | ||
declare type AllowedNumberTypes = 'bigint' | 'number' | 'string'; | ||
declare type AllowedNumberTypes = "bigint" | "number" | "string"; | ||
export declare const assetFromString: (assetString: string) => { | ||
chain: Chain; | ||
symbol: string; | ||
ticker: string; | ||
synth: boolean; | ||
chain: Chain; | ||
symbol: string; | ||
ticker: string; | ||
synth: boolean; | ||
}; | ||
export declare class AssetValue extends BigIntArithmetics { | ||
address?: string; | ||
chain: Chain; | ||
isGasAsset: boolean; | ||
isSynthetic: boolean; | ||
symbol: string; | ||
tax?: TokenTax; | ||
ticker: string; | ||
type: ReturnType<typeof getAssetType>; | ||
constructor({ | ||
value, | ||
decimal, | ||
tax, | ||
chain, | ||
symbol, | ||
identifier, | ||
}: { | ||
decimal: number; | ||
value: SwapKitValueType; | ||
address?: string; | ||
chain: Chain; | ||
isGasAsset: boolean; | ||
isSynthetic: boolean; | ||
symbol: string; | ||
tax?: TokenTax; | ||
} & ( | ||
| { | ||
ticker: string; | ||
type: ReturnType<typeof getAssetType>; | ||
constructor({ value, decimal, tax, chain, symbol, identifier, }: { | ||
decimal: number; | ||
value: SwapKitValueType; | ||
tax?: TokenTax; | ||
} & ({ | ||
chain: Chain; | ||
symbol: string; | ||
identifier?: never; | ||
} | ||
| { | ||
} | { | ||
identifier: string; | ||
chain?: never; | ||
symbol?: never; | ||
} | ||
)); | ||
toString(): string; | ||
toUrl(): string; | ||
eq({ chain, symbol }: { chain: Chain; symbol: string }): boolean; | ||
chainId(): ChainId; | ||
static fromUrl(urlAsset: string, value?: NumberPrimitives): Promise<AssetValue>; | ||
static fromString(assetString: string, value?: NumberPrimitives): Promise<AssetValue>; | ||
static fromIdentifier( | ||
assetString: | ||
| `${Chain}.${string}` | ||
| `${Chain}/${string}` | ||
| `${Chain}.${string}-${string}` | ||
| TokenNames, | ||
value?: NumberPrimitives, | ||
): Promise<AssetValue>; | ||
static fromStringSync(assetString: string, value?: NumberPrimitives): AssetValue; | ||
static fromIdentifierSync(assetString: TokenNames, value?: NumberPrimitives): AssetValue; | ||
static fromChainOrSignature(assetString: CommonAssetString, value?: NumberPrimitives): AssetValue; | ||
static loadStaticAssets(): Promise< | ||
| { | ||
})); | ||
toString(): string; | ||
toUrl(): string; | ||
eq({ chain, symbol }: { | ||
chain: Chain; | ||
symbol: string; | ||
}): boolean; | ||
chainId(): ChainId; | ||
static fromUrl(urlAsset: string, value?: NumberPrimitives): Promise<AssetValue>; | ||
static fromString(assetString: string, value?: NumberPrimitives): Promise<AssetValue>; | ||
static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}` | TokenNames, value?: NumberPrimitives): Promise<AssetValue>; | ||
static fromStringSync(assetString: string, value?: NumberPrimitives): AssetValue; | ||
static fromStringWithBase(assetString: string, value?: NumberPrimitives, baseDecimal?: number): Promise<AssetValue>; | ||
static fromStringWithBaseSync(assetString: string, value?: NumberPrimitives, baseDecimal?: number): AssetValue; | ||
static fromIdentifierSync(assetString: TokenNames, value?: NumberPrimitives): AssetValue; | ||
static fromChainOrSignature(assetString: CommonAssetString, value?: NumberPrimitives): AssetValue; | ||
static loadStaticAssets(): Promise<{ | ||
ok: true; | ||
} | ||
| { | ||
} | { | ||
ok: false; | ||
message: string; | ||
error: any; | ||
} | ||
>; | ||
}>; | ||
} | ||
export declare class BigIntArithmetics { | ||
decimalMultiplier: bigint; | ||
bigIntValue: bigint; | ||
decimal?: number; | ||
static fromBigInt(value: bigint, decimal?: number): BigIntArithmetics; | ||
static shiftDecimals({ | ||
value, | ||
from, | ||
to, | ||
}: { | ||
value: InstanceType<typeof SwapKitNumber>; | ||
from: number; | ||
to: number; | ||
}): BigIntArithmetics; | ||
constructor(params: SKBigIntParams); | ||
set(value: SKBigIntParams): this; | ||
add(...args: InitialisationValueType[]): this; | ||
sub(...args: InitialisationValueType[]): this; | ||
mul(...args: InitialisationValueType[]): this; | ||
div(...args: InitialisationValueType[]): this; | ||
gt(value: InitialisationValueType): boolean; | ||
gte(value: InitialisationValueType): boolean; | ||
lt(value: InitialisationValueType): boolean; | ||
lte(value: InitialisationValueType): boolean; | ||
eqValue(value: InitialisationValueType): boolean; | ||
getValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T]; | ||
getBaseValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T]; | ||
getBigIntValue(value: InitialisationValueType, decimal?: number): bigint; | ||
toSignificant(significantDigits?: number): string; | ||
toFixed(fixedDigits?: number): string; | ||
toAbbreviation(digits?: number): string; | ||
toCurrency( | ||
currency?: string, | ||
{ | ||
currencyPosition, | ||
decimal, | ||
decimalSeparator, | ||
thousandSeparator, | ||
}?: { | ||
currencyPosition?: string | undefined; | ||
decimal?: number | undefined; | ||
decimalSeparator?: string | undefined; | ||
thousandSeparator?: string | undefined; | ||
}, | ||
): string; | ||
formatBigIntToSafeValue(value: bigint, decimal?: number): string; | ||
decimalMultiplier: bigint; | ||
bigIntValue: bigint; | ||
decimal?: number; | ||
static fromBigInt(value: bigint, decimal?: number): BigIntArithmetics; | ||
static shiftDecimals({ value, from, to, }: { | ||
value: InstanceType<typeof SwapKitNumber>; | ||
from: number; | ||
to: number; | ||
}): BigIntArithmetics; | ||
constructor(params: SKBigIntParams); | ||
set(value: SKBigIntParams): this; | ||
add(...args: InitialisationValueType[]): this; | ||
sub(...args: InitialisationValueType[]): this; | ||
mul(...args: InitialisationValueType[]): this; | ||
div(...args: InitialisationValueType[]): this; | ||
gt(value: InitialisationValueType): boolean; | ||
gte(value: InitialisationValueType): boolean; | ||
lt(value: InitialisationValueType): boolean; | ||
lte(value: InitialisationValueType): boolean; | ||
eqValue(value: InitialisationValueType): boolean; | ||
getValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T]; | ||
getBaseValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T]; | ||
getBigIntValue(value: InitialisationValueType, decimal?: number): bigint; | ||
toSignificant(significantDigits?: number): string; | ||
toFixed(fixedDigits?: number): string; | ||
toAbbreviation(digits?: number): string; | ||
toCurrency(currency?: string, { currencyPosition, decimal, decimalSeparator, thousandSeparator, }?: { | ||
currencyPosition?: string | undefined; | ||
decimal?: number | undefined; | ||
decimalSeparator?: string | undefined; | ||
thousandSeparator?: string | undefined; | ||
}): string; | ||
formatBigIntToSafeValue(value: bigint, decimal?: number): string; | ||
} | ||
export declare type CommonAssetString = | ||
| `${Chain.Maya}.MAYA` | ||
| `${Chain.Ethereum}.THOR` | ||
| `${Chain.Ethereum}.vTHOR` | ||
| `${Chain.Kujira}.USK` | ||
| Chain; | ||
export declare type CommonAssetString = `${Chain.Maya}.MAYA` | `${Chain.Ethereum}.THOR` | `${Chain.Ethereum}.vTHOR` | `${Chain.Kujira}.USK` | Chain; | ||
export declare function derivationPathToString([ | ||
network, | ||
chainId, | ||
account, | ||
change, | ||
index, | ||
]: number[]): string; | ||
export declare function derivationPathToString([network, chainId, account, change, index]: number[]): string; | ||
@@ -153,68 +118,75 @@ export declare type ErrorKeys = keyof typeof errorMessages; | ||
declare const errorMessages: { | ||
/** | ||
* Core | ||
*/ | ||
readonly core_wallet_connection_not_found: 10001; | ||
readonly core_estimated_max_spendable_chain_not_supported: 10002; | ||
readonly core_extend_error: 10003; | ||
readonly core_inbound_data_not_found: 10004; | ||
readonly core_approve_asset_address_or_from_not_found: 10005; | ||
readonly core_chain_halted: 10099; | ||
/** | ||
* Core - Wallet Connection | ||
*/ | ||
readonly core_wallet_xdefi_not_installed: 10101; | ||
readonly core_wallet_evmwallet_not_installed: 10102; | ||
readonly core_wallet_walletconnect_not_installed: 10103; | ||
readonly core_wallet_keystore_not_installed: 10104; | ||
readonly core_wallet_ledger_not_installed: 10105; | ||
readonly core_wallet_trezor_not_installed: 10106; | ||
readonly core_wallet_keplr_not_installed: 10107; | ||
readonly core_wallet_okx_not_installed: 10108; | ||
readonly core_wallet_keepkey_not_installed: 10109; | ||
/** | ||
* Core - Swap | ||
*/ | ||
readonly core_swap_invalid_params: 10200; | ||
readonly core_swap_route_not_complete: 10201; | ||
readonly core_swap_asset_not_recognized: 10202; | ||
readonly core_swap_contract_not_found: 10203; | ||
readonly core_swap_route_transaction_not_found: 10204; | ||
readonly core_swap_contract_not_supported: 10205; | ||
readonly core_swap_transaction_error: 10206; | ||
readonly core_swap_quote_mode_not_supported: 10207; | ||
/** | ||
* Core - Transaction | ||
*/ | ||
readonly core_transaction_deposit_error: 10301; | ||
readonly core_transaction_create_liquidity_rune_error: 10302; | ||
readonly core_transaction_create_liquidity_asset_error: 10303; | ||
readonly core_transaction_create_liquidity_invalid_params: 10304; | ||
readonly core_transaction_add_liquidity_invalid_params: 10305; | ||
readonly core_transaction_add_liquidity_no_rune_address: 10306; | ||
readonly core_transaction_add_liquidity_rune_error: 10307; | ||
readonly core_transaction_add_liquidity_asset_error: 10308; | ||
readonly core_transaction_withdraw_error: 10309; | ||
readonly core_transaction_deposit_to_pool_error: 10310; | ||
readonly core_transaction_deposit_insufficient_funds_error: 10311; | ||
readonly core_transaction_deposit_gas_error: 10312; | ||
readonly core_transaction_invalid_sender_address: 10313; | ||
readonly core_transaction_deposit_server_error: 10314; | ||
readonly core_transaction_user_rejected: 10315; | ||
/** | ||
* Wallets | ||
*/ | ||
readonly wallet_ledger_connection_error: 20001; | ||
readonly wallet_ledger_connection_claimed: 20002; | ||
readonly wallet_ledger_get_address_error: 20003; | ||
readonly wallet_ledger_device_not_found: 20004; | ||
readonly wallet_ledger_device_locked: 20005; | ||
/** | ||
* Helpers | ||
*/ | ||
readonly helpers_number_different_decimals: 99101; | ||
/** | ||
* Core | ||
*/ | ||
readonly core_wallet_connection_not_found: 10001; | ||
readonly core_estimated_max_spendable_chain_not_supported: 10002; | ||
readonly core_extend_error: 10003; | ||
readonly core_inbound_data_not_found: 10004; | ||
readonly core_approve_asset_address_or_from_not_found: 10005; | ||
readonly core_chain_halted: 10099; | ||
/** | ||
* Core - Wallet Connection | ||
*/ | ||
readonly core_wallet_xdefi_not_installed: 10101; | ||
readonly core_wallet_evmwallet_not_installed: 10102; | ||
readonly core_wallet_walletconnect_not_installed: 10103; | ||
readonly core_wallet_keystore_not_installed: 10104; | ||
readonly core_wallet_ledger_not_installed: 10105; | ||
readonly core_wallet_trezor_not_installed: 10106; | ||
readonly core_wallet_keplr_not_installed: 10107; | ||
readonly core_wallet_okx_not_installed: 10108; | ||
readonly core_wallet_keepkey_not_installed: 10109; | ||
/** | ||
* Core - Swap | ||
*/ | ||
readonly core_swap_invalid_params: 10200; | ||
readonly core_swap_route_not_complete: 10201; | ||
readonly core_swap_asset_not_recognized: 10202; | ||
readonly core_swap_contract_not_found: 10203; | ||
readonly core_swap_route_transaction_not_found: 10204; | ||
readonly core_swap_contract_not_supported: 10205; | ||
readonly core_swap_transaction_error: 10206; | ||
readonly core_swap_quote_mode_not_supported: 10207; | ||
readonly core_swap_provider_not_found: 10208; | ||
/** | ||
* Core - Transaction | ||
*/ | ||
readonly core_transaction_deposit_error: 10301; | ||
readonly core_transaction_create_liquidity_rune_error: 10302; | ||
readonly core_transaction_create_liquidity_asset_error: 10303; | ||
readonly core_transaction_create_liquidity_invalid_params: 10304; | ||
readonly core_transaction_add_liquidity_invalid_params: 10305; | ||
readonly core_transaction_add_liquidity_no_rune_address: 10306; | ||
readonly core_transaction_add_liquidity_rune_error: 10307; | ||
readonly core_transaction_add_liquidity_asset_error: 10308; | ||
readonly core_transaction_withdraw_error: 10309; | ||
readonly core_transaction_deposit_to_pool_error: 10310; | ||
readonly core_transaction_deposit_insufficient_funds_error: 10311; | ||
readonly core_transaction_deposit_gas_error: 10312; | ||
readonly core_transaction_invalid_sender_address: 10313; | ||
readonly core_transaction_deposit_server_error: 10314; | ||
readonly core_transaction_user_rejected: 10315; | ||
/** | ||
* Wallets | ||
*/ | ||
readonly wallet_ledger_connection_error: 20001; | ||
readonly wallet_ledger_connection_claimed: 20002; | ||
readonly wallet_ledger_get_address_error: 20003; | ||
readonly wallet_ledger_device_not_found: 20004; | ||
readonly wallet_ledger_device_locked: 20005; | ||
/** | ||
* Chainflip | ||
*/ | ||
readonly chainflip_channel_error: 30001; | ||
/** | ||
* THORChain | ||
*/ | ||
/** | ||
* Helpers | ||
*/ | ||
readonly helpers_number_different_decimals: 99101; | ||
}; | ||
export declare const filterAssets: ( | ||
tokens: { | ||
export declare const filterAssets: (tokens: { | ||
value: string; | ||
@@ -224,18 +196,13 @@ decimal: number; | ||
symbol: string; | ||
}[], | ||
) => { | ||
value: string; | ||
decimal: number; | ||
chain: Chain; | ||
symbol: string; | ||
}[]) => { | ||
value: string; | ||
decimal: number; | ||
chain: Chain; | ||
symbol: string; | ||
}[]; | ||
export declare function formatBigIntToSafeValue({ | ||
value, | ||
bigIntDecimal, | ||
decimal, | ||
}: { | ||
value: bigint; | ||
bigIntDecimal?: number; | ||
decimal?: number; | ||
export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: { | ||
value: bigint; | ||
bigIntDecimal?: number; | ||
decimal?: number; | ||
}): string; | ||
@@ -245,37 +212,14 @@ | ||
export declare const getAssetType: ({ | ||
chain, | ||
symbol, | ||
}: { | ||
chain: Chain; | ||
symbol: string; | ||
}) => | ||
| Chain.Avalanche | ||
| Chain.Cosmos | ||
| Chain.Kujira | ||
| 'Synth' | ||
| 'Native' | ||
| 'BEP2' | ||
| 'BEP20' | ||
| 'ERC20' | ||
| 'POLYGON' | ||
| 'ARBITRUM' | ||
| 'OPTIMISM'; | ||
export declare const getAssetType: ({ chain, symbol }: { | ||
chain: Chain; | ||
symbol: string; | ||
}) => Chain.Avalanche | Chain.Cosmos | Chain.Kujira | "Synth" | "Native" | "BEP2" | "BEP20" | "ERC20" | "POLYGON" | "ARBITRUM" | "OPTIMISM"; | ||
export declare function getAsymmetricAssetShare({ | ||
liquidityUnits, | ||
poolUnits, | ||
assetDepth, | ||
}: ShareParams<{ | ||
assetDepth: string; | ||
export declare function getAsymmetricAssetShare({ liquidityUnits, poolUnits, assetDepth, }: ShareParams<{ | ||
assetDepth: string; | ||
}>): SwapKitNumber; | ||
export declare function getAsymmetricAssetWithdrawAmount({ | ||
percent, | ||
assetDepth, | ||
liquidityUnits, | ||
poolUnits, | ||
}: ShareParams<{ | ||
percent: number; | ||
assetDepth: string; | ||
export declare function getAsymmetricAssetWithdrawAmount({ percent, assetDepth, liquidityUnits, poolUnits, }: ShareParams<{ | ||
percent: number; | ||
assetDepth: string; | ||
}>): SwapKitNumber; | ||
@@ -294,86 +238,48 @@ | ||
*/ | ||
export declare function getAsymmetricRuneShare({ | ||
liquidityUnits, | ||
poolUnits, | ||
runeDepth, | ||
}: ShareParams<{ | ||
runeDepth: string; | ||
export declare function getAsymmetricRuneShare({ liquidityUnits, poolUnits, runeDepth, }: ShareParams<{ | ||
runeDepth: string; | ||
}>): SwapKitNumber; | ||
export declare function getAsymmetricRuneWithdrawAmount({ | ||
percent, | ||
runeDepth, | ||
liquidityUnits, | ||
poolUnits, | ||
}: ShareParams<{ | ||
percent: number; | ||
runeDepth: string; | ||
export declare function getAsymmetricRuneWithdrawAmount({ percent, runeDepth, liquidityUnits, poolUnits, }: ShareParams<{ | ||
percent: number; | ||
runeDepth: string; | ||
}>): SwapKitNumber; | ||
export declare const getCommonAssetInfo: (assetString: CommonAssetString) => { | ||
identifier: string; | ||
decimal: number; | ||
identifier: string; | ||
decimal: number; | ||
}; | ||
export declare const getDecimal: ({ | ||
chain, | ||
symbol, | ||
}: { | ||
chain: Chain; | ||
symbol: string; | ||
}) => Promise<number>; | ||
export declare const getDecimal: ({ chain, symbol }: { | ||
chain: Chain; | ||
symbol: string; | ||
}) => BaseDecimal | Promise<number>; | ||
export declare function getEstimatedPoolShare({ | ||
runeDepth, | ||
poolUnits, | ||
assetDepth, | ||
liquidityUnits, | ||
runeAmount, | ||
assetAmount, | ||
}: ShareParams<{ | ||
runeAmount: string; | ||
assetAmount: string; | ||
runeDepth: string; | ||
assetDepth: string; | ||
export declare function getEstimatedPoolShare({ runeDepth, poolUnits, assetDepth, liquidityUnits, runeAmount, assetAmount, }: ShareParams<{ | ||
runeAmount: string; | ||
assetAmount: string; | ||
runeDepth: string; | ||
assetDepth: string; | ||
}>): number; | ||
export declare function getLiquiditySlippage({ | ||
runeAmount, | ||
assetAmount, | ||
runeDepth, | ||
assetDepth, | ||
}: PoolParams): number; | ||
export declare function getLiquiditySlippage({ runeAmount, assetAmount, runeDepth, assetDepth, }: PoolParams): number; | ||
export declare const getMemoFor: <T extends MemoType>( | ||
memoType: T, | ||
options: MemoOptions<T>, | ||
) => string; | ||
export declare const getMemoFor: <T extends MemoType>(memoType: T, options: MemoOptions<T>) => string; | ||
export declare function getMinAmountByChain(chain: Chain): AssetValue; | ||
export declare function getSymmetricPoolShare({ | ||
liquidityUnits, | ||
poolUnits, | ||
runeDepth, | ||
assetDepth, | ||
}: ShareParams<{ | ||
runeDepth: string; | ||
assetDepth: string; | ||
export declare function getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth, }: ShareParams<{ | ||
runeDepth: string; | ||
assetDepth: string; | ||
}>): { | ||
assetAmount: SwapKitNumber; | ||
runeAmount: SwapKitNumber; | ||
assetAmount: SwapKitNumber; | ||
runeAmount: SwapKitNumber; | ||
}; | ||
export declare function getSymmetricWithdraw({ | ||
liquidityUnits, | ||
poolUnits, | ||
runeDepth, | ||
assetDepth, | ||
percent, | ||
}: ShareParams<{ | ||
runeDepth: string; | ||
assetDepth: string; | ||
percent: number; | ||
export declare function getSymmetricWithdraw({ liquidityUnits, poolUnits, runeDepth, assetDepth, percent, }: ShareParams<{ | ||
runeDepth: string; | ||
assetDepth: string; | ||
percent: number; | ||
}>): { | ||
[k: string]: SwapKitNumber; | ||
[k: string]: SwapKitNumber; | ||
}; | ||
@@ -385,31 +291,41 @@ | ||
export declare const isGasAsset: ({ chain, symbol }: { chain: Chain; symbol: string }) => boolean; | ||
export declare const isGasAsset: ({ chain, symbol }: { | ||
chain: Chain; | ||
symbol: string; | ||
}) => boolean; | ||
export declare type MemoOptions<T extends MemoType> = { | ||
[MemoType.BOND]: WithAddress; | ||
[MemoType.LEAVE]: WithAddress; | ||
[MemoType.CLOSE_LOAN]: WithAddress<{ | ||
asset: string; | ||
minAmount?: string; | ||
}>; | ||
[MemoType.OPEN_LOAN]: WithAddress<{ | ||
asset: string; | ||
minAmount?: string; | ||
}>; | ||
[MemoType.UNBOND]: WithAddress<{ | ||
unbondAmount: number; | ||
}>; | ||
[MemoType.DEPOSIT]: WithChain<{ | ||
symbol: string; | ||
address?: string; | ||
singleSide?: boolean; | ||
}>; | ||
[MemoType.WITHDRAW]: WithChain<{ | ||
ticker: string; | ||
symbol: string; | ||
basisPoints: number; | ||
targetAssetString?: string; | ||
singleSide?: boolean; | ||
}>; | ||
[MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, 'preferredAsset' | 'expiryBlock'>; | ||
[MemoType.BOND]: { | ||
address: string; | ||
}; | ||
[MemoType.LEAVE]: { | ||
address: string; | ||
}; | ||
[MemoType.CLOSE_LOAN]: { | ||
address: string; | ||
asset: string; | ||
minAmount?: string; | ||
}; | ||
[MemoType.OPEN_LOAN]: { | ||
address: string; | ||
asset: string; | ||
minAmount?: string; | ||
}; | ||
[MemoType.UNBOND]: { | ||
address: string; | ||
unbondAmount: number; | ||
}; | ||
[MemoType.DEPOSIT]: WithChain<{ | ||
symbol: string; | ||
address?: string; | ||
singleSide?: boolean; | ||
}>; | ||
[MemoType.WITHDRAW]: WithChain<{ | ||
ticker: string; | ||
symbol: string; | ||
basisPoints: number; | ||
targetAssetString?: string; | ||
singleSide?: boolean; | ||
}>; | ||
[MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, "preferredAsset" | "expiryBlock">; | ||
}[T]; | ||
@@ -420,33 +336,31 @@ | ||
declare type NumberPrimitivesType = { | ||
bigint: bigint; | ||
number: number; | ||
string: string; | ||
bigint: bigint; | ||
number: number; | ||
string: string; | ||
}; | ||
declare type PoolParams<T = {}> = T & { | ||
runeAmount: string; | ||
assetAmount: string; | ||
runeDepth: string; | ||
assetDepth: string; | ||
declare type PoolParams = { | ||
runeAmount: string; | ||
assetAmount: string; | ||
runeDepth: string; | ||
assetDepth: string; | ||
}; | ||
declare type ShareParams<T = {}> = T & { | ||
liquidityUnits: string; | ||
poolUnits: string; | ||
declare type ShareParams<T extends {}> = T & { | ||
liquidityUnits: string; | ||
poolUnits: string; | ||
}; | ||
declare type SKBigIntParams = | ||
| InitialisationValueType | ||
| { | ||
decimal?: number; | ||
value: number | string; | ||
}; | ||
declare type SKBigIntParams = InitialisationValueType | { | ||
decimal?: number; | ||
value: number | string; | ||
}; | ||
export declare class SwapKitError extends Error { | ||
constructor(errorKey: ErrorKeys, sourceError?: any); | ||
constructor(errorKey: ErrorKeys, sourceError?: any); | ||
} | ||
export declare class SwapKitNumber extends BigIntArithmetics { | ||
eq(value: SwapKitValueType): boolean; | ||
static fromBigInt(value: bigint, decimal?: number): SwapKitNumber; | ||
eq(value: SwapKitValueType): boolean; | ||
static fromBigInt(value: bigint, decimal?: number): SwapKitNumber; | ||
} | ||
@@ -457,27 +371,15 @@ | ||
export declare type ThornameRegisterParam = { | ||
name: string; | ||
chain: string; | ||
address: string; | ||
owner?: string; | ||
preferredAsset?: string; | ||
expiryBlock?: string; | ||
name: string; | ||
chain: string; | ||
address: string; | ||
owner?: string; | ||
preferredAsset?: string; | ||
expiryBlock?: string; | ||
}; | ||
declare type TokenNames = | ||
| (typeof ThorchainList)['tokens'][number]['identifier'] | ||
| (typeof CoinGeckoList)['tokens'][number]['identifier'] | ||
| (typeof MayaList)['tokens'][number]['identifier'] | ||
| (typeof PancakeswapETHList)['tokens'][number]['identifier'] | ||
| (typeof PancakeswapList)['tokens'][number]['identifier'] | ||
| (typeof PangolinList)['tokens'][number]['identifier'] | ||
| (typeof StargateARBList)['tokens'][number]['identifier'] | ||
| (typeof SushiswapList)['tokens'][number]['identifier'] | ||
| (typeof TraderjoeList)['tokens'][number]['identifier'] | ||
| (typeof WoofiList)['tokens'][number]['identifier'] | ||
| (typeof UniswapList)['tokens'][number]['identifier'] | ||
| (typeof ChainflipList)['tokens'][number]['identifier']; | ||
declare type TokenNames = (typeof ThorchainList)["tokens"][number]["identifier"] | (typeof CoinGeckoList)["tokens"][number]["identifier"] | (typeof MayaList)["tokens"][number]["identifier"] | (typeof PancakeswapETHList)["tokens"][number]["identifier"] | (typeof PancakeswapList)["tokens"][number]["identifier"] | (typeof PangolinList)["tokens"][number]["identifier"] | (typeof StargateARBList)["tokens"][number]["identifier"] | (typeof SushiswapList)["tokens"][number]["identifier"] | (typeof TraderjoeList)["tokens"][number]["identifier"] | (typeof WoofiList)["tokens"][number]["identifier"] | (typeof UniswapList)["tokens"][number]["identifier"] | (typeof ChainflipList)["tokens"][number]["identifier"]; | ||
declare type TokenTax = { | ||
buy: number; | ||
sell: number; | ||
buy: number; | ||
sell: number; | ||
}; | ||
@@ -487,12 +389,9 @@ | ||
declare type WithAddress<T = {}> = T & { | ||
address: string; | ||
declare type WithChain<T extends {}> = T & { | ||
chain: Chain; | ||
}; | ||
declare type WithChain<T = {}> = T & { | ||
chain: Chain; | ||
}; | ||
export * from '@swapkit/api'; | ||
export * from "@swapkit/api"; | ||
export {}; | ||
export { } |
1130
dist/index.es.js
@@ -1,8 +0,8 @@ | ||
var ye = Object.defineProperty; | ||
var we = (e, t, n) => t in e ? ye(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n; | ||
var p = (e, t, n) => (we(e, typeof t != "symbol" ? t + "" : t, n), n), Ve = (e, t, n) => { | ||
var $e = Object.defineProperty; | ||
var ve = (e, t, n) => t in e ? $e(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n; | ||
var _ = (e, t, n) => (ve(e, typeof t != "symbol" ? t + "" : t, n), n), Ie = (e, t, n) => { | ||
if (!t.has(e)) | ||
throw TypeError("Cannot " + n); | ||
}; | ||
var O = (e, t, n) => { | ||
var R = (e, t, n) => { | ||
if (t.has(e)) | ||
@@ -12,10 +12,8 @@ throw TypeError("Cannot add the same private member more than once"); | ||
}; | ||
var T = (e, t, n) => (Ve(e, t, "access private method"), n); | ||
import { FeeOption as Y, BaseDecimal as d, Chain as a, EVMChainList as Be, ChainToRPC as Le, MemoType as E, ChainToChainId as Ue } from "@swapkit/types"; | ||
var u = /* @__PURE__ */ ((e) => (e.INVALID_INPUT_PARAMETERS = "1000", e.UNKNOWN_PROVIDERS = "1001", e.CANNOT_FIND_INBOUND_ADDRESS = "1002", e.NO_INBOUND_ADDRESSES = "1003", e.CHAIN_HALTED_OR_UNSUPPORTED = "1004", e.MISSING_INPUT_PARAMETER = "1005", e.INVALID_TYPE_GENERIC = "1100", e.INVALID_NUMBER_STRING = "1101", e.INVALID_NUMBER = "1102", e.INVALID_BOOLEAN = "1103", e.INVALID_OBJECT = "1104", e.INVALID_ARRAY = "1105", e.SELL_AMOUNT_MUST_BE_POSITIVE_INTEGER = "2000", e.SELL_BUY_ASSETS_ARE_THE_SAME = "2001", e.MISSING_SOURCE_ADDRESS_FOR_SYNTH = "2002", e.AFF_ADDRESS_AND_BPS_OR_NEITHER = "2003", e.AFF_ADDRESS_TOO_LONG = "2004", e.AFF_BPS_INTEGER_MAX_500 = "2005", e.SOURCE_ADDRESS_INVALID_FOR_SELL_CHAIN = "2006", e.DESTINATION_ADDRESS_INVALID_FOR_BUY_CHAIN = "2007", e.PREFERRED_PROVIDER_NOT_SUPPORTED = "2008", e.DESTINATION_ADDRESS_SMART_CONTRACT = "2009", e.BUY_AMOUNT_MUST_BE_POSITIVE_INTEGER = "2010", e.SOURCE_ADDRESS_SMART_CONTRACT = "2011", e.INVALID_PROVIDER = "2100", e.MISSING_CROSS_CHAIN_PROVIDER = "2101", e.MISSING_AVAX_PROVIDER = "2102", e.MISSING_BSC_PROVIDER = "2103", e.MISSING_ETH_PROVIDER = "2104", e.INVALID_PROVIDER_FOR_SWAP_OUT = "2105", e.MISSING_ARB_PROVIDER = "2106", e.INVALID_CHAIN = "2200", e.INVALID_ASSET = "2201", e.INVALID_ASSET_IDENTIFIER = "2202", e.UNSUPPORTED_CHAIN = "2204", e.UNSUPPORTED_ASSET = "2203", e.UNSUPPORTED_ASSET_FOR_SWAPOUT = "2205", e.INVALID_SOURCE_ADDRESS = "2300", e.INVALID_DESTINATION_ADDRESS = "2301", e.THORNODE_QUOTE_GENERIC_ERROR = "3000", e.NOT_ENOUGH_SYNTH_BALANCE = "3001", e.SYNTH_MINTING_CAP_REACHED = "3002", e.INVALID_QUOTE_MODE = "4000", e.NO_QUOTES = "4001", e.SERVICE_UNAVAILABLE_GENERIC = "5000", e.MISSING_GAS_DATA_GENERIC = "5100", e.MISSING_TOKEN_INFO_GENERIC = "5200", e.CANT_FIND_TOKEN_LIST = "5201", e.NO_PRICE = "5202", e.PRICE_IS_STALE = "5203", e.ADDRESS_NOT_WHITELISTED = "6000", e.ADDRESS_ALREADY_CLAIMED = "6001", e.TEMPORARY_ERROR = "9999", e))(u || {}); | ||
u.INVALID_INPUT_PARAMETERS + "", u.UNKNOWN_PROVIDERS + "", u.CANNOT_FIND_INBOUND_ADDRESS + "", u.NO_INBOUND_ADDRESSES + "", u.CHAIN_HALTED_OR_UNSUPPORTED + "", u.MISSING_INPUT_PARAMETER + "", u.INVALID_TYPE_GENERIC + "", u.INVALID_NUMBER_STRING + "", u.INVALID_NUMBER + "", u.INVALID_BOOLEAN + "", u.INVALID_OBJECT + "", u.INVALID_ARRAY + "", u.SELL_AMOUNT_MUST_BE_POSITIVE_INTEGER + "", u.SELL_BUY_ASSETS_ARE_THE_SAME + "", u.MISSING_SOURCE_ADDRESS_FOR_SYNTH + "", u.AFF_ADDRESS_AND_BPS_OR_NEITHER + "", u.AFF_ADDRESS_TOO_LONG + "", u.AFF_BPS_INTEGER_MAX_500 + "", u.SOURCE_ADDRESS_INVALID_FOR_SELL_CHAIN + "", u.DESTINATION_ADDRESS_INVALID_FOR_BUY_CHAIN + "", u.PREFERRED_PROVIDER_NOT_SUPPORTED + "", u.SOURCE_ADDRESS_SMART_CONTRACT + "", u.DESTINATION_ADDRESS_SMART_CONTRACT + "", u.BUY_AMOUNT_MUST_BE_POSITIVE_INTEGER + "", u.INVALID_PROVIDER + "", u.MISSING_CROSS_CHAIN_PROVIDER + "", u.MISSING_AVAX_PROVIDER + "", u.MISSING_BSC_PROVIDER + "", u.MISSING_ETH_PROVIDER + "", u.MISSING_ARB_PROVIDER + "", u.INVALID_PROVIDER_FOR_SWAP_OUT + "", u.INVALID_CHAIN + "", u.INVALID_ASSET + "", u.UNSUPPORTED_CHAIN + "", u.UNSUPPORTED_ASSET + "", u.UNSUPPORTED_ASSET_FOR_SWAPOUT + "", u.THORNODE_QUOTE_GENERIC_ERROR + "", u.INVALID_SOURCE_ADDRESS + "", u.INVALID_DESTINATION_ADDRESS + "", u.NOT_ENOUGH_SYNTH_BALANCE + "", u.SYNTH_MINTING_CAP_REACHED + "", u.INVALID_QUOTE_MODE + "", u.NO_QUOTES + "", u.SERVICE_UNAVAILABLE_GENERIC + "", u.MISSING_GAS_DATA_GENERIC + "", u.MISSING_TOKEN_INFO_GENERIC + "", u.CANT_FIND_TOKEN_LIST + "", u.NO_PRICE + "", u.PRICE_IS_STALE + "", u.ADDRESS_NOT_WHITELISTED + "", u.ADDRESS_ALREADY_CLAIMED + ""; | ||
var j = /* @__PURE__ */ ((e) => (e.Arbitrum = "ARB", e.Avalanche = "AVAX", e.Binance = "BNB", e.BinanceSmartChain = "BSC", e.Bitcoin = "BTC", e.BitcoinCash = "BCH", e.Cosmos = "GAIA", e.Dogecoin = "DOGE", e.Ethereum = "ETH", e.Kujira = "KUJI", e.Litecoin = "LTC", e.Maya = "MAYA", e.Optimism = "OP", e.Polkadot = "DOT", e.Chainflip = "FLIP", e.Polygon = "MATIC", e.THORChain = "THOR", e))(j || {}), te = /* @__PURE__ */ ((e) => (e.Arbitrum = "42161", e.ArbitrumHex = "0xa4b1", e.Avalanche = "43114", e.AvalancheHex = "0xa86a", e.Binance = "Binance-Chain-Tigris", e.BinanceSmartChain = "56", e.BinanceSmartChainHex = "0x38", e.Bitcoin = "bitcoin", e.BitcoinCash = "bitcoincash", e.Chainflip = "chainflip", e.Cosmos = "cosmoshub-4", e.Dogecoin = "dogecoin", e.Kujira = "kaiyo-1", e.Ethereum = "1", e.EthereumHex = "0x1", e.Litecoin = "litecoin", e.Maya = "mayachain-mainnet-v1", e.MayaStagenet = "mayachain-stagenet-v1", e.Optimism = "10", e.OptimismHex = "0xa", e.Polkadot = "polkadot", e.Polygon = "137", e.PolygonHex = "0x89", e.THORChain = "thorchain-mainnet-v1", e.THORChainStagenet = "thorchain-stagenet-v2", e))(te || {}), de = /* @__PURE__ */ ((e) => (e.Arbitrum = "https://arb1.arbitrum.io/rpc", e.Avalanche = "https://node-router.thorswap.net/avalanche-c", e.Binance = "", e.BinanceSmartChain = "https://bsc-dataseed.binance.org", e.Bitcoin = "https://node-router.thorswap.net/bitcoin", e.BitcoinCash = "https://node-router.thorswap.net/bitcoin-cash", e.Chainflip = "wss://mainnet-archive.chainflip.io", e.Cosmos = "https://node-router.thorswap.net/cosmos/rpc", e.Kujira = "https://rpc-kujira.synergynodes.com/", e.Dogecoin = "https://node-router.thorswap.net/dogecoin", e.Ethereum = "https://node-router.thorswap.net/ethereum", e.Litecoin = "https://node-router.thorswap.net/litecoin", e.Maya = "https://tendermint.mayachain.info", e.MayaStagenet = "https://stagenet.tendermint.mayachain.info", e.Optimism = "https://mainnet.optimism.io", e.Polkadot = "wss://rpc.polkadot.io", e.Polygon = "https://polygon-rpc.com", e.THORChain = "https://rpc.thorswap.net", e.THORChainStagenet = "https://stagenet-rpc.ninerealms.com", e))(de || {}), R = /* @__PURE__ */ ((e) => (e.Cosmos = "https://node-router.thorswap.net/cosmos/rest", e.Kujira = "https://lcd-kujira.synergynodes.com/", e.MayanodeMainnet = "https://mayanode.mayachain.info", e.MayanodeStagenet = "https://stagenet.mayanode.mayachain.info", e.ThornodeMainnet = "https://thornode.thorswap.net", e.ThornodeStagenet = "https://stagenet-thornode.ninerealms.com", e.ThorswapApi = "https://api.thorswap.net", e.ThorswapStatic = "https://static.thorswap.net", e))(R || {}); | ||
const q = Object.values(j), ve = Object.keys(j), ne = q.reduce( | ||
var p = (e, t, n) => (Ie(e, t, "access private method"), n); | ||
import { FeeOption as K, BaseDecimal as d, Chain as l, EVMChains as Ne, ChainToRPC as Be, MemoType as C, ChainToChainId as De } from "@swapkit/types"; | ||
var F = /* @__PURE__ */ ((e) => (e.Arbitrum = "ARB", e.Avalanche = "AVAX", e.Binance = "BNB", e.BinanceSmartChain = "BSC", e.Bitcoin = "BTC", e.BitcoinCash = "BCH", e.Cosmos = "GAIA", e.Dash = "DASH", e.Dogecoin = "DOGE", e.Ethereum = "ETH", e.Kujira = "KUJI", e.Litecoin = "LTC", e.Maya = "MAYA", e.Optimism = "OP", e.Polkadot = "DOT", e.Chainflip = "FLIP", e.Polygon = "MATIC", e.THORChain = "THOR", e))(F || {}), ne = /* @__PURE__ */ ((e) => (e.Arbitrum = "42161", e.ArbitrumHex = "0xa4b1", e.Avalanche = "43114", e.AvalancheHex = "0xa86a", e.Binance = "Binance-Chain-Tigris", e.BinanceSmartChain = "56", e.BinanceSmartChainHex = "0x38", e.Bitcoin = "bitcoin", e.BitcoinCash = "bitcoincash", e.Chainflip = "chainflip", e.Cosmos = "cosmoshub-4", e.Dash = "dash", e.Dogecoin = "dogecoin", e.Kujira = "kaiyo-1", e.Ethereum = "1", e.EthereumHex = "0x1", e.Litecoin = "litecoin", e.Maya = "mayachain-mainnet-v1", e.MayaStagenet = "mayachain-stagenet-v1", e.Optimism = "10", e.OptimismHex = "0xa", e.Polkadot = "polkadot", e.Polygon = "137", e.PolygonHex = "0x89", e.THORChain = "thorchain-mainnet-v1", e.THORChainStagenet = "thorchain-stagenet-v2", e))(ne || {}), de = /* @__PURE__ */ ((e) => (e.Arbitrum = "https://arb1.arbitrum.io/rpc", e.Avalanche = "https://node-router.thorswap.net/avalanche-c", e.Binance = "", e.BinanceSmartChain = "https://bsc-dataseed.binance.org", e.Bitcoin = "https://node-router.thorswap.net/bitcoin", e.BitcoinCash = "https://node-router.thorswap.net/bitcoin-cash", e.Chainflip = "wss://mainnet-archive.chainflip.io", e.Cosmos = "https://node-router.thorswap.net/cosmos/rpc", e.Dash = "https://node-router.thorswap.net/dash", e.Dogecoin = "https://node-router.thorswap.net/dogecoin", e.Ethereum = "https://node-router.thorswap.net/ethereum", e.Kujira = "https://rpc-kujira.synergynodes.com/", e.Litecoin = "https://node-router.thorswap.net/litecoin", e.Maya = "https://tendermint.mayachain.info", e.MayaStagenet = "https://stagenet.tendermint.mayachain.info", e.Optimism = "https://mainnet.optimism.io", e.Polkadot = "wss://rpc.polkadot.io", e.Polygon = "https://polygon-rpc.com", e.THORChain = "https://rpc.thorswap.net", e.THORChainStagenet = "https://stagenet-rpc.ninerealms.com", e))(de || {}), S = /* @__PURE__ */ ((e) => (e.Cosmos = "https://node-router.thorswap.net/cosmos/rest", e.Kujira = "https://lcd-kujira.synergynodes.com/", e.MayanodeMainnet = "https://mayanode.mayachain.info", e.MayanodeStagenet = "https://stagenet.mayanode.mayachain.info", e.ThornodeMainnet = "https://thornode.thorswap.net", e.ThornodeStagenet = "https://stagenet-thornode.ninerealms.com", e.ThorswapApi = "https://api.thorswap.net", e.ThorswapStatic = "https://static.thorswap.net", e))(S || {}); | ||
const G = Object.values(F), Ve = Object.keys(F), re = G.reduce( | ||
(e, t) => { | ||
const n = ve.find((s) => j[s] === t); | ||
const n = Ve.find((r) => F[r] === t); | ||
return n && (e[t] = n), e; | ||
@@ -25,21 +23,21 @@ }, | ||
); | ||
q.reduce( | ||
(e, t) => (e[t] = te[ne[t]], e), | ||
G.reduce( | ||
(e, t) => (e[t] = ne[re[t]], e), | ||
{} | ||
); | ||
q.reduce( | ||
(e, t) => (e[t] = de[ne[t]], e), | ||
G.reduce( | ||
(e, t) => (e[t] = de[re[t]], e), | ||
{} | ||
); | ||
q.reduce( | ||
G.reduce( | ||
(e, t) => { | ||
const n = `${ne[t]}Hex`; | ||
return e[t] = te[n], e; | ||
const n = `${re[t]}Hex`; | ||
return e[t] = ne[n], e; | ||
}, | ||
{} | ||
); | ||
class oe extends Error { | ||
constructor(t, n, s) { | ||
const r = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", o = `${r} ${i}`.trim(), l = o ? `status code ${o}` : "an unknown error"; | ||
super(`Request failed with ${l}`), Object.defineProperty(this, "response", { | ||
class ae extends Error { | ||
constructor(t, n, r) { | ||
const s = t.status || t.status === 0 ? t.status : "", i = t.statusText || "", o = `${s} ${i}`.trim(), c = o ? `status code ${o}` : "an unknown error"; | ||
super(`Request failed with ${c}`), Object.defineProperty(this, "response", { | ||
enumerable: !0, | ||
@@ -59,6 +57,6 @@ configurable: !0, | ||
value: void 0 | ||
}), this.name = "HTTPError", this.response = t, this.request = n, this.options = s; | ||
}), this.name = "HTTPError", this.response = t, this.request = n, this.options = r; | ||
} | ||
} | ||
class Te extends Error { | ||
class pe extends Error { | ||
constructor(t) { | ||
@@ -73,27 +71,27 @@ super("Request timed out"), Object.defineProperty(this, "request", { | ||
} | ||
const M = (e) => e !== null && typeof e == "object", v = (...e) => { | ||
const k = (e) => e !== null && typeof e == "object", x = (...e) => { | ||
for (const t of e) | ||
if ((!M(t) || Array.isArray(t)) && t !== void 0) | ||
if ((!k(t) || Array.isArray(t)) && t !== void 0) | ||
throw new TypeError("The `options` argument must be an object"); | ||
return se({}, ...e); | ||
}, Ae = (e = {}, t = {}) => { | ||
const n = new globalThis.Headers(e), s = t instanceof globalThis.Headers, r = new globalThis.Headers(t); | ||
for (const [i, o] of r.entries()) | ||
s && o === "undefined" || o === void 0 ? n.delete(i) : n.set(i, o); | ||
}, me = (e = {}, t = {}) => { | ||
const n = new globalThis.Headers(e), r = t instanceof globalThis.Headers, s = new globalThis.Headers(t); | ||
for (const [i, o] of s.entries()) | ||
r && o === "undefined" || o === void 0 ? n.delete(i) : n.set(i, o); | ||
return n; | ||
}, se = (...e) => { | ||
let t = {}, n = {}; | ||
for (const s of e) | ||
if (Array.isArray(s)) | ||
Array.isArray(t) || (t = []), t = [...t, ...s]; | ||
else if (M(s)) { | ||
for (let [r, i] of Object.entries(s)) | ||
M(i) && r in t && (i = se(t[r], i)), t = { ...t, [r]: i }; | ||
M(s.headers) && (n = Ae(n, s.headers), t.headers = n); | ||
for (const r of e) | ||
if (Array.isArray(r)) | ||
Array.isArray(t) || (t = []), t = [...t, ...r]; | ||
else if (k(r)) { | ||
for (let [s, i] of Object.entries(r)) | ||
k(i) && s in t && (i = se(t[s], i)), t = { ...t, [s]: i }; | ||
k(r.headers) && (n = me(n, r.headers), t.headers = n); | ||
} | ||
return t; | ||
}, $e = (() => { | ||
}, He = (() => { | ||
let e = !1, t = !1; | ||
const n = typeof globalThis.ReadableStream == "function", s = typeof globalThis.Request == "function"; | ||
return n && s && (t = new globalThis.Request("https://empty.invalid", { | ||
const n = typeof globalThis.ReadableStream == "function", r = typeof globalThis.Request == "function"; | ||
return n && r && (t = new globalThis.Request("https://empty.invalid", { | ||
body: new globalThis.ReadableStream(), | ||
@@ -106,3 +104,3 @@ method: "POST", | ||
}).headers.has("Content-Type")), e && !t; | ||
})(), Me = typeof globalThis.AbortController == "function", He = typeof globalThis.ReadableStream == "function", Fe = typeof globalThis.FormData == "function", pe = ["get", "post", "put", "patch", "head", "delete"], xe = { | ||
})(), xe = typeof globalThis.AbortController == "function", Me = typeof globalThis.ReadableStream == "function", ke = typeof globalThis.FormData == "function", _e = ["get", "post", "put", "patch", "head", "delete"], Le = { | ||
json: "application/json", | ||
@@ -113,3 +111,3 @@ text: "text/*", | ||
blob: "*/*" | ||
}, K = 2147483647, Se = Symbol("stop"), Ge = { | ||
}, J = 2147483647, Te = Symbol("stop"), We = { | ||
json: !0, | ||
@@ -125,3 +123,3 @@ parseJson: !0, | ||
fetch: !0 | ||
}, We = { | ||
}, Ue = { | ||
method: !0, | ||
@@ -142,11 +140,11 @@ headers: !0, | ||
duplex: !0 | ||
}, ke = (e) => pe.includes(e) ? e.toUpperCase() : e, je = ["get", "put", "head", "delete", "options", "trace"], qe = [408, 413, 429, 500, 502, 503, 504], me = [413, 429, 503], ce = { | ||
}, je = (e) => _e.includes(e) ? e.toUpperCase() : e, qe = ["get", "put", "head", "delete", "options", "trace"], Fe = [408, 413, 429, 500, 502, 503, 504], fe = [413, 429, 503], ce = { | ||
limit: 2, | ||
methods: je, | ||
statusCodes: qe, | ||
afterStatusCodes: me, | ||
methods: qe, | ||
statusCodes: Fe, | ||
afterStatusCodes: fe, | ||
maxRetryAfter: Number.POSITIVE_INFINITY, | ||
backoffLimit: Number.POSITIVE_INFINITY, | ||
delay: (e) => 0.3 * 2 ** (e - 1) * 1e3 | ||
}, Xe = (e = {}) => { | ||
}, Ge = (e = {}) => { | ||
if (typeof e == "number") | ||
@@ -164,11 +162,11 @@ return { | ||
...e, | ||
afterStatusCodes: me | ||
afterStatusCodes: fe | ||
}; | ||
}; | ||
async function Ye(e, t, n, s) { | ||
return new Promise((r, i) => { | ||
async function Xe(e, t, n, r) { | ||
return new Promise((s, i) => { | ||
const o = setTimeout(() => { | ||
n && n.abort(), i(new Te(e)); | ||
}, s.timeout); | ||
s.fetch(e, t).then(r).catch(i).then(() => { | ||
n && n.abort(), i(new pe(e)); | ||
}, r.timeout); | ||
r.fetch(e, t).then(s).catch(i).then(() => { | ||
clearTimeout(o); | ||
@@ -179,9 +177,9 @@ }); | ||
async function Ke(e, { signal: t }) { | ||
return new Promise((n, s) => { | ||
t && (t.throwIfAborted(), t.addEventListener("abort", r, { once: !0 })); | ||
function r() { | ||
clearTimeout(i), s(t.reason); | ||
return new Promise((n, r) => { | ||
t && (t.throwIfAborted(), t.addEventListener("abort", s, { once: !0 })); | ||
function s() { | ||
clearTimeout(i), r(t.reason); | ||
} | ||
const i = setTimeout(() => { | ||
t == null || t.removeEventListener("abort", r), n(); | ||
t == null || t.removeEventListener("abort", s), n(); | ||
}, e); | ||
@@ -192,43 +190,43 @@ }); | ||
const n = {}; | ||
for (const s in t) | ||
!(s in We) && !(s in Ge) && !(s in e) && (n[s] = t[s]); | ||
for (const r in t) | ||
!(r in Ue) && !(r in We) && !(r in e) && (n[r] = t[r]); | ||
return n; | ||
}; | ||
class x { | ||
class W { | ||
static create(t, n) { | ||
const s = new x(t, n), r = async () => { | ||
if (typeof s._options.timeout == "number" && s._options.timeout > K) | ||
throw new RangeError(`The \`timeout\` option cannot be greater than ${K}`); | ||
const r = new W(t, n), s = async () => { | ||
if (typeof r._options.timeout == "number" && r._options.timeout > J) | ||
throw new RangeError(`The \`timeout\` option cannot be greater than ${J}`); | ||
await Promise.resolve(); | ||
let o = await s._fetch(); | ||
for (const l of s._options.hooks.afterResponse) { | ||
const c = await l(s.request, s._options, s._decorateResponse(o.clone())); | ||
c instanceof globalThis.Response && (o = c); | ||
let o = await r._fetch(); | ||
for (const c of r._options.hooks.afterResponse) { | ||
const a = await c(r.request, r._options, r._decorateResponse(o.clone())); | ||
a instanceof globalThis.Response && (o = a); | ||
} | ||
if (s._decorateResponse(o), !o.ok && s._options.throwHttpErrors) { | ||
let l = new oe(o, s.request, s._options); | ||
for (const c of s._options.hooks.beforeError) | ||
l = await c(l); | ||
throw l; | ||
if (r._decorateResponse(o), !o.ok && r._options.throwHttpErrors) { | ||
let c = new ae(o, r.request, r._options); | ||
for (const a of r._options.hooks.beforeError) | ||
c = await a(c); | ||
throw c; | ||
} | ||
if (s._options.onDownloadProgress) { | ||
if (typeof s._options.onDownloadProgress != "function") | ||
if (r._options.onDownloadProgress) { | ||
if (typeof r._options.onDownloadProgress != "function") | ||
throw new TypeError("The `onDownloadProgress` option must be a function"); | ||
if (!He) | ||
if (!Me) | ||
throw new Error("Streams are not supported in your environment. `ReadableStream` is missing."); | ||
return s._stream(o.clone(), s._options.onDownloadProgress); | ||
return r._stream(o.clone(), r._options.onDownloadProgress); | ||
} | ||
return o; | ||
}, i = s._options.retry.methods.includes(s.request.method.toLowerCase()) ? s._retry(r) : r(); | ||
for (const [o, l] of Object.entries(xe)) | ||
}, i = r._options.retry.methods.includes(r.request.method.toLowerCase()) ? r._retry(s) : s(); | ||
for (const [o, c] of Object.entries(Le)) | ||
i[o] = async () => { | ||
s.request.headers.set("accept", s.request.headers.get("accept") || l); | ||
const c = (await i).clone(); | ||
r.request.headers.set("accept", r.request.headers.get("accept") || c); | ||
const a = (await i).clone(); | ||
if (o === "json") { | ||
if (c.status === 204 || (await c.clone().arrayBuffer()).byteLength === 0) | ||
if (a.status === 204 || (await a.clone().arrayBuffer()).byteLength === 0) | ||
return ""; | ||
if (n.parseJson) | ||
return n.parseJson(await c.text()); | ||
return n.parseJson(await a.text()); | ||
} | ||
return c[o](); | ||
return a[o](); | ||
}; | ||
@@ -268,3 +266,3 @@ return i; | ||
...n, | ||
headers: Ae(this._input.headers, n.headers), | ||
headers: me(this._input.headers, n.headers), | ||
hooks: se({ | ||
@@ -276,6 +274,6 @@ beforeRequest: [], | ||
}, n.hooks), | ||
method: ke(n.method ?? this._input.method), | ||
method: je(n.method ?? this._input.method), | ||
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing | ||
prefixUrl: String(n.prefixUrl || ""), | ||
retry: Xe(n.retry), | ||
retry: Ge(n.retry), | ||
throwHttpErrors: n.throwHttpErrors !== !1, | ||
@@ -291,7 +289,7 @@ timeout: n.timeout ?? 1e4, | ||
} | ||
if (Me) { | ||
if (xe) { | ||
if (this.abortController = new globalThis.AbortController(), this._options.signal) { | ||
const s = this._options.signal; | ||
const r = this._options.signal; | ||
this._options.signal.addEventListener("abort", () => { | ||
this.abortController.abort(s.reason); | ||
this.abortController.abort(r.reason); | ||
}); | ||
@@ -301,5 +299,5 @@ } | ||
} | ||
if ($e && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) { | ||
const s = "?" + (typeof this._options.searchParams == "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString()), r = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, s); | ||
(Fe && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"]) && this.request.headers.delete("content-type"), this.request = new globalThis.Request(new globalThis.Request(r, { ...this.request }), this._options); | ||
if (He && (this._options.duplex = "half"), this.request = new globalThis.Request(this._input, this._options), this._options.searchParams) { | ||
const r = "?" + (typeof this._options.searchParams == "string" ? this._options.searchParams.replace(/^\?/, "") : new URLSearchParams(this._options.searchParams).toString()), s = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, r); | ||
(ke && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers["content-type"]) && this.request.headers.delete("content-type"), this.request = new globalThis.Request(new globalThis.Request(s, { ...this.request }), this._options); | ||
} | ||
@@ -309,10 +307,10 @@ this._options.json !== void 0 && (this._options.body = JSON.stringify(this._options.json), this.request.headers.set("content-type", this._options.headers.get("content-type") ?? "application/json"), this.request = new globalThis.Request(this.request, { body: this._options.body })); | ||
_calculateRetryDelay(t) { | ||
if (this._retryCount++, this._retryCount <= this._options.retry.limit && !(t instanceof Te)) { | ||
if (t instanceof oe) { | ||
if (this._retryCount++, this._retryCount <= this._options.retry.limit && !(t instanceof pe)) { | ||
if (t instanceof ae) { | ||
if (!this._options.retry.statusCodes.includes(t.response.status)) | ||
return 0; | ||
const s = t.response.headers.get("Retry-After"); | ||
if (s && this._options.retry.afterStatusCodes.includes(t.response.status)) { | ||
let r = Number(s); | ||
return Number.isNaN(r) ? r = Date.parse(s) - Date.now() : r *= 1e3, this._options.retry.maxRetryAfter !== void 0 && r > this._options.retry.maxRetryAfter ? 0 : r; | ||
const r = t.response.headers.get("Retry-After"); | ||
if (r && this._options.retry.afterStatusCodes.includes(t.response.status)) { | ||
let s = Number(r); | ||
return Number.isNaN(s) ? s = Date.parse(r) - Date.now() : s *= 1e3, this._options.retry.maxRetryAfter !== void 0 && s > this._options.retry.maxRetryAfter ? 0 : s; | ||
} | ||
@@ -334,7 +332,7 @@ if (t.response.status === 413) | ||
} catch (n) { | ||
const s = Math.min(this._calculateRetryDelay(n), K); | ||
if (s !== 0 && this._retryCount > 0) { | ||
await Ke(s, { signal: this._options.signal }); | ||
for (const r of this._options.hooks.beforeRetry) | ||
if (await r({ | ||
const r = Math.min(this._calculateRetryDelay(n), J); | ||
if (r !== 0 && this._retryCount > 0) { | ||
await Ke(r, { signal: this._options.signal }); | ||
for (const s of this._options.hooks.beforeRetry) | ||
if (await s({ | ||
request: this.request, | ||
@@ -344,3 +342,3 @@ options: this._options, | ||
retryCount: this._retryCount | ||
}) === Se) | ||
}) === Te) | ||
return; | ||
@@ -354,18 +352,18 @@ return this._retry(t); | ||
for (const n of this._options.hooks.beforeRequest) { | ||
const s = await n(this.request, this._options); | ||
if (s instanceof Request) { | ||
this.request = s; | ||
const r = await n(this.request, this._options); | ||
if (r instanceof Request) { | ||
this.request = r; | ||
break; | ||
} | ||
if (s instanceof Response) | ||
return s; | ||
if (r instanceof Response) | ||
return r; | ||
} | ||
const t = Je(this.request, this._options); | ||
return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Ye(this.request.clone(), t, this.abortController, this._options); | ||
return this._options.timeout === !1 ? this._options.fetch(this.request.clone(), t) : Xe(this.request.clone(), t, this.abortController, this._options); | ||
} | ||
/* istanbul ignore next */ | ||
_stream(t, n) { | ||
const s = Number(t.headers.get("content-length")) || 0; | ||
let r = 0; | ||
return t.status === 204 ? (n && n({ percent: 1, totalBytes: s, transferredBytes: r }, new Uint8Array()), new globalThis.Response(null, { | ||
const r = Number(t.headers.get("content-length")) || 0; | ||
let s = 0; | ||
return t.status === 204 ? (n && n({ percent: 1, totalBytes: r, transferredBytes: s }, new Uint8Array()), new globalThis.Response(null, { | ||
status: t.status, | ||
@@ -377,6 +375,6 @@ statusText: t.statusText, | ||
const o = t.body.getReader(); | ||
n && n({ percent: 0, transferredBytes: 0, totalBytes: s }, new Uint8Array()); | ||
async function l() { | ||
const { done: c, value: _ } = await o.read(); | ||
if (c) { | ||
n && n({ percent: 0, transferredBytes: 0, totalBytes: r }, new Uint8Array()); | ||
async function c() { | ||
const { done: a, value: u } = await o.read(); | ||
if (a) { | ||
i.close(); | ||
@@ -386,9 +384,9 @@ return; | ||
if (n) { | ||
r += _.byteLength; | ||
const h = s === 0 ? 0 : r / s; | ||
n({ percent: h, transferredBytes: r, totalBytes: s }, _); | ||
s += u.byteLength; | ||
const h = r === 0 ? 0 : s / r; | ||
n({ percent: h, transferredBytes: s, totalBytes: r }, u); | ||
} | ||
i.enqueue(_), await l(); | ||
i.enqueue(u), await c(); | ||
} | ||
await l(); | ||
await c(); | ||
} | ||
@@ -403,46 +401,50 @@ }), { | ||
/*! MIT License © Sindre Sorhus */ | ||
const Q = (e) => { | ||
const t = (n, s) => x.create(n, v(e, s)); | ||
for (const n of pe) | ||
t[n] = (s, r) => x.create(s, v(e, r, { method: n })); | ||
return t.create = (n) => Q(v(n)), t.extend = (n) => Q(v(e, n)), t.stop = Se, t; | ||
}, Ee = Q(); | ||
let H; | ||
const m = { | ||
CachedPrices: `${R.ThorswapApi}/tokenlist/cached-price`, | ||
GasRates: `${R.ThorswapApi}/resource-worker/gasPrice/getAll`, | ||
Quote: `${R.ThorswapApi}/aggregator/tokens/quote`, | ||
Txn: `${R.ThorswapApi}/apiusage/v2/txn`, | ||
TokenlistProviders: `${R.ThorswapApi}/tokenlist/providers`, | ||
TokenList: `${R.ThorswapStatic}/token-list`, | ||
Thorname: `${R.ThorswapApi}/thorname` | ||
}, Re = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, le = () => H || (H = Ee.create({ headers: Re }), H), mt = ({ apiKey: e, ...t }) => { | ||
H = Ee.create({ | ||
const z = (e) => { | ||
const t = (n, r) => W.create(n, x(e, r)); | ||
for (const n of _e) | ||
t[n] = (r, s) => W.create(r, x(e, s, { method: n })); | ||
return t.create = (n) => z(x(n)), t.extend = (n) => z(x(e, n)), t.stop = Te, t; | ||
}, ge = z(); | ||
let L; | ||
const f = { | ||
CachedPrices: `${S.ThorswapApi}/tokenlist/cached-price`, | ||
GasRates: `${S.ThorswapApi}/resource-worker/gasPrice/getAll`, | ||
Quote: `${S.ThorswapApi}/aggregator/tokens/quote`, | ||
Txn: `${S.ThorswapApi}/apiusage/v2/txn`, | ||
TokenlistProviders: `${S.ThorswapApi}/tokenlist/providers`, | ||
TokenList: `${S.ThorswapStatic}/token-list`, | ||
Thorname: `${S.ThorswapApi}/thorname` | ||
}, Ae = typeof window < "u" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" }, le = () => L || (L = ge.create({ headers: Ae }), L), ft = ({ apiKey: e, ...t }) => { | ||
L = ge.create({ | ||
...t, | ||
headers: { ...Re, ...t.headers, "x-api-key": e } | ||
headers: { ...Ae, ...t.headers, "x-api-key": e } | ||
}); | ||
}, S = { | ||
}, T = { | ||
get: (e, t) => le().get(e, t).json(), | ||
post: (e, t) => le().post(e, t).json() | ||
}, Qe = ({ tokens: e, ...t }) => { | ||
const n = new URLSearchParams(); | ||
return e.filter((s, r, i) => i.findIndex((o) => o === s) === r).forEach((s) => n.append("tokens", JSON.stringify(s))), t.metadata && n.append("metadata", "true"), t.lookup && n.append("lookup", "true"), t.sparkline && n.append("sparkline", "true"), S.post(m.CachedPrices, { | ||
}, Ye = ({ tokens: e, ...t }) => { | ||
const n = new URLSearchParams(), r = e.filter( | ||
(s, i, o) => o.findIndex((c) => c === s) === i | ||
); | ||
for (const s of r) | ||
n.append("tokens", JSON.stringify(s)); | ||
return t.metadata && n.append("metadata", "true"), t.lookup && n.append("lookup", "true"), t.sparkline && n.append("sparkline", "true"), T.post(f.CachedPrices, { | ||
body: n.toString(), | ||
headers: { "Content-Type": "application/x-www-form-urlencoded" } | ||
}); | ||
}, Et = { | ||
getCachedPrices: Qe, | ||
getQuote: (e) => S.get(m.Quote, { searchParams: e }), | ||
getGasRates: () => S.get(m.GasRates), | ||
getTxnDetails: (e) => S.get(m.Txn, { searchParams: e }), | ||
getTokenlistProviders: () => S.get(m.TokenlistProviders), | ||
getTokenList: (e) => S.get(`${m.TokenList}/${e}.json`), | ||
getThornameAddresses: (e) => S.get(`${m.Thorname}/${e}`), | ||
getThornameRegisteredChains: (e) => S.get(`${m.Thorname}/chains/${e}`), | ||
getThornameRlookup: (e, t) => S.get(`${m.Thorname}/rlookup`, { searchParams: { address: e, chain: t } }) | ||
}, gt = { | ||
getCachedPrices: Ye, | ||
getQuote: (e) => T.get(f.Quote, { searchParams: e }), | ||
getGasRates: () => T.get(f.GasRates), | ||
getTxnDetails: (e) => T.get(f.Txn, { searchParams: e }), | ||
getTokenlistProviders: () => T.get(f.TokenlistProviders), | ||
getTokenList: (e) => T.get(`${f.TokenList}/${e}.json`), | ||
getThornameAddresses: (e) => T.get(`${f.Thorname}/${e}`), | ||
getThornameRegisteredChains: (e) => T.get(`${f.Thorname}/chains/${e}`), | ||
getThornameRlookup: (e, t) => T.get(`${f.Thorname}/rlookup`, { searchParams: { address: e, chain: t } }) | ||
}; | ||
var ze = /* @__PURE__ */ ((e) => (e.SWAP_TC_TO_TC = "SWAP:TC-TC", e.SWAP_ETH_TO_TC = "SWAP:ERC20-TC", e.SWAP_TC_TO_ETH = "SWAP:TC-ERC20", e.SWAP_ETH_TO_ETH = "SWAP:ERC20-ERC20", e.SWAP_AVAX_TO_TC = "SWAP:AVAX-TC", e.SWAP_TC_TO_AVAX = "SWAP:TC-AVAX", e.SWAP_AVAX_TO_AVAX = "SWAP:AVAX-AVAX", e.SWAP_ETH_TO_AVAX = "SWAP:ETH-AVAX", e.SWAP_AVAX_TO_ETH = "SWAP:AVAX-ETH", e.SWAP_TC_TO_GAIA = "SWAP:TC-GAIA", e.SWAP_GAIA_TO_TC = "SWAP:GAIA-TC", e.SWAP_TC_TO_BNB = "SWAP:TC-BNB", e.SWAP_BNB_TO_TC = "SWAP:BNB-TC", e.SWAP_TC_TO_BTC = "SWAP:TC-BTC", e.SWAP_BTC_TO_TC = "SWAP:BTC-TC", e.SWAP_TC_TO_BCH = "SWAP:TC-BCH", e.SWAP_BCH_TO_TC = "SWAP:BCH-TC", e.SWAP_TC_TO_LTC = "SWAP:TC-LTC", e.SWAP_LTC_TO_TC = "SWAP:LTC-TC", e.SWAP_TC_TO_DOGE = "SWAP:TC-DOGE", e.SWAP_DOGE_TO_TC = "SWAP:DOGE-TC", e.TC_STATUS = "TC:STATUS", e.TC_TRANSFER = "TC:TRANSFER", e.TC_DEPOSIT = "TC:DEPOSIT", e.TC_SEND = "TC:SEND", e.TC_SWITCH = "TC:SWITCH", e.TC_LP_ADD = "TC:ADDLIQUIDITY", e.TC_LP_WITHDRAW = "TC:WITHDRAW", e.TC_TNS_CREATE = "TC:TNS-CREATE", e.TC_TNS_EXTEND = "TC:TNS-EXTEND", e.TC_TNS_UPDATE = "TC:TNS-UPDATE", e.TC_SAVINGS_ADD = "TC:ADDSAVINGS", e.TC_SAVINGS_WITHDRAW = "TC:WITHDRAWSAVINGS", e.TC_LENDING_OPEN = "TC:LENDINGOPEN", e.TC_LENDING_CLOSE = "TC:LENDINGCLOSE", e.ETH_APPROVAL = "ETH:APPROVAL", e.ETH_STATUS = "ETH:STATUS", e.ETH_TRANSFER_TO_TC = "ETH:TRANSFER:IN", e.ETH_TRANSFER_FROM_TC = "ETH:TRANSFER:OUT", e.AVAX_APPROVAL = "AVAX:APPROVAL", e.AVAX_STATUS = "AVAX:STATUS", e.AVAX_TRANSFER_TO_TC = "AVAX:TRANSFER:IN", e.AVAX_TRANSFER_FROM_TC = "AVAX:TRANSFER:OUT", e.BSC_APPROVAL = "BSC:APPROVAL", e.BSC_STATUS = "BSC:STATUS", e.BSC_TRANSFER_TO_TC = "BSC:TRANSFER:IN", e.BSC_TRANSFER_FROM_TC = "BSC:TRANSFER:OUT", e.APPROVAL = "APPROVAL", e.STATUS = "STATUS", e.TRANSFER_TO_TC = "TRANSFER:IN", e.TRANSFER_FROM_TC = "TRANSFER:OUT", e.UNSUPPORTED = "UNSUPPORTED", e.TC_LENDING = "TC:LENDING", e))(ze || {}), Ze = /* @__PURE__ */ ((e) => (e.PENDING = "pending", e.SUCCESS = "success", e.CANCELLED = "cancelled", e.REFUNDED = "refunded", e.REPLACED = "replaced", e.ERROR = "error", e.UNKNOWN = "unknown", e.NOT_STARTED = "not_started", e.NOT_FOUND = "not_found", e.RETRIES_EXCEEDED = "retries_exceeded", e.STREAMING = "streaming", e))(Ze || {}), et = /* @__PURE__ */ ((e) => (e[e.NOT_STARTED = 0] = "NOT_STARTED", e[e.SUCCESS = 1] = "SUCCESS", e[e.REFUNDED = 2] = "REFUNDED", e))(et || {}); | ||
const tt = "0x313ce567", Ie = async ({ chain: e, to: t }) => { | ||
var Qe = /* @__PURE__ */ ((e) => (e.SWAP_TC_TO_TC = "SWAP:TC-TC", e.SWAP_ETH_TO_TC = "SWAP:ERC20-TC", e.SWAP_TC_TO_ETH = "SWAP:TC-ERC20", e.SWAP_ETH_TO_ETH = "SWAP:ERC20-ERC20", e.SWAP_AVAX_TO_TC = "SWAP:AVAX-TC", e.SWAP_TC_TO_AVAX = "SWAP:TC-AVAX", e.SWAP_AVAX_TO_AVAX = "SWAP:AVAX-AVAX", e.SWAP_ETH_TO_AVAX = "SWAP:ETH-AVAX", e.SWAP_AVAX_TO_ETH = "SWAP:AVAX-ETH", e.SWAP_TC_TO_GAIA = "SWAP:TC-GAIA", e.SWAP_GAIA_TO_TC = "SWAP:GAIA-TC", e.SWAP_TC_TO_BNB = "SWAP:TC-BNB", e.SWAP_BNB_TO_TC = "SWAP:BNB-TC", e.SWAP_TC_TO_BTC = "SWAP:TC-BTC", e.SWAP_BTC_TO_TC = "SWAP:BTC-TC", e.SWAP_TC_TO_BCH = "SWAP:TC-BCH", e.SWAP_BCH_TO_TC = "SWAP:BCH-TC", e.SWAP_TC_TO_LTC = "SWAP:TC-LTC", e.SWAP_LTC_TO_TC = "SWAP:LTC-TC", e.SWAP_TC_TO_DOGE = "SWAP:TC-DOGE", e.SWAP_DOGE_TO_TC = "SWAP:DOGE-TC", e.TC_STATUS = "TC:STATUS", e.TC_TRANSFER = "TC:TRANSFER", e.TC_DEPOSIT = "TC:DEPOSIT", e.TC_SEND = "TC:SEND", e.TC_SWITCH = "TC:SWITCH", e.TC_LP_ADD = "TC:ADDLIQUIDITY", e.TC_LP_WITHDRAW = "TC:WITHDRAW", e.TC_TNS_CREATE = "TC:TNS-CREATE", e.TC_TNS_EXTEND = "TC:TNS-EXTEND", e.TC_TNS_UPDATE = "TC:TNS-UPDATE", e.TC_SAVINGS_ADD = "TC:ADDSAVINGS", e.TC_SAVINGS_WITHDRAW = "TC:WITHDRAWSAVINGS", e.TC_LENDING_OPEN = "TC:LENDINGOPEN", e.TC_LENDING_CLOSE = "TC:LENDINGCLOSE", e.ETH_APPROVAL = "ETH:APPROVAL", e.ETH_STATUS = "ETH:STATUS", e.ETH_TRANSFER_TO_TC = "ETH:TRANSFER:IN", e.ETH_TRANSFER_FROM_TC = "ETH:TRANSFER:OUT", e.AVAX_APPROVAL = "AVAX:APPROVAL", e.AVAX_STATUS = "AVAX:STATUS", e.AVAX_TRANSFER_TO_TC = "AVAX:TRANSFER:IN", e.AVAX_TRANSFER_FROM_TC = "AVAX:TRANSFER:OUT", e.BSC_APPROVAL = "BSC:APPROVAL", e.BSC_STATUS = "BSC:STATUS", e.BSC_TRANSFER_TO_TC = "BSC:TRANSFER:IN", e.BSC_TRANSFER_FROM_TC = "BSC:TRANSFER:OUT", e.APPROVAL = "APPROVAL", e.STATUS = "STATUS", e.TRANSFER_TO_TC = "TRANSFER:IN", e.TRANSFER_FROM_TC = "TRANSFER:OUT", e.UNSUPPORTED = "UNSUPPORTED", e.TC_LENDING = "TC:LENDING", e))(Qe || {}), ze = /* @__PURE__ */ ((e) => (e.PENDING = "pending", e.SUCCESS = "success", e.CANCELLED = "cancelled", e.REFUNDED = "refunded", e.REPLACED = "replaced", e.ERROR = "error", e.UNKNOWN = "unknown", e.NOT_STARTED = "not_started", e.NOT_FOUND = "not_found", e.RETRIES_EXCEEDED = "retries_exceeded", e.STREAMING = "streaming", e))(ze || {}), Ze = /* @__PURE__ */ ((e) => (e[e.NOT_STARTED = 0] = "NOT_STARTED", e[e.SUCCESS = 1] = "SUCCESS", e[e.REFUNDED = 2] = "REFUNDED", e))(Ze || {}); | ||
const et = "0x313ce567", Ce = async ({ chain: e, to: t }) => { | ||
try { | ||
const { result: n } = await S.post(Le[e], { | ||
const { result: n } = await T.post(Be[e], { | ||
headers: { | ||
@@ -457,3 +459,3 @@ accept: "*/*", | ||
method: "eth_call", | ||
params: [{ to: t.toLowerCase(), data: tt }, "latest"] | ||
params: [{ to: t.toLowerCase(), data: et }, "latest"] | ||
}) | ||
@@ -465,17 +467,17 @@ }); | ||
} | ||
}, nt = async (e) => { | ||
if (e === a.Ethereum) | ||
}, tt = (e) => { | ||
if (e === l.Ethereum) | ||
return d.ETH; | ||
const [, t] = e.split("-"); | ||
return t != null && t.startsWith("0x") ? Ie({ chain: a.Ethereum, to: t }) : d.ETH; | ||
}, st = async (e) => { | ||
return t != null && t.startsWith("0x") ? Ce({ chain: l.Ethereum, to: t }) : d.ETH; | ||
}, nt = (e) => { | ||
const [, t] = e.split("-"); | ||
return t != null && t.startsWith("0x") ? Ie({ chain: a.Avalanche, to: t.toLowerCase() }) : d.AVAX; | ||
}, rt = async (e) => e === a.BinanceSmartChain ? d.BSC : d.BSC, it = async ({ chain: e, symbol: t }) => { | ||
return t != null && t.startsWith("0x") ? Ce({ chain: l.Avalanche, to: t.toLowerCase() }) : d.AVAX; | ||
}, rt = (e) => e === l.BinanceSmartChain ? d.BSC : d.BSC, st = ({ chain: e, symbol: t }) => { | ||
switch (e) { | ||
case a.Ethereum: | ||
case l.Ethereum: | ||
return tt(t); | ||
case l.Avalanche: | ||
return nt(t); | ||
case a.Avalanche: | ||
return st(t); | ||
case a.BinanceSmartChain: | ||
case l.BinanceSmartChain: | ||
return rt(t); | ||
@@ -485,65 +487,45 @@ default: | ||
} | ||
}, Rt = { | ||
[Y.Average]: 1.2, | ||
[Y.Fast]: 1.5, | ||
[Y.Fastest]: 2 | ||
}, fe = ({ chain: e, symbol: t }) => { | ||
}, At = { | ||
[K.Average]: 1.2, | ||
[K.Fast]: 1.5, | ||
[K.Fastest]: 2 | ||
}, Se = ({ chain: e, symbol: t }) => { | ||
switch (e) { | ||
case a.Bitcoin: | ||
case a.BitcoinCash: | ||
case a.Litecoin: | ||
case a.Dogecoin: | ||
case a.Binance: | ||
case a.Ethereum: | ||
case a.Avalanche: | ||
case a.Polkadot: | ||
case a.Chainflip: | ||
return t === e; | ||
case a.Arbitrum: | ||
case a.Optimism: | ||
case l.Arbitrum: | ||
case l.Optimism: | ||
return t === "ETH"; | ||
case a.Maya: | ||
case l.Maya: | ||
return t === "CACAO"; | ||
case a.Kujira: | ||
case l.Kujira: | ||
return t === "KUJI"; | ||
case a.Cosmos: | ||
case l.Cosmos: | ||
return t === "ATOM"; | ||
case a.Polygon: | ||
case l.Polygon: | ||
return t === "MATIC"; | ||
case a.BinanceSmartChain: | ||
case l.BinanceSmartChain: | ||
return t === "BNB"; | ||
case a.THORChain: | ||
case l.THORChain: | ||
return t === "RUNE"; | ||
default: | ||
return t === e; | ||
} | ||
}, at = (e) => { | ||
}, it = (e) => { | ||
switch (e) { | ||
case `${a.Ethereum}.THOR`: | ||
case `${l.Ethereum}.THOR`: | ||
return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 }; | ||
case `${a.Ethereum}.vTHOR`: | ||
case `${l.Ethereum}.vTHOR`: | ||
return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 }; | ||
case a.Cosmos: | ||
case l.Cosmos: | ||
return { identifier: "GAIA.ATOM", decimal: d[e] }; | ||
case a.THORChain: | ||
case l.THORChain: | ||
return { identifier: "THOR.RUNE", decimal: d[e] }; | ||
case a.BinanceSmartChain: | ||
case l.BinanceSmartChain: | ||
return { identifier: "BSC.BNB", decimal: d[e] }; | ||
case a.Maya: | ||
case l.Maya: | ||
return { identifier: "MAYA.CACAO", decimal: d.MAYA }; | ||
case `${a.Maya}.MAYA`: | ||
case `${l.Maya}.MAYA`: | ||
return { identifier: "MAYA.MAYA", decimal: 4 }; | ||
case `${a.Kujira}.USK`: | ||
return { identifier: `${a.Kujira}.USK`, decimal: 6 }; | ||
case a.Kujira: | ||
case a.Arbitrum: | ||
case a.Optimism: | ||
case a.BitcoinCash: | ||
case a.Litecoin: | ||
case a.Dogecoin: | ||
case a.Binance: | ||
case a.Avalanche: | ||
case a.Chainflip: | ||
case a.Polygon: | ||
case a.Polkadot: | ||
case a.Bitcoin: | ||
case a.Ethereum: | ||
case `${l.Kujira}.USK`: | ||
return { identifier: `${l.Kujira}.USK`, decimal: 6 }; | ||
default: | ||
return { identifier: `${e}.${e}`, decimal: d[e] }; | ||
@@ -555,48 +537,41 @@ } | ||
switch (e) { | ||
case a.Bitcoin: | ||
case a.BitcoinCash: | ||
case a.Dogecoin: | ||
case a.Litecoin: | ||
case a.Maya: | ||
case a.THORChain: | ||
case a.Polkadot: | ||
case a.Chainflip: | ||
case l.Cosmos: | ||
return t === "ATOM" ? "Native" : l.Cosmos; | ||
case l.Kujira: | ||
return t === l.Kujira ? "Native" : l.Kujira; | ||
case l.Binance: | ||
return t === l.Binance ? "Native" : "BEP2"; | ||
case l.BinanceSmartChain: | ||
return t === l.Binance ? "Native" : "BEP20"; | ||
case l.Ethereum: | ||
return t === l.Ethereum ? "Native" : "ERC20"; | ||
case l.Avalanche: | ||
return t === l.Avalanche ? "Native" : l.Avalanche; | ||
case l.Polygon: | ||
return t === l.Polygon ? "Native" : "POLYGON"; | ||
case l.Arbitrum: | ||
return [l.Ethereum, l.Arbitrum].includes(t) ? "Native" : "ARBITRUM"; | ||
case l.Optimism: | ||
return [l.Ethereum, l.Optimism].includes(t) ? "Native" : "OPTIMISM"; | ||
default: | ||
return "Native"; | ||
case a.Cosmos: | ||
return t === "ATOM" ? "Native" : a.Cosmos; | ||
case a.Kujira: | ||
return t === a.Kujira ? "Native" : a.Kujira; | ||
case a.Binance: | ||
return t === a.Binance ? "Native" : "BEP2"; | ||
case a.BinanceSmartChain: | ||
return t === a.Binance ? "Native" : "BEP20"; | ||
case a.Ethereum: | ||
return t === a.Ethereum ? "Native" : "ERC20"; | ||
case a.Avalanche: | ||
return t === a.Avalanche ? "Native" : a.Avalanche; | ||
case a.Polygon: | ||
return t === a.Polygon ? "Native" : "POLYGON"; | ||
case a.Arbitrum: | ||
return [a.Ethereum, a.Arbitrum].includes(t) ? "Native" : "ARBITRUM"; | ||
case a.Optimism: | ||
return [a.Ethereum, a.Optimism].includes(t) ? "Native" : "OPTIMISM"; | ||
} | ||
}, It = (e) => { | ||
}, Ct = (e) => { | ||
var o; | ||
const [t, ...n] = e.split("."), s = e.includes("/"), r = n.join("."), i = (o = r == null ? void 0 : r.split("-")) == null ? void 0 : o[0]; | ||
return { chain: t, symbol: r, ticker: i, synth: s }; | ||
}, ct = new RegExp( | ||
const [t, ...n] = e.split("."), r = e.includes("/"), s = n.join("."), i = (o = s == null ? void 0 : s.split("-")) == null ? void 0 : o[0]; | ||
return { chain: t, symbol: s, ticker: i, synth: r }; | ||
}, at = new RegExp( | ||
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/, | ||
"gmi" | ||
), lt = (e) => { | ||
), ct = (e) => { | ||
const [t, n] = e.split("."); | ||
if (!Be.includes(t)) | ||
if (!Ne.includes(t)) | ||
return !0; | ||
const [, s] = n.split("-"); | ||
return fe({ chain: t, symbol: n }) || !!s; | ||
}, ft = (e) => e.filter((t) => { | ||
const n = `${t.chain}.${t.symbol}`; | ||
return !ct.test(n) && lt(n) && t.value !== "0"; | ||
const [, r] = n.split("-"); | ||
return Se({ chain: t, symbol: n }) || !!r; | ||
}, St = (e) => e.filter(({ chain: t, value: n, symbol: r }) => { | ||
const s = `${t}.${r}`; | ||
return !at.test(s) && ct(s) && n !== "0"; | ||
}); | ||
function ut({ | ||
function lt({ | ||
liquidityUnits: e, | ||
@@ -606,6 +581,6 @@ poolUnits: t, | ||
}) { | ||
const s = A(e), r = A(t), i = A(n), o = s.mul(i), l = r.mul(r).mul(2), c = r.mul(s).mul(2), _ = s.mul(s), h = r.mul(r).mul(r); | ||
return o.mul(l.sub(c).add(_)).div(h); | ||
const r = m(e), s = m(t), i = m(n), o = r.mul(i), c = s.mul(s).mul(2), a = s.mul(r).mul(2), u = r.mul(r), h = s.mul(s).mul(s); | ||
return o.mul(c.sub(a).add(u)).div(h); | ||
} | ||
function _t({ | ||
function ut({ | ||
liquidityUnits: e, | ||
@@ -615,23 +590,23 @@ poolUnits: t, | ||
}) { | ||
const s = A(e), r = A(t), i = A(n), o = s.mul(i), l = r.mul(r).mul(2), c = r.mul(s).mul(2), _ = s.mul(s), h = o.mul(l.sub(c).add(_)), P = r.mul(r).mul(r); | ||
return h.div(P); | ||
const r = m(e), s = m(t), i = m(n), o = r.mul(i), c = s.mul(s).mul(2), a = s.mul(r).mul(2), u = r.mul(r), h = o.mul(c.sub(a).add(u)), $ = s.mul(s).mul(s); | ||
return h.div($); | ||
} | ||
function Ct({ | ||
function bt({ | ||
percent: e, | ||
runeDepth: t, | ||
liquidityUnits: n, | ||
poolUnits: s | ||
poolUnits: r | ||
}) { | ||
return ut({ runeDepth: t, liquidityUnits: n, poolUnits: s }).mul(e); | ||
return lt({ runeDepth: t, liquidityUnits: n, poolUnits: r }).mul(e); | ||
} | ||
function Nt({ | ||
function yt({ | ||
percent: e, | ||
assetDepth: t, | ||
liquidityUnits: n, | ||
poolUnits: s | ||
poolUnits: r | ||
}) { | ||
return _t({ assetDepth: t, liquidityUnits: n, poolUnits: s }).mul(e); | ||
return ut({ assetDepth: t, liquidityUnits: n, poolUnits: r }).mul(e); | ||
} | ||
function A(e) { | ||
return I.fromBigInt(BigInt(e), d.THOR); | ||
function m(e) { | ||
return g.fromBigInt(BigInt(e), d.THOR); | ||
} | ||
@@ -642,85 +617,85 @@ function ht({ | ||
runeDepth: n, | ||
assetDepth: s | ||
assetDepth: r | ||
}) { | ||
return { | ||
assetAmount: A(s).mul(e).div(t), | ||
runeAmount: A(n).mul(e).div(t) | ||
assetAmount: m(r).mul(e).div(t), | ||
runeAmount: m(n).mul(e).div(t) | ||
}; | ||
} | ||
function gt({ | ||
function wt({ | ||
liquidityUnits: e, | ||
poolUnits: t, | ||
runeDepth: n, | ||
assetDepth: s, | ||
percent: r | ||
assetDepth: r, | ||
percent: s | ||
}) { | ||
return Object.fromEntries( | ||
Object.entries(ht({ liquidityUnits: e, poolUnits: t, runeDepth: n, assetDepth: s })).map( | ||
([i, o]) => [i, o.mul(r)] | ||
Object.entries(ht({ liquidityUnits: e, poolUnits: t, runeDepth: n, assetDepth: r })).map( | ||
([i, o]) => [i, o.mul(s)] | ||
) | ||
); | ||
} | ||
function Ot({ | ||
function Rt({ | ||
runeDepth: e, | ||
poolUnits: t, | ||
assetDepth: n, | ||
liquidityUnits: s, | ||
runeAmount: r, | ||
liquidityUnits: r, | ||
runeAmount: s, | ||
assetAmount: i | ||
}) { | ||
const o = new I({ value: e, decimal: 8 }), l = new I({ value: n, decimal: 8 }), c = new I({ value: t, decimal: 8 }), _ = new I({ value: r, decimal: 8 }), h = new I({ value: i, decimal: 8 }), P = _.mul(l), ie = h.mul(o), ge = _.mul(h), Oe = o.mul(l), De = c.mul(P.add(ie.add(ge.mul(2)))), Pe = P.add(ie.add(Oe.mul(2))), ae = De.div(Pe), X = A(s).add(ae); | ||
if (ae.getBaseValue("number") === 0) | ||
return X.div(c).getBaseValue("number"); | ||
const be = c.add(X); | ||
return X.div(be).getBaseValue("number"); | ||
const o = new g({ value: e, decimal: 8 }), c = new g({ value: n, decimal: 8 }), a = new g({ value: t, decimal: 8 }), u = new g({ value: s, decimal: 8 }), h = new g({ value: i, decimal: 8 }), $ = u.mul(c), ie = h.mul(o), we = u.mul(h), Re = o.mul(c), Ee = a.mul($.add(ie.add(we.mul(2)))), Pe = $.add(ie.add(Re.mul(2))), oe = Ee.div(Pe), X = m(r).add(oe); | ||
if (oe.getBaseValue("number") === 0) | ||
return X.div(a).getBaseValue("number"); | ||
const Oe = a.add(X); | ||
return X.div(Oe).getBaseValue("number"); | ||
} | ||
function Dt({ | ||
function Et({ | ||
runeAmount: e, | ||
assetAmount: t, | ||
runeDepth: n, | ||
assetDepth: s | ||
assetDepth: r | ||
}) { | ||
if (e === "0" || t === "0" || n === "0" || s === "0") | ||
if (e === "0" || t === "0" || n === "0" || r === "0") | ||
return 0; | ||
const r = A(n), i = A(s), o = A(t), l = A(e), c = o.mul(r).sub(i.mul(l)), _ = i.mul(l).add(r.mul(i)); | ||
return Math.abs(c.div(_).getBaseValue("number")); | ||
const s = m(n), i = m(r), o = m(t), c = m(e), a = o.mul(s).sub(i.mul(c)), u = i.mul(c).add(s.mul(i)); | ||
return Math.abs(a.div(u).getBaseValue("number")); | ||
} | ||
const Pt = (e, t) => { | ||
switch (e) { | ||
case E.LEAVE: | ||
case E.BOND: { | ||
case C.LEAVE: | ||
case C.BOND: { | ||
const { address: n } = t; | ||
return `${e}:${n}`; | ||
} | ||
case E.UNBOND: { | ||
const { address: n, unbondAmount: s } = t; | ||
return `${e}:${n}:${s}`; | ||
case C.UNBOND: { | ||
const { address: n, unbondAmount: r } = t; | ||
return `${e}:${n}:${r}`; | ||
} | ||
case E.THORNAME_REGISTER: { | ||
const { name: n, chain: s, address: r, owner: i } = t; | ||
return `${e}:${n}:${s}:${r}${i ? `:${i}` : ""}`; | ||
case C.THORNAME_REGISTER: { | ||
const { name: n, chain: r, address: s, owner: i } = t; | ||
return `${e}:${n}:${r}:${s}${i ? `:${i}` : ""}`; | ||
} | ||
case E.DEPOSIT: { | ||
const { chain: n, symbol: s, address: r, singleSide: i } = t; | ||
return i ? `${e}:${n}/${s}::t:0` : `${e}:${((l, c) => { | ||
switch (l) { | ||
case a.Litecoin: | ||
case C.DEPOSIT: { | ||
const { chain: n, symbol: r, address: s, singleSide: i } = t; | ||
return i ? `${e}:${n}/${r}` : `${e}:${((c, a) => { | ||
switch (c) { | ||
case l.Litecoin: | ||
return "l"; | ||
case a.Dogecoin: | ||
case l.Dogecoin: | ||
return "d"; | ||
case a.BitcoinCash: | ||
case l.BitcoinCash: | ||
return "c"; | ||
default: | ||
return `${l}.${c}`; | ||
return `${c}.${a}`; | ||
} | ||
})(n, s)}:${r || ""}:t:0`; | ||
})(n, r)}:${s || ""}`; | ||
} | ||
case E.WITHDRAW: { | ||
const { chain: n, ticker: s, symbol: r, basisPoints: i, targetAssetString: o, singleSide: l } = t, c = n === "ETH" && s !== "ETH" ? `${s}-${r.slice(-3)}` : r, _ = !l && o ? `:${o}` : ""; | ||
return `${e}:${n}${l ? "/" : "."}${c}:${i}${_}`; | ||
case C.WITHDRAW: { | ||
const { chain: n, ticker: r, symbol: s, basisPoints: i, targetAssetString: o, singleSide: c } = t, a = n === "ETH" && r !== "ETH" ? `${r}-${s.slice(-3)}` : s, u = !c && o ? `:${o}` : ""; | ||
return `${e}:${n}${c ? "/" : "."}${a}:${i}${u}`; | ||
} | ||
case E.OPEN_LOAN: | ||
case E.CLOSE_LOAN: { | ||
const { asset: n, address: s } = t; | ||
return `${e}:${n}:${s}`; | ||
case C.OPEN_LOAN: | ||
case C.CLOSE_LOAN: { | ||
const { asset: n, address: r } = t; | ||
return `${e}:${n}:${r}`; | ||
} | ||
@@ -731,3 +706,3 @@ default: | ||
}; | ||
function bt(e) { | ||
function Ot(e) { | ||
if (e < 0) | ||
@@ -737,3 +712,3 @@ throw new Error("Invalid number of year"); | ||
} | ||
function yt(e) { | ||
function $t(e) { | ||
if (e.length > 30) | ||
@@ -744,6 +719,6 @@ return !1; | ||
} | ||
function wt([e, t, n, s, r]) { | ||
return `${e}'/${t}'/${n}'/${s}${typeof r != "number" ? "" : `/${r}`}`; | ||
function vt([e, t, n, r, s]) { | ||
return `${e}'/${t}'/${n}'/${r}${typeof s != "number" ? "" : `/${s}`}`; | ||
} | ||
const ue = [...Object.values(a), "TERRA"]; | ||
const ue = [...Object.values(l), "TERRA"]; | ||
function dt(e = "") { | ||
@@ -753,4 +728,4 @@ const t = e.toUpperCase(), [n] = t.split("."); | ||
return !0; | ||
const [s] = t.split("/"); | ||
if (ue.includes(s)) | ||
const [r] = t.split("/"); | ||
if (ue.includes(r)) | ||
return !0; | ||
@@ -761,4 +736,4 @@ throw new Error( | ||
} | ||
const B = 8, C = (e) => 10n ** BigInt(e), b = (e) => Math.log10(parseFloat(e.toString())); | ||
function G({ | ||
const B = 8, y = (e) => 10n ** BigInt(e), v = (e) => Math.log10(parseFloat(e.toString())); | ||
function U({ | ||
value: e, | ||
@@ -770,9 +745,9 @@ bigIntDecimal: t = B, | ||
return e.toString(); | ||
const s = e < 0n; | ||
let r = e.toString().substring(s ? 1 : 0); | ||
const i = n - (r.length - 1); | ||
i > 0 && (r = "0".repeat(i) + r); | ||
const o = r.length - n; | ||
let l = r.slice(-n); | ||
return parseInt(l[t]) >= 5 ? l = `${l.substring(0, t - 1)}${(parseInt(l[t - 1]) + 1).toString()}` : l = l.substring(0, t), `${s ? "-" : ""}${r.slice(0, o)}.${l}`.replace( | ||
const r = e < 0n; | ||
let s = e.toString().substring(r ? 1 : 0); | ||
const i = n - (s.length - 1); | ||
i > 0 && (s = "0".repeat(i) + s); | ||
const o = s.length - n; | ||
let c = s.slice(-n); | ||
return parseInt(c[t]) >= 5 ? c = `${c.substring(0, t - 1)}${(parseInt(c[t - 1]) + 1).toString()}` : c = c.substring(0, t), `${r ? "-" : ""}${s.slice(0, o)}.${c}`.replace( | ||
/\.?0*$/, | ||
@@ -782,20 +757,20 @@ "" | ||
} | ||
var N, y, f, D, k, Ce, L, z, U, Z; | ||
const re = class re { | ||
var w, I, b, E, j, be, V, Z, H, ee; | ||
const q = class q { | ||
constructor(t) { | ||
O(this, N); | ||
O(this, f); | ||
O(this, k); | ||
O(this, L); | ||
O(this, U); | ||
p(this, "decimalMultiplier", 10n ** 8n); | ||
p(this, "bigIntValue", 0n); | ||
p(this, "decimal"); | ||
const n = ee(t), s = typeof t == "object"; | ||
this.decimal = s ? t.decimal : void 0, this.decimalMultiplier = s && "decimalMultiplier" in t ? t.decimalMultiplier : C(Math.max(_e($(n)), this.decimal || 0)), T(this, k, Ce).call(this, n); | ||
R(this, w); | ||
R(this, b); | ||
R(this, j); | ||
R(this, V); | ||
R(this, H); | ||
_(this, "decimalMultiplier", 10n ** 8n); | ||
_(this, "bigIntValue", 0n); | ||
_(this, "decimal"); | ||
const n = te(t), r = typeof t == "object"; | ||
this.decimal = r ? t.decimal : void 0, this.decimalMultiplier = r && "decimalMultiplier" in t ? t.decimalMultiplier : y(Math.max(he(M(n)), this.decimal || 0)), p(this, j, be).call(this, n); | ||
} | ||
static fromBigInt(t, n) { | ||
return new re({ | ||
return new q({ | ||
decimal: n, | ||
value: G({ value: t, bigIntDecimal: n, decimal: n }) | ||
value: U({ value: t, bigIntDecimal: n, decimal: n }) | ||
}); | ||
@@ -806,7 +781,7 @@ } | ||
from: n, | ||
to: s | ||
to: r | ||
}) { | ||
return this.fromBigInt( | ||
t.getBaseValue("bigint") * C(s) / C(n), | ||
s | ||
return q.fromBigInt( | ||
t.getBaseValue("bigint") * y(r) / y(n), | ||
r | ||
); | ||
@@ -818,27 +793,27 @@ } | ||
add(...t) { | ||
return T(this, N, y).call(this, "add", ...t); | ||
return p(this, w, I).call(this, "add", ...t); | ||
} | ||
sub(...t) { | ||
return T(this, N, y).call(this, "sub", ...t); | ||
return p(this, w, I).call(this, "sub", ...t); | ||
} | ||
mul(...t) { | ||
return T(this, N, y).call(this, "mul", ...t); | ||
return p(this, w, I).call(this, "mul", ...t); | ||
} | ||
div(...t) { | ||
return T(this, N, y).call(this, "div", ...t); | ||
return p(this, w, I).call(this, "div", ...t); | ||
} | ||
gt(t) { | ||
return T(this, f, D).call(this, "gt", t); | ||
return p(this, b, E).call(this, "gt", t); | ||
} | ||
gte(t) { | ||
return T(this, f, D).call(this, "gte", t); | ||
return p(this, b, E).call(this, "gte", t); | ||
} | ||
lt(t) { | ||
return T(this, f, D).call(this, "lt", t); | ||
return p(this, b, E).call(this, "lt", t); | ||
} | ||
lte(t) { | ||
return T(this, f, D).call(this, "lte", t); | ||
return p(this, b, E).call(this, "lte", t); | ||
} | ||
eqValue(t) { | ||
return T(this, f, D).call(this, "eqValue", t); | ||
return p(this, b, E).call(this, "eqValue", t); | ||
} | ||
@@ -849,3 +824,3 @@ // @ts-expect-error False positive | ||
this.bigIntValue, | ||
this.decimal || b(this.decimalMultiplier) | ||
this.decimal || v(this.decimalMultiplier) | ||
); | ||
@@ -863,10 +838,10 @@ switch (t) { | ||
getBaseValue(t) { | ||
const n = this.decimalMultiplier / C(this.decimal || d.THOR), s = this.bigIntValue / n; | ||
const n = this.decimalMultiplier / y(this.decimal || d.THOR), r = this.bigIntValue / n; | ||
switch (t) { | ||
case "number": | ||
return Number(s); | ||
return Number(r); | ||
case "string": | ||
return s.toString(); | ||
return r.toString(); | ||
case "bigint": | ||
return s; | ||
return r; | ||
} | ||
@@ -877,19 +852,19 @@ } | ||
return t.bigIntValue; | ||
const s = ee(t), r = $(s); | ||
return r === "0" || r === "undefined" ? 0n : T(this, U, Z).call(this, r, n); | ||
const r = te(t), s = M(r); | ||
return s === "0" || s === "undefined" ? 0n : p(this, H, ee).call(this, s, n); | ||
} | ||
toSignificant(t = 6) { | ||
const [n, s] = this.getValue("string").split("."), r = n || "", i = s || ""; | ||
if ((parseInt(r) ? r.length + i.length : i.length) <= t) | ||
const [n, r] = this.getValue("string").split("."), s = n || "", i = r || ""; | ||
if ((parseInt(s) ? s.length + i.length : i.length) <= t) | ||
return this.getValue("string"); | ||
if (r.length >= t) | ||
return r.slice(0, t).padEnd(r.length, "0"); | ||
if (parseInt(r)) | ||
return `${r}.${i.slice(0, t - r.length)}`.padEnd( | ||
t - r.length, | ||
if (s.length >= t) | ||
return s.slice(0, t).padEnd(s.length, "0"); | ||
if (parseInt(s)) | ||
return `${s}.${i.slice(0, t - s.length)}`.padEnd( | ||
t - s.length, | ||
"0" | ||
); | ||
const l = parseInt(i), c = `${l}`.slice(0, t); | ||
return `0.${c.padStart( | ||
i.length - `${l}`.length + c.length, | ||
const c = parseInt(i), a = `${c}`.slice(0, t); | ||
return `0.${a.padStart( | ||
i.length - `${c}`.length + a.length, | ||
"0" | ||
@@ -899,8 +874,8 @@ )}`; | ||
toFixed(t = 6) { | ||
const [n, s] = this.getValue("string").split("."), r = n || "", i = s || ""; | ||
if (parseInt(r)) | ||
return `${r}.${i.slice(0, t)}`.padEnd(t, "0"); | ||
const o = parseInt(i), l = `${o}`.slice(0, t); | ||
return `0.${l.padStart( | ||
i.length - `${o}`.length + l.length, | ||
const [n, r] = this.getValue("string").split("."), s = n || "", i = r || ""; | ||
if (parseInt(s)) | ||
return `${s}.${i.slice(0, t)}`.padEnd(t, "0"); | ||
const o = parseInt(i), c = `${o}`.slice(0, t); | ||
return `0.${c.padStart( | ||
i.length - `${o}`.length + c.length, | ||
"0" | ||
@@ -910,6 +885,6 @@ )}`; | ||
toAbbreviation(t = 2) { | ||
const n = this.getValue("number"), s = ["", "K", "M", "B", "T", "Q", "Qi", "S"], r = Math.floor(Math.log10(Math.abs(n)) / 3), i = s[r]; | ||
const n = this.getValue("number"), r = ["", "K", "M", "B", "T", "Q", "Qi", "S"], s = Math.floor(Math.log10(Math.abs(n)) / 3), i = r[s]; | ||
if (!i) | ||
return this.getValue("string"); | ||
const o = 10 ** (r * 3); | ||
const o = 10 ** (s * 3); | ||
return `${(n / o).toFixed(t)}${i}`; | ||
@@ -919,39 +894,39 @@ } | ||
currencyPosition: n = "start", | ||
decimal: s = 2, | ||
decimalSeparator: r = ".", | ||
decimal: r = 2, | ||
decimalSeparator: s = ".", | ||
thousandSeparator: i = "," | ||
} = {}) { | ||
const o = this.getValue("number"), [l, c = ""] = o.toFixed(6).split("."), _ = l.replace(/\B(?=(\d{3})+(?!\d))/g, i), h = !l && !c ? "0.00" : l === "0" ? `${parseFloat(`0.${c}`)}`.replace(".", r) : `${_}${parseInt(c) ? `${r}${c.slice(0, s)}` : ""}`; | ||
const o = this.getValue("number"), [c, a = ""] = o.toFixed(6).split("."), u = c.replace(/\B(?=(\d{3})+(?!\d))/g, i), h = c || a ? c === "0" ? `${parseFloat(`0.${a}`)}`.replace(".", s) : `${u}${parseInt(a) ? `${s}${a.slice(0, r)}` : ""}` : "0.00"; | ||
return `${n === "start" ? t : ""}${h}${n === "end" ? t : ""}`; | ||
} | ||
formatBigIntToSafeValue(t, n) { | ||
const s = n || this.decimal || B, r = Math.max( | ||
s, | ||
b(this.decimalMultiplier) | ||
), i = t < 0n, o = t.toString().substring(i ? 1 : 0), l = r - (o.length - 1), c = l > 0 ? "0".repeat(l) + o : o, _ = c.length - r; | ||
let h = c.slice(-r); | ||
return parseInt(h[s]) >= 5 ? h = `${h.substring(0, s - 1)}${(parseInt(h[s - 1]) + 1).toString()}` : h = h.substring(0, s), `${i ? "-" : ""}${c.slice( | ||
const r = n || this.decimal || B, s = Math.max( | ||
r, | ||
v(this.decimalMultiplier) | ||
), i = t < 0n, o = t.toString().substring(i ? 1 : 0), c = s - (o.length - 1), a = c > 0 ? "0".repeat(c) + o : o, u = a.length - s; | ||
let h = a.slice(-s); | ||
return parseInt(h[r]) >= 5 ? h = `${h.substring(0, r - 1)}${(parseInt(h[r - 1]) + 1).toString()}` : h = h.substring(0, r), `${i ? "-" : ""}${a.slice( | ||
0, | ||
_ | ||
u | ||
)}.${h}`.replace(/\.?0*$/, ""); | ||
} | ||
}; | ||
N = new WeakSet(), y = function(t, ...n) { | ||
const s = T(this, L, z).call(this, this, ...n), r = Math.max(s, b(this.decimalMultiplier)), i = C(r), o = n.reduce( | ||
(c, _) => { | ||
const h = this.getBigIntValue(_, r); | ||
w = new WeakSet(), I = function(t, ...n) { | ||
const r = p(this, V, Z).call(this, this, ...n), s = Math.max(r, v(this.decimalMultiplier)), i = y(s), o = n.reduce( | ||
(a, u) => { | ||
const h = this.getBigIntValue(u, s); | ||
switch (t) { | ||
case "add": | ||
return c + h; | ||
return a + h; | ||
case "sub": | ||
return c - h; | ||
return a - h; | ||
case "mul": | ||
return c * h / i; | ||
return a * h / i; | ||
case "div": { | ||
if (h === 0n) | ||
throw new RangeError("Division by zero"); | ||
return c * i / h; | ||
return a * i / h; | ||
} | ||
default: | ||
return c; | ||
return a; | ||
} | ||
@@ -961,47 +936,47 @@ }, | ||
this.bigIntValue * i / this.decimalMultiplier | ||
), l = G({ | ||
bigIntDecimal: r, | ||
decimal: r, | ||
), c = U({ | ||
bigIntDecimal: s, | ||
decimal: s, | ||
value: o | ||
}); | ||
return new this.constructor({ | ||
decimalMultiplier: C(r), | ||
decimalMultiplier: y(s), | ||
decimal: this.decimal, | ||
value: l, | ||
value: c, | ||
identifier: this.toString() | ||
}); | ||
}, f = new WeakSet(), D = function(t, ...n) { | ||
const s = T(this, L, z).call(this, this, ...n), r = this.getBigIntValue(n[0], s), i = this.getBigIntValue(this, s); | ||
}, b = new WeakSet(), E = function(t, ...n) { | ||
const r = p(this, V, Z).call(this, this, ...n), s = this.getBigIntValue(n[0], r), i = this.getBigIntValue(this, r); | ||
switch (t) { | ||
case "gt": | ||
return i > r; | ||
return i > s; | ||
case "gte": | ||
return i >= r; | ||
return i >= s; | ||
case "lt": | ||
return i < r; | ||
return i < s; | ||
case "lte": | ||
return i <= r; | ||
return i <= s; | ||
case "eqValue": | ||
return i === r; | ||
return i === s; | ||
} | ||
}, k = new WeakSet(), Ce = function(t) { | ||
const n = $(t) || "0"; | ||
this.bigIntValue = T(this, U, Z).call(this, n); | ||
}, L = new WeakSet(), z = function(...t) { | ||
const n = t.map((s) => typeof s == "object" ? s.decimal || b(s.decimalMultiplier) : _e($(s))).filter(Boolean); | ||
}, j = new WeakSet(), be = function(t) { | ||
const n = M(t) || "0"; | ||
this.bigIntValue = p(this, H, ee).call(this, n); | ||
}, V = new WeakSet(), Z = function(...t) { | ||
const n = t.map((r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : he(M(r))).filter(Boolean); | ||
return Math.max(...n, B); | ||
}, U = new WeakSet(), Z = function(t, n) { | ||
const s = n ? C(n) : this.decimalMultiplier, r = b(s), [i = "", o = ""] = t.split("."); | ||
return BigInt(`${i}${o.padEnd(r, "0")}`); | ||
}, H = new WeakSet(), ee = function(t, n) { | ||
const r = n ? y(n) : this.decimalMultiplier, s = v(r), [i = "", o = ""] = t.split("."); | ||
return BigInt(`${i}${o.padEnd(s, "0")}`); | ||
}; | ||
let W = re; | ||
const Tt = Intl.NumberFormat("fullwide", { | ||
let D = q; | ||
const pt = Intl.NumberFormat("fullwide", { | ||
useGrouping: !1, | ||
maximumFractionDigits: 20 | ||
}); | ||
function $(e) { | ||
const n = `${typeof e == "number" ? Tt.format(e) : ee(e)}`.replaceAll(",", ".").split("."); | ||
function M(e) { | ||
const n = `${typeof e == "number" ? pt.format(e) : te(e)}`.replaceAll(",", ".").split("."); | ||
return n.length > 1 ? `${n.slice(0, -1).join("")}.${n.at(-1)}` : n[0]; | ||
} | ||
function _e(e) { | ||
function he(e) { | ||
var n; | ||
@@ -1011,26 +986,37 @@ const t = ((n = e.split(".")[1]) == null ? void 0 : n.length) || 0; | ||
} | ||
function ee(e) { | ||
function te(e) { | ||
return typeof e == "object" ? "getValue" in e ? e.getValue("string") : e.value : e; | ||
} | ||
const w = /* @__PURE__ */ new Map(); | ||
class g extends W { | ||
class g extends D { | ||
eq(t) { | ||
return this.eqValue(t); | ||
} | ||
static fromBigInt(t, n) { | ||
return new g({ | ||
decimal: n, | ||
value: U({ value: t, bigIntDecimal: n, decimal: n }) | ||
}); | ||
} | ||
} | ||
const P = /* @__PURE__ */ new Map(); | ||
class A extends D { | ||
constructor({ | ||
value: n, | ||
decimal: s, | ||
tax: r, | ||
decimal: r, | ||
tax: s, | ||
chain: i, | ||
symbol: o, | ||
identifier: l | ||
identifier: c | ||
}) { | ||
super(typeof n == "object" ? n : { decimal: s, value: n }); | ||
p(this, "address"); | ||
p(this, "chain"); | ||
p(this, "isGasAsset", !1); | ||
p(this, "isSynthetic", !1); | ||
p(this, "symbol"); | ||
p(this, "tax"); | ||
p(this, "ticker"); | ||
p(this, "type"); | ||
const c = F(l || `${i}.${o}`); | ||
this.type = ot(c), this.tax = r, this.chain = c.chain, this.ticker = c.ticker, this.symbol = c.symbol, this.address = c.address, this.isSynthetic = c.isSynthetic, this.isGasAsset = c.isGasAsset; | ||
super(typeof n == "object" ? n : { decimal: r, value: n }); | ||
_(this, "address"); | ||
_(this, "chain"); | ||
_(this, "isGasAsset", !1); | ||
_(this, "isSynthetic", !1); | ||
_(this, "symbol"); | ||
_(this, "tax"); | ||
_(this, "ticker"); | ||
_(this, "type"); | ||
const a = N(c || `${i}.${o}`); | ||
this.type = ot(a), this.tax = s, this.chain = a.chain, this.ticker = a.ticker, this.symbol = a.symbol, this.address = a.address, this.isSynthetic = a.isSynthetic, this.isGasAsset = a.isGasAsset; | ||
} | ||
@@ -1043,7 +1029,7 @@ toString() { | ||
} | ||
eq({ chain: n, symbol: s }) { | ||
return this.chain === n && this.symbol === s; | ||
eq({ chain: n, symbol: r }) { | ||
return this.chain === n && this.symbol === r; | ||
} | ||
chainId() { | ||
return Ue[this.chain]; | ||
return De[this.chain]; | ||
} | ||
@@ -1053,62 +1039,84 @@ // THOR.RUNE | ||
// ETH.THOR-0x1234567890 | ||
static fromUrl(n, s = 0) { | ||
const [r, i, o] = n.split("."); | ||
if (!r || !i) | ||
static fromUrl(n, r = 0) { | ||
const [s, i, o] = n.split("."); | ||
if (!(s && i)) | ||
throw new Error("Invalid asset url"); | ||
const l = r === a.THORChain && o ? `${r}.${i}/${o}` : n; | ||
return J(l, s); | ||
const c = s === l.THORChain && o ? `${s}.${i}/${o}` : n; | ||
return Y(c, r); | ||
} | ||
static fromString(n, s = 0) { | ||
return J(n, s); | ||
static fromString(n, r = 0) { | ||
return Y(n, r); | ||
} | ||
static fromIdentifier(n, s = 0) { | ||
return J(n, s); | ||
static fromIdentifier(n, r = 0) { | ||
return Y(n, r); | ||
} | ||
static fromStringSync(n, s = 0) { | ||
const { chain: r, isSynthetic: i } = F(n), o = w.get(n.toUpperCase()); | ||
static fromStringSync(n, r = 0) { | ||
const { chain: s, isSynthetic: i } = N(n), o = P.get(n.toUpperCase()); | ||
if (i) | ||
return he(n, s); | ||
const { tax: l, decimal: c, identifier: _ } = o || { | ||
decimal: d[r], | ||
return Q(n, r); | ||
const { tax: c, decimal: a, identifier: u } = o || { | ||
decimal: d[s], | ||
identifier: n | ||
}; | ||
return new g({ | ||
tax: l, | ||
value: V(s, c), | ||
identifier: i ? n : _, | ||
decimal: i ? 8 : c | ||
return new A({ | ||
tax: c, | ||
value: O(r, a), | ||
identifier: i ? n : u, | ||
decimal: i ? 8 : a | ||
}); | ||
} | ||
static fromIdentifierSync(n, s = 0) { | ||
const { chain: r, isSynthetic: i } = F(n), o = w.get(n); | ||
static async fromStringWithBase(n, r = 0, s = d.THOR) { | ||
const i = D.shiftDecimals({ | ||
value: g.fromBigInt(BigInt(r)), | ||
from: 0, | ||
to: s | ||
}).getBaseValue("string"); | ||
return (await A.fromString(n, r)).set(i); | ||
} | ||
static fromStringWithBaseSync(n, r = 0, s = d.THOR) { | ||
const { chain: i, isSynthetic: o } = N(n), c = P.get(n.toUpperCase()); | ||
if (o) | ||
return Q(n, r); | ||
const { tax: a, decimal: u, identifier: h } = c || { | ||
decimal: d[i], | ||
identifier: n | ||
}; | ||
return new A({ | ||
tax: a, | ||
value: O(BigInt(r), s), | ||
identifier: h, | ||
decimal: u | ||
}); | ||
} | ||
static fromIdentifierSync(n, r = 0) { | ||
const { chain: s, isSynthetic: i } = N(n), o = P.get(n); | ||
if (i) | ||
return he(n, s); | ||
const { tax: l, decimal: c, identifier: _ } = o || { | ||
decimal: d[r], | ||
return Q(n, r); | ||
const { tax: c, decimal: a, identifier: u } = o || { | ||
decimal: d[s], | ||
identifier: n | ||
}; | ||
return new g({ tax: l, decimal: c, identifier: _, value: V(s, c) }); | ||
return new A({ tax: c, decimal: a, identifier: u, value: O(r, a) }); | ||
} | ||
static fromChainOrSignature(n, s = 0) { | ||
const { decimal: r, identifier: i } = at(n); | ||
return new g({ value: V(s, r), decimal: r, identifier: i }); | ||
static fromChainOrSignature(n, r = 0) { | ||
const { decimal: s, identifier: i } = it(n); | ||
return new A({ value: O(r, s), decimal: s, identifier: i }); | ||
} | ||
static loadStaticAssets() { | ||
return new Promise( | ||
async (n, s) => { | ||
(n, r) => { | ||
try { | ||
const r = await import("@swapkit/tokens"); | ||
Object.values(r).forEach((i) => { | ||
var o; | ||
(o = i == null ? void 0 : i.tokens) == null || o.forEach(({ identifier: l, chain: c, ..._ }) => { | ||
w.set(l.toUpperCase(), { | ||
identifier: l, | ||
decimal: "decimals" in _ ? _.decimals : d[c] | ||
}); | ||
}); | ||
}), n({ ok: !0 }); | ||
} catch (r) { | ||
console.error(r), s({ | ||
import("@swapkit/tokens").then((s) => { | ||
for (const i of Object.values(s)) | ||
for (const { identifier: o, chain: c, ...a } of i.tokens) | ||
P.set(o.toUpperCase(), { | ||
identifier: o, | ||
decimal: "decimals" in a ? a.decimals : d[c] | ||
}); | ||
n({ ok: !0 }); | ||
}); | ||
} catch (s) { | ||
console.error(s), r({ | ||
ok: !1, | ||
error: r, | ||
error: s, | ||
message: "Couldn't load static assets. Ensure you have installed @swapkit/tokens package" | ||
@@ -1121,18 +1129,18 @@ }); | ||
} | ||
function Vt(e) { | ||
const t = g.fromChainOrSignature(e); | ||
function It(e) { | ||
const t = A.fromChainOrSignature(e); | ||
switch (e) { | ||
case a.Bitcoin: | ||
case a.Litecoin: | ||
case a.BitcoinCash: | ||
case l.Bitcoin: | ||
case l.Litecoin: | ||
case l.BitcoinCash: | ||
return t.set(10001e-8); | ||
case a.Dogecoin: | ||
case l.Dogecoin: | ||
return t.set(1.00000001); | ||
case a.Avalanche: | ||
case a.Ethereum: | ||
case l.Avalanche: | ||
case l.Ethereum: | ||
return t.set(1e-8); | ||
case a.THORChain: | ||
case a.Maya: | ||
case l.THORChain: | ||
case l.Maya: | ||
return t.set(0); | ||
case a.Cosmos: | ||
case l.Cosmos: | ||
return t.set(1e-6); | ||
@@ -1143,35 +1151,35 @@ default: | ||
} | ||
async function J(e, t = 0) { | ||
async function Y(e, t = 0) { | ||
dt(e); | ||
const n = w.get(e.toUpperCase()), s = (n == null ? void 0 : n.decimal) || await it(F(e)); | ||
return n || w.set(e.toUpperCase(), { identifier: e, decimal: s }), new g({ decimal: s, value: V(t, s), identifier: e }); | ||
const n = P.get(e.toUpperCase()), r = (n == null ? void 0 : n.decimal) || await st(N(e)); | ||
return n || P.set(e.toUpperCase(), { identifier: e, decimal: r }), new A({ decimal: r, value: O(t, r), identifier: e }); | ||
} | ||
function he(e, t = 0) { | ||
const [n, s] = e.split(".")[0].toUpperCase() === a.THORChain ? e.split(".").slice(1).join().split("/") : e.split("/"); | ||
if (!n || !s) | ||
function Q(e, t = 0) { | ||
const [n, r] = e.split(".")[0].toUpperCase() === l.THORChain ? e.split(".").slice(1).join().split("/") : e.split("/"); | ||
if (!(n && r)) | ||
throw new Error("Invalid asset identifier"); | ||
return new g({ | ||
return new A({ | ||
decimal: 8, | ||
value: V(t, 8), | ||
identifier: `${a.THORChain}.${n}/${s}` | ||
value: O(t, 8), | ||
identifier: `${l.THORChain}.${n}/${r}` | ||
}); | ||
} | ||
function V(e, t) { | ||
return typeof e == "bigint" ? G({ value: e, bigIntDecimal: t, decimal: t }) : e; | ||
function O(e, t) { | ||
return typeof e == "bigint" ? U({ value: e, bigIntDecimal: t, decimal: t }) : e; | ||
} | ||
function F(e) { | ||
const t = e.slice(0, 14).includes("/"), [n, s] = e.split(".")[0].toUpperCase() === a.THORChain ? e.split(".").slice(1).join().split("/") : e.split("/"); | ||
if (t && (!n || !s)) | ||
function N(e) { | ||
const t = e.slice(0, 14).includes("/"), [n, r] = e.split(".")[0].toUpperCase() === l.THORChain ? e.split(".").slice(1).join().split("/") : e.split("/"); | ||
if (t && !(n && r)) | ||
throw new Error("Invalid asset identifier"); | ||
const r = e.includes(".") && !t ? e : `${a.THORChain}.${s}`, [i, ...o] = r.split("."), [l, c] = (t ? s : o.join(".")).split("-"), _ = t ? s : o.join("."); | ||
const s = e.includes(".") && !t ? e : `${l.THORChain}.${r}`, [i, ...o] = s.split("."), [c, a] = (t ? r : o.join(".")).split("-"), u = t ? r : o.join("."); | ||
return { | ||
address: c == null ? void 0 : c.toLowerCase(), | ||
address: a == null ? void 0 : a.toLowerCase(), | ||
chain: i, | ||
isGasAsset: fe({ chain: i, symbol: _ }), | ||
isGasAsset: Se({ chain: i, symbol: u }), | ||
isSynthetic: t, | ||
symbol: (t ? `${n}/` : "") + (c ? `${l}-${(c == null ? void 0 : c.toLowerCase()) ?? ""}` : _), | ||
ticker: l | ||
symbol: (t ? `${n}/` : "") + (a ? `${c}-${(a == null ? void 0 : a.toLowerCase()) ?? ""}` : u), | ||
ticker: c | ||
}; | ||
} | ||
const At = { | ||
const mt = { | ||
/** | ||
@@ -1209,2 +1217,3 @@ * Core | ||
core_swap_quote_mode_not_supported: 10207, | ||
core_swap_provider_not_found: 10208, | ||
/** | ||
@@ -1237,2 +1246,9 @@ * Core - Transaction | ||
/** | ||
* Chainflip | ||
*/ | ||
chainflip_channel_error: 30001, | ||
/** | ||
* THORChain | ||
*/ | ||
/** | ||
* Helpers | ||
@@ -1242,53 +1258,47 @@ */ | ||
}; | ||
class Ne extends Error { | ||
class ye extends Error { | ||
constructor(t, n) { | ||
n && console.error(n, { stack: n == null ? void 0 : n.stack, message: n == null ? void 0 : n.message }), super(t, { cause: { code: At[t], message: t } }), Object.setPrototypeOf(this, Ne.prototype); | ||
n && console.error(n, { | ||
stack: n == null ? void 0 : n.stack, | ||
message: n == null ? void 0 : n.message | ||
}), super(t, { | ||
cause: { code: mt[t], message: t } | ||
}), Object.setPrototypeOf(this, ye.prototype); | ||
} | ||
} | ||
class I extends W { | ||
eq(t) { | ||
return this.eqValue(t); | ||
} | ||
static fromBigInt(t, n) { | ||
return new I({ | ||
decimal: n, | ||
value: G({ value: t, bigIntDecimal: n, decimal: n }) | ||
}); | ||
} | ||
} | ||
export { | ||
m as ApiEndpoints, | ||
g as AssetValue, | ||
W as BigIntArithmetics, | ||
S as RequestClient, | ||
et as StreamingSwapProgressStatus, | ||
Et as SwapKitApi, | ||
Ne as SwapKitError, | ||
I as SwapKitNumber, | ||
ze as TransactionType, | ||
Ze as TxStatus, | ||
It as assetFromString, | ||
Re as defaultRequestHeaders, | ||
wt as derivationPathToString, | ||
ft as filterAssets, | ||
G as formatBigIntToSafeValue, | ||
Rt as gasFeeMultiplier, | ||
f as ApiEndpoints, | ||
A as AssetValue, | ||
D as BigIntArithmetics, | ||
T as RequestClient, | ||
Ze as StreamingSwapProgressStatus, | ||
gt as SwapKitApi, | ||
ye as SwapKitError, | ||
g as SwapKitNumber, | ||
Qe as TransactionType, | ||
ze as TxStatus, | ||
Ct as assetFromString, | ||
Ae as defaultRequestHeaders, | ||
vt as derivationPathToString, | ||
St as filterAssets, | ||
U as formatBigIntToSafeValue, | ||
At as gasFeeMultiplier, | ||
ot as getAssetType, | ||
_t as getAsymmetricAssetShare, | ||
Nt as getAsymmetricAssetWithdrawAmount, | ||
ut as getAsymmetricRuneShare, | ||
Ct as getAsymmetricRuneWithdrawAmount, | ||
at as getCommonAssetInfo, | ||
it as getDecimal, | ||
Ot as getEstimatedPoolShare, | ||
Dt as getLiquiditySlippage, | ||
ut as getAsymmetricAssetShare, | ||
yt as getAsymmetricAssetWithdrawAmount, | ||
lt as getAsymmetricRuneShare, | ||
bt as getAsymmetricRuneWithdrawAmount, | ||
it as getCommonAssetInfo, | ||
st as getDecimal, | ||
Rt as getEstimatedPoolShare, | ||
Et as getLiquiditySlippage, | ||
Pt as getMemoFor, | ||
Vt as getMinAmountByChain, | ||
It as getMinAmountByChain, | ||
ht as getSymmetricPoolShare, | ||
gt as getSymmetricWithdraw, | ||
bt as getTHORNameCost, | ||
fe as isGasAsset, | ||
mt as setRequestClientConfig, | ||
yt as validateTHORName | ||
wt as getSymmetricWithdraw, | ||
Ot as getTHORNameCost, | ||
Se as isGasAsset, | ||
ft as setRequestClientConfig, | ||
$t as validateTHORName | ||
}; | ||
//# sourceMappingURL=index.es.js.map |
{ | ||
"author": "swapkit-oss-team", | ||
"author": "swapkit-oss", | ||
"description": "SwapKit Lib swapkit-helpers", | ||
"dependencies": { | ||
"@swapkit/api": "0.0.0-nightly-20240208140027" | ||
"@swapkit/api": "0.0.0-nightly-20240223171610" | ||
}, | ||
"devDependencies": { | ||
"@vitest/coverage-istanbul": "1.2.1", | ||
"vite": "5.0.12", | ||
"vitest": "1.2.1", | ||
"@internal/config": "0.0.0-nightly-20240208140027", | ||
"@swapkit/tokens": "0.0.0-nightly-20240208140027", | ||
"@swapkit/types": "0.0.0-nightly-20240208140027" | ||
"@vitest/coverage-istanbul": "1.3.1", | ||
"vite": "5.1.3", | ||
"vitest": "1.3.1", | ||
"@swapkit/tokens": "0.0.0-nightly-20240223171610", | ||
"@swapkit/types": "0.0.0-nightly-20240223171610" | ||
}, | ||
"eslintConfig": { | ||
"extends": "../../../internal/eslint-config" | ||
}, | ||
"peerDependencies": { | ||
"@swapkit/tokens": "0.0.0-nightly-20240208140027", | ||
"@swapkit/types": "0.0.0-nightly-20240208140027" | ||
"@swapkit/tokens": "0.0.0-nightly-20240223171610", | ||
"@swapkit/types": "0.0.0-nightly-20240223171610" | ||
}, | ||
@@ -45,7 +41,7 @@ "exports": { | ||
"types": "./dist/index.d.ts", | ||
"version": "0.0.0-nightly-20240208140027", | ||
"version": "0.0.0-nightly-20240223171610", | ||
"scripts": { | ||
"build": "vite build", | ||
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules", | ||
"lint": "eslint ./ --ext .ts,.tsx --fix; tsc --noEmit", | ||
"clean": "rm -rf dist vite.config.ts.* node_modules", | ||
"lint": "biome check --apply ./src", | ||
"test": "vitest --run", | ||
@@ -52,0 +48,0 @@ "test:coverage": "vitest run --coverage" |
@@ -1,64 +0,64 @@ | ||
import { BaseDecimal, Chain } from '@swapkit/types'; | ||
import { describe, expect, it } from 'vitest'; | ||
import { BaseDecimal, Chain } from "@swapkit/types"; | ||
import { describe, expect, test } from "vitest"; | ||
import { getAssetType, getDecimal } from '../asset.ts'; | ||
import { getAssetType, getDecimal } from "../asset.ts"; | ||
const tickerMap: Record<string, string> = { | ||
[Chain.THORChain]: 'RUNE', | ||
[Chain.Cosmos]: 'ATOM', | ||
[Chain.BinanceSmartChain]: 'BNB', | ||
[Chain.THORChain]: "RUNE", | ||
[Chain.Cosmos]: "ATOM", | ||
[Chain.BinanceSmartChain]: "BNB", | ||
}; | ||
describe('getAssetType', () => { | ||
describe('when isSynth is true', () => { | ||
it('should return "Synth"', () => { | ||
const result = getAssetType({ chain: Chain.Bitcoin, symbol: 'BTC/BTC' }); | ||
expect(result).toBe('Synth'); | ||
describe("getAssetType", () => { | ||
describe("when isSynth is true", () => { | ||
test('should return "Synth"', () => { | ||
const result = getAssetType({ chain: Chain.Bitcoin, symbol: "BTC/BTC" }); | ||
expect(result).toBe("Synth"); | ||
}); | ||
}); | ||
describe('when isSynth is false', () => { | ||
describe('for native chains and their assets', () => { | ||
Object.values(Chain).forEach((chain) => { | ||
it(`should return "Native" for chain ${chain} asset`, () => { | ||
describe("when isSynth is false", () => { | ||
describe("for native chains and their assets", () => { | ||
for (const chain of Object.values(Chain)) { | ||
test(`should return "Native" for chain ${chain} asset`, () => { | ||
const ticker = tickerMap[chain] || chain; | ||
const result = getAssetType({ chain: chain as Chain, symbol: ticker }); | ||
expect(result).toBe('Native'); | ||
expect(result).toBe("Native"); | ||
}); | ||
}); | ||
} | ||
}); | ||
describe('for Cosmos chain', () => { | ||
it('should return "GAIA" for non-ATOM tickers', () => { | ||
const result = getAssetType({ chain: Chain.Cosmos, symbol: 'NOT_ATOM' }); | ||
expect(result).toBe('GAIA'); | ||
describe("for Cosmos chain", () => { | ||
test('should return "GAIA" for non-ATOM tickers', () => { | ||
const result = getAssetType({ chain: Chain.Cosmos, symbol: "NOT_ATOM" }); | ||
expect(result).toBe("GAIA"); | ||
}); | ||
}); | ||
describe('for Binance chain', () => { | ||
it('should return "BEP2" for non-BNB tickers', () => { | ||
const result = getAssetType({ chain: Chain.Binance, symbol: 'NOT_BNB' }); | ||
expect(result).toBe('BEP2'); | ||
describe("for Binance chain", () => { | ||
test('should return "BEP2" for non-BNB tickers', () => { | ||
const result = getAssetType({ chain: Chain.Binance, symbol: "NOT_BNB" }); | ||
expect(result).toBe("BEP2"); | ||
}); | ||
}); | ||
describe('for Binance Smart Chain', () => { | ||
it('should return "BEP20" for non-BNB tickers', () => { | ||
const result = getAssetType({ chain: Chain.BinanceSmartChain, symbol: 'NOT_BNB' }); | ||
expect(result).toBe('BEP20'); | ||
describe("for Binance Smart Chain", () => { | ||
test('should return "BEP20" for non-BNB tickers', () => { | ||
const result = getAssetType({ chain: Chain.BinanceSmartChain, symbol: "NOT_BNB" }); | ||
expect(result).toBe("BEP20"); | ||
}); | ||
}); | ||
describe('for Ethereum chain', () => { | ||
it('should return "ERC20" for non-ETH tickers', () => { | ||
const result = getAssetType({ chain: Chain.Ethereum, symbol: 'NOT_ETH' }); | ||
expect(result).toBe('ERC20'); | ||
describe("for Ethereum chain", () => { | ||
test('should return "ERC20" for non-ETH tickers', () => { | ||
const result = getAssetType({ chain: Chain.Ethereum, symbol: "NOT_ETH" }); | ||
expect(result).toBe("ERC20"); | ||
}); | ||
}); | ||
describe('for Avalanche chain', () => { | ||
it('should return "AVAX" for non-AVAX tickers', () => { | ||
const result = getAssetType({ chain: Chain.Avalanche, symbol: 'NOT_AVAX' }); | ||
expect(result).toBe('AVAX'); | ||
describe("for Avalanche chain", () => { | ||
test('should return "AVAX" for non-AVAX tickers', () => { | ||
const result = getAssetType({ chain: Chain.Avalanche, symbol: "NOT_AVAX" }); | ||
expect(result).toBe("AVAX"); | ||
}); | ||
@@ -69,20 +69,22 @@ }); | ||
describe('getDecimal', () => { | ||
describe("getDecimal", () => { | ||
/** | ||
* Test out native | ||
*/ | ||
Object.values(Chain) | ||
.filter((c) => ![Chain.Ethereum, Chain.Avalanche].includes(c)) | ||
.forEach((chain) => { | ||
describe(chain, () => { | ||
it(`returns proper decimal for native ${chain} asset`, async () => { | ||
const decimal = await getDecimal({ chain, symbol: chain }); | ||
expect(decimal).toBe(BaseDecimal[chain]); | ||
}); | ||
const filteredChains = Object.values(Chain).filter( | ||
(c) => ![Chain.Ethereum, Chain.Avalanche].includes(c), | ||
); | ||
for (const chain of filteredChains) { | ||
describe(chain, () => { | ||
test(`returns proper decimal for native ${chain} asset`, async () => { | ||
const decimal = await getDecimal({ chain, symbol: chain }); | ||
expect(decimal).toBe(BaseDecimal[chain]); | ||
}); | ||
}); | ||
} | ||
describe('ETH', () => { | ||
it("returns proper decimal for eth and it's assets", async () => { | ||
const ethDecimal = await getDecimal({ chain: Chain.Ethereum, symbol: 'ETH' }); | ||
describe("ETH", () => { | ||
test("returns proper decimal for eth and it's assets", async () => { | ||
const ethDecimal = await getDecimal({ chain: Chain.Ethereum, symbol: "ETH" }); | ||
expect(ethDecimal).toBe(BaseDecimal.ETH); | ||
@@ -92,3 +94,3 @@ | ||
chain: Chain.Ethereum, | ||
symbol: 'USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', | ||
symbol: "USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", | ||
}); | ||
@@ -99,3 +101,3 @@ expect(usdcDecimal).toBe(6); | ||
chain: Chain.Ethereum, | ||
symbol: 'WBTC-0x2260fac5e5542a773aa44fbcfedf7c193bc2c599', | ||
symbol: "WBTC-0x2260fac5e5542a773aa44fbcfedf7c193bc2c599", | ||
}); | ||
@@ -106,3 +108,3 @@ expect(wbtcDecimal).toBe(8); | ||
chain: Chain.Ethereum, | ||
symbol: 'ZIL-0x05f4a42e251f2d52b8ed15e9fedaacfcef1fad27', | ||
symbol: "ZIL-0x05f4a42e251f2d52b8ed15e9fedaacfcef1fad27", | ||
}); | ||
@@ -113,3 +115,3 @@ expect(decDecimal).toBe(12); | ||
chain: Chain.Ethereum, | ||
symbol: 'KIND-0x4618519de4c304f3444ffa7f812dddc2971cc688', | ||
symbol: "KIND-0x4618519de4c304f3444ffa7f812dddc2971cc688", | ||
}); | ||
@@ -120,3 +122,3 @@ expect(kindDecimal).toBe(8); | ||
chain: Chain.Ethereum, | ||
symbol: 'HOMI-0xCa208BfD69ae6D2667f1FCbE681BAe12767c0078', | ||
symbol: "HOMI-0xCa208BfD69ae6D2667f1FCbE681BAe12767c0078", | ||
}); | ||
@@ -127,5 +129,5 @@ expect(shitcoinDecimal).toBe(0); | ||
describe('AVAX', () => { | ||
it("returns proper decimal for avax and it's assets", async () => { | ||
const avaxDecimal = await getDecimal({ chain: Chain.Avalanche, symbol: 'AVAX' }); | ||
describe("AVAX", () => { | ||
test.skip("returns proper decimal for avax and it's assets", async () => { | ||
const avaxDecimal = await getDecimal({ chain: Chain.Avalanche, symbol: "AVAX" }); | ||
expect(avaxDecimal).toBe(BaseDecimal.AVAX); | ||
@@ -135,3 +137,3 @@ | ||
chain: Chain.Avalanche, | ||
symbol: 'WBTC.e-0x50b7545627a5162f82a992c33b87adc75187b218', | ||
symbol: "WBTC.e-0x50b7545627a5162f82a992c33b87adc75187b218", | ||
}); | ||
@@ -142,3 +144,3 @@ expect(wbtceDecimal).toBe(8); | ||
chain: Chain.Avalanche, | ||
symbol: 'BTC.b-0x152b9d0FdC40C096757F570A51E494bd4b943E50', | ||
symbol: "BTC.b-0x152b9d0FdC40C096757F570A51E494bd4b943E50", | ||
}); | ||
@@ -149,3 +151,3 @@ expect(btcbDecimal).toBe(8); | ||
chain: Chain.Avalanche, | ||
symbol: 'TIME-0xb54f16fB19478766A268F172C9480f8da1a7c9C3', | ||
symbol: "TIME-0xb54f16fB19478766A268F172C9480f8da1a7c9C3", | ||
}); | ||
@@ -156,3 +158,3 @@ expect(timeDecimal).toBe(9); | ||
chain: Chain.Avalanche, | ||
symbol: 'USDT-0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7', | ||
symbol: "USDT-0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7", | ||
}); | ||
@@ -163,3 +165,3 @@ expect(usdtDecimal).toBe(6); | ||
chain: Chain.Avalanche, | ||
symbol: 'USDC-0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', | ||
symbol: "USDC-0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", | ||
}); | ||
@@ -166,0 +168,0 @@ expect(usdcDecimal).toBe(6); |
@@ -1,79 +0,81 @@ | ||
import { Chain, MemoType } from '@swapkit/types'; | ||
import { describe, expect, it } from 'vitest'; | ||
import { Chain, MemoType } from "@swapkit/types"; | ||
import { describe, expect, test } from "vitest"; | ||
import { getMemoFor } from '../memo.ts'; | ||
import { getMemoFor } from "../memo.ts"; | ||
describe('getMemoFor', () => { | ||
describe('for Leave, Upgrade, and Bond', () => { | ||
[ | ||
[MemoType.LEAVE, 'LEAVE:ABC123'], | ||
[MemoType.BOND, 'BOND:ABC123'], | ||
].forEach(([memoType, expected]) => { | ||
it(`returns correct memo for ${memoType}`, () => { | ||
const result = getMemoFor(memoType as MemoType, { address: 'ABC123' }); | ||
describe("getMemoFor", () => { | ||
describe("for Leave, Upgrade, and Bond", () => { | ||
const nodeMemos = [ | ||
[MemoType.LEAVE, "LEAVE:ABC123"], | ||
[MemoType.BOND, "BOND:ABC123"], | ||
]; | ||
for (const [memoType, expected] of nodeMemos) { | ||
test(`returns correct memo for ${memoType}`, () => { | ||
const result = getMemoFor(memoType as MemoType, { address: "ABC123" }); | ||
expect(result).toBe(expected); | ||
}); | ||
}); | ||
} | ||
}); | ||
describe('for Unbond and Thorname Register', () => { | ||
it('returns correct memo for Unbond', () => { | ||
const result = getMemoFor(MemoType.UNBOND, { address: 'ABC123', unbondAmount: 1000000000 }); | ||
expect(result).toBe('UNBOND:ABC123:1000000000'); | ||
describe("for Unbond and Thorname Register", () => { | ||
test("returns correct memo for Unbond", () => { | ||
const result = getMemoFor(MemoType.UNBOND, { address: "ABC123", unbondAmount: 1000000000 }); | ||
expect(result).toBe("UNBOND:ABC123:1000000000"); | ||
}); | ||
it('returns correct memo for Thorname Register', () => { | ||
test("returns correct memo for Thorname Register", () => { | ||
const result = getMemoFor(MemoType.THORNAME_REGISTER, { | ||
name: 'thorname', | ||
chain: 'BNB', | ||
address: '0xABC123', | ||
owner: '0xDEF456', | ||
name: "thorname", | ||
chain: "BNB", | ||
address: "0xABC123", | ||
owner: "0xDEF456", | ||
}); | ||
expect(result).toBe('~:thorname:BNB:0xABC123:0xDEF456'); | ||
expect(result).toBe("~:thorname:BNB:0xABC123:0xDEF456"); | ||
}); | ||
}); | ||
describe('for Deposit', () => { | ||
it('returns correct memo for Deposit (single side)', () => { | ||
describe("for Deposit", () => { | ||
test("returns correct memo for Deposit (single side)", () => { | ||
const result = getMemoFor(MemoType.DEPOSIT, { | ||
chain: Chain.Ethereum, | ||
symbol: 'ETH', | ||
symbol: "ETH", | ||
singleSide: true, | ||
}); | ||
expect(result).toBe('+:ETH/ETH::t:0'); | ||
expect(result).toBe("+:ETH/ETH"); | ||
}); | ||
it('returns correct memo for Deposit (dual side)', () => { | ||
test("returns correct memo for Deposit (dual side)", () => { | ||
const result = getMemoFor(MemoType.DEPOSIT, { | ||
chain: Chain.Avalanche, | ||
symbol: 'AVAX', | ||
address: '0xABC123', | ||
symbol: "AVAX", | ||
address: "0xABC123", | ||
}); | ||
expect(result).toBe('+:AVAX.AVAX:0xABC123:t:0'); | ||
expect(result).toBe("+:AVAX.AVAX:0xABC123"); | ||
}); | ||
}); | ||
describe('for Withdraw', () => { | ||
it('returns correct memo for Withdraw (single side)', () => { | ||
describe("for Withdraw", () => { | ||
test("returns correct memo for Withdraw (single side)", () => { | ||
const result = getMemoFor(MemoType.WITHDRAW, { | ||
chain: Chain.Bitcoin, | ||
ticker: 'BTC', | ||
symbol: 'BTC', | ||
ticker: "BTC", | ||
symbol: "BTC", | ||
basisPoints: 10000, | ||
singleSide: true, | ||
}); | ||
expect(result).toBe('-:BTC/BTC:10000'); | ||
expect(result).toBe("-:BTC/BTC:10000"); | ||
}); | ||
it('returns correct memo for Withdraw (dual side)', () => { | ||
test("returns correct memo for Withdraw (dual side)", () => { | ||
const result = getMemoFor(MemoType.WITHDRAW, { | ||
chain: Chain.Ethereum, | ||
ticker: 'ETH', | ||
symbol: 'ETH', | ||
ticker: "ETH", | ||
symbol: "ETH", | ||
basisPoints: 100, | ||
targetAssetString: 'ETH.ETH', | ||
targetAssetString: "ETH.ETH", | ||
}); | ||
expect(result).toBe('-:ETH.ETH:100:ETH.ETH'); | ||
expect(result).toBe("-:ETH.ETH:100:ETH.ETH"); | ||
}); | ||
}); | ||
}); |
@@ -1,22 +0,20 @@ | ||
import { describe, expect, it } from 'vitest'; | ||
import { describe, expect, test } from "vitest"; | ||
import { derivationPathToString, getTHORNameCost, validateTHORName } from '../others.ts'; | ||
import { derivationPathToString, getTHORNameCost, validateTHORName } from "../others.ts"; | ||
describe('derivationPathToString', () => { | ||
it('should return the correct string for a full path', () => { | ||
describe("derivationPathToString", () => { | ||
test("should return the correct string for a full path", () => { | ||
const path = [1, 2, 3, 4, 5]; | ||
const result = derivationPathToString(path); | ||
expect(result).toEqual("1'/2'/3'/4/5"); | ||
expect(derivationPathToString(path)).toEqual("1'/2'/3'/4/5"); | ||
}); | ||
it('should return the correct string for a short path', () => { | ||
test("should return the correct string for a short path", () => { | ||
const path = [1, 2, 3, 4]; | ||
const result = derivationPathToString(path); | ||
expect(result).toEqual("1'/2'/3'/4"); | ||
expect(derivationPathToString(path)).toEqual("1'/2'/3'/4"); | ||
}); | ||
}); | ||
describe('getTHORNameCost', () => { | ||
describe('for correct values', () => { | ||
[ | ||
describe("getTHORNameCost", () => { | ||
describe("for correct values", () => { | ||
const costCases = [ | ||
[1, 11], | ||
@@ -26,35 +24,37 @@ [2, 12], | ||
[10, 20], | ||
].forEach(([years, expected]) => { | ||
it(`returns correct ${expected} cost for ${years} years`, () => { | ||
]; | ||
for (const [years, expected] of costCases) { | ||
test(`returns correct ${expected} cost for ${years} years`, () => { | ||
const result = getTHORNameCost(years); | ||
expect(result).toBe(expected); | ||
}); | ||
}); | ||
} | ||
}); | ||
it('throws an error for negative years', () => { | ||
expect(() => getTHORNameCost(-1)).toThrowError('Invalid number of year'); | ||
test("throws an error for negative years", () => { | ||
expect(() => getTHORNameCost(-1)).toThrowError("Invalid number of year"); | ||
}); | ||
}); | ||
describe('validateTHORName', () => { | ||
describe("validateTHORName", () => { | ||
const casesWithExpectation: [string, boolean][] = [ | ||
['validname', true], | ||
['valid-name', true], | ||
['valid_name', true], | ||
['valid+name', true], | ||
['name_with_numbers123', true], | ||
['UPPER_CASE', true], | ||
['toolongname123456789012345678901', false], | ||
['invalid@name', false], | ||
['invalid!name', false], | ||
['invalid#name', false], | ||
["validname", true], | ||
["valid-name", true], | ||
["valid_name", true], | ||
["valid+name", true], | ||
["name_with_numbers123", true], | ||
["UPPER_CASE", true], | ||
["toolongname123456789012345678901", false], | ||
["invalid@name", false], | ||
["invalid!name", false], | ||
["invalid#name", false], | ||
]; | ||
casesWithExpectation.forEach(([name, expected]) => { | ||
it(`returns ${expected} for THORName "${name}"`, () => { | ||
for (const [name, expected] of casesWithExpectation) { | ||
test(`returns ${expected} for THORName "${name}"`, () => { | ||
const result = validateTHORName(name); | ||
expect(result).toBe(expected); | ||
}); | ||
}); | ||
} | ||
}); |
@@ -1,6 +0,6 @@ | ||
import { RequestClient } from '@swapkit/api'; | ||
import type { EVMChain } from '@swapkit/types'; | ||
import { BaseDecimal, Chain, ChainToRPC, EVMChainList, FeeOption } from '@swapkit/types'; | ||
import { RequestClient } from "@swapkit/api"; | ||
import type { EVMChain } from "@swapkit/types"; | ||
import { BaseDecimal, Chain, ChainToRPC, EVMChains, FeeOption } from "@swapkit/types"; | ||
const getDecimalMethodHex = '0x313ce567'; | ||
const getDecimalMethodHex = "0x313ce567"; | ||
@@ -18,11 +18,11 @@ export type CommonAssetString = | ||
headers: { | ||
accept: '*/*', | ||
'content-type': 'application/json', | ||
'cache-control': 'no-cache', | ||
accept: "*/*", | ||
"content-type": "application/json", | ||
"cache-control": "no-cache", | ||
}, | ||
body: JSON.stringify({ | ||
id: 44, | ||
jsonrpc: '2.0', | ||
method: 'eth_call', | ||
params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, 'latest'], | ||
jsonrpc: "2.0", | ||
method: "eth_call", | ||
params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, "latest"], | ||
}), | ||
@@ -38,7 +38,7 @@ }); | ||
const getETHAssetDecimal = async (symbol: string) => { | ||
const getETHAssetDecimal = (symbol: string) => { | ||
if (symbol === Chain.Ethereum) return BaseDecimal.ETH; | ||
const [, address] = symbol.split('-'); | ||
const [, address] = symbol.split("-"); | ||
return address?.startsWith('0x') | ||
return address?.startsWith("0x") | ||
? getContractDecimals({ chain: Chain.Ethereum, to: address }) | ||
@@ -48,6 +48,6 @@ : BaseDecimal.ETH; | ||
const getAVAXAssetDecimal = async (symbol: string) => { | ||
const [, address] = symbol.split('-'); | ||
const getAVAXAssetDecimal = (symbol: string) => { | ||
const [, address] = symbol.split("-"); | ||
return address?.startsWith('0x') | ||
return address?.startsWith("0x") | ||
? getContractDecimals({ chain: Chain.Avalanche, to: address.toLowerCase() }) | ||
@@ -57,3 +57,3 @@ : BaseDecimal.AVAX; | ||
const getBSCAssetDecimal = async (symbol: string) => { | ||
const getBSCAssetDecimal = (symbol: string) => { | ||
if (symbol === Chain.BinanceSmartChain) return BaseDecimal.BSC; | ||
@@ -64,3 +64,3 @@ | ||
export const getDecimal = async ({ chain, symbol }: { chain: Chain; symbol: string }) => { | ||
export const getDecimal = ({ chain, symbol }: { chain: Chain; symbol: string }) => { | ||
switch (chain) { | ||
@@ -86,31 +86,20 @@ case Chain.Ethereum: | ||
switch (chain) { | ||
case Chain.Bitcoin: | ||
case Chain.BitcoinCash: | ||
case Chain.Litecoin: | ||
case Chain.Dogecoin: | ||
case Chain.Binance: | ||
case Chain.Ethereum: | ||
case Chain.Avalanche: | ||
case Chain.Polkadot: | ||
case Chain.Chainflip: | ||
return symbol === chain; | ||
case Chain.Arbitrum: | ||
case Chain.Optimism: | ||
return 'ETH' === symbol; | ||
return symbol === "ETH"; | ||
case Chain.Maya: | ||
return symbol === 'CACAO'; | ||
return symbol === "CACAO"; | ||
case Chain.Kujira: | ||
return symbol === 'KUJI'; | ||
return symbol === "KUJI"; | ||
case Chain.Cosmos: | ||
return symbol === 'ATOM'; | ||
return symbol === "ATOM"; | ||
case Chain.Polygon: | ||
return symbol === 'MATIC'; | ||
return symbol === "MATIC"; | ||
case Chain.BinanceSmartChain: | ||
return symbol === 'BNB'; | ||
return symbol === "BNB"; | ||
case Chain.THORChain: | ||
return symbol === 'RUNE'; | ||
return symbol === "RUNE"; | ||
default: | ||
return symbol === chain; | ||
} | ||
@@ -124,16 +113,16 @@ }; | ||
case `${Chain.Ethereum}.THOR`: | ||
return { identifier: 'ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044', decimal: 18 }; | ||
return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 }; | ||
case `${Chain.Ethereum}.vTHOR`: | ||
return { identifier: 'ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d', decimal: 18 }; | ||
return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 }; | ||
case Chain.Cosmos: | ||
return { identifier: 'GAIA.ATOM', decimal: BaseDecimal[assetString] }; | ||
return { identifier: "GAIA.ATOM", decimal: BaseDecimal[assetString] }; | ||
case Chain.THORChain: | ||
return { identifier: 'THOR.RUNE', decimal: BaseDecimal[assetString] }; | ||
return { identifier: "THOR.RUNE", decimal: BaseDecimal[assetString] }; | ||
case Chain.BinanceSmartChain: | ||
return { identifier: 'BSC.BNB', decimal: BaseDecimal[assetString] }; | ||
return { identifier: "BSC.BNB", decimal: BaseDecimal[assetString] }; | ||
case Chain.Maya: | ||
return { identifier: 'MAYA.CACAO', decimal: BaseDecimal.MAYA }; | ||
return { identifier: "MAYA.CACAO", decimal: BaseDecimal.MAYA }; | ||
case `${Chain.Maya}.MAYA`: | ||
return { identifier: 'MAYA.MAYA', decimal: 4 }; | ||
return { identifier: "MAYA.MAYA", decimal: 4 }; | ||
@@ -143,15 +132,3 @@ case `${Chain.Kujira}.USK`: | ||
case Chain.Kujira: | ||
case Chain.Arbitrum: | ||
case Chain.Optimism: | ||
case Chain.BitcoinCash: | ||
case Chain.Litecoin: | ||
case Chain.Dogecoin: | ||
case Chain.Binance: | ||
case Chain.Avalanche: | ||
case Chain.Chainflip: | ||
case Chain.Polygon: | ||
case Chain.Polkadot: | ||
case Chain.Bitcoin: | ||
case Chain.Ethereum: | ||
default: | ||
return { identifier: `${assetString}.${assetString}`, decimal: BaseDecimal[assetString] }; | ||
@@ -161,35 +138,29 @@ } | ||
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: Refactor | ||
export const getAssetType = ({ chain, symbol }: { chain: Chain; symbol: string }) => { | ||
if (symbol.includes('/')) return 'Synth'; | ||
if (symbol.includes("/")) return "Synth"; | ||
switch (chain) { | ||
case Chain.Bitcoin: | ||
case Chain.BitcoinCash: | ||
case Chain.Dogecoin: | ||
case Chain.Litecoin: | ||
case Chain.Maya: | ||
case Chain.THORChain: | ||
case Chain.Polkadot: | ||
case Chain.Chainflip: | ||
return 'Native'; | ||
case Chain.Cosmos: | ||
return symbol === 'ATOM' ? 'Native' : Chain.Cosmos; | ||
return symbol === "ATOM" ? "Native" : Chain.Cosmos; | ||
case Chain.Kujira: | ||
return symbol === Chain.Kujira ? 'Native' : Chain.Kujira; | ||
return symbol === Chain.Kujira ? "Native" : Chain.Kujira; | ||
case Chain.Binance: | ||
return symbol === Chain.Binance ? 'Native' : 'BEP2'; | ||
return symbol === Chain.Binance ? "Native" : "BEP2"; | ||
case Chain.BinanceSmartChain: | ||
return symbol === Chain.Binance ? 'Native' : 'BEP20'; | ||
return symbol === Chain.Binance ? "Native" : "BEP20"; | ||
case Chain.Ethereum: | ||
return symbol === Chain.Ethereum ? 'Native' : 'ERC20'; | ||
return symbol === Chain.Ethereum ? "Native" : "ERC20"; | ||
case Chain.Avalanche: | ||
return symbol === Chain.Avalanche ? 'Native' : Chain.Avalanche; | ||
return symbol === Chain.Avalanche ? "Native" : Chain.Avalanche; | ||
case Chain.Polygon: | ||
return symbol === Chain.Polygon ? 'Native' : 'POLYGON'; | ||
return symbol === Chain.Polygon ? "Native" : "POLYGON"; | ||
case Chain.Arbitrum: | ||
return [Chain.Ethereum, Chain.Arbitrum].includes(symbol as Chain) ? 'Native' : 'ARBITRUM'; | ||
return [Chain.Ethereum, Chain.Arbitrum].includes(symbol as Chain) ? "Native" : "ARBITRUM"; | ||
case Chain.Optimism: | ||
return [Chain.Ethereum, Chain.Optimism].includes(symbol as Chain) ? 'Native' : 'OPTIMISM'; | ||
return [Chain.Ethereum, Chain.Optimism].includes(symbol as Chain) ? "Native" : "OPTIMISM"; | ||
default: | ||
return "Native"; | ||
} | ||
@@ -199,6 +170,6 @@ }; | ||
export const assetFromString = (assetString: string) => { | ||
const [chain, ...symbolArray] = assetString.split('.') as [Chain, ...(string | undefined)[]]; | ||
const synth = assetString.includes('/'); | ||
const symbol = symbolArray.join('.'); | ||
const ticker = symbol?.split('-')?.[0]; | ||
const [chain, ...symbolArray] = assetString.split(".") as [Chain, ...(string | undefined)[]]; | ||
const synth = assetString.includes("/"); | ||
const symbol = symbolArray.join("."); | ||
const ticker = symbol?.split("-")?.[0]; | ||
@@ -210,9 +181,9 @@ return { chain, symbol, ticker, synth }; | ||
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/, | ||
'gmi', | ||
"gmi", | ||
); | ||
const evmAssetHasAddress = (assetString: string) => { | ||
const [chain, symbol] = assetString.split('.') as [EVMChain, string]; | ||
if (!EVMChainList.includes(chain as EVMChain)) return true; | ||
const [, address] = symbol.split('-') as [string, string?]; | ||
const [chain, symbol] = assetString.split(".") as [EVMChain, string]; | ||
if (!EVMChains.includes(chain as EVMChain)) return true; | ||
const [, address] = symbol.split("-") as [string, string?]; | ||
@@ -230,10 +201,8 @@ return isGasAsset({ chain: chain as Chain, symbol }) || !!address; | ||
) => | ||
tokens.filter((token) => { | ||
const assetString = `${token.chain}.${token.symbol}`; | ||
tokens.filter(({ chain, value, symbol }) => { | ||
const assetString = `${chain}.${symbol}`; | ||
return ( | ||
!potentialScamRegex.test(assetString) && | ||
evmAssetHasAddress(assetString) && | ||
token.value !== '0' | ||
!potentialScamRegex.test(assetString) && evmAssetHasAddress(assetString) && value !== "0" | ||
); | ||
}); |
@@ -1,6 +0,6 @@ | ||
import { BaseDecimal } from '@swapkit/types'; | ||
import { BaseDecimal } from "@swapkit/types"; | ||
import { SwapKitNumber } from '../index.ts'; | ||
import { SwapKitNumber } from "../index.ts"; | ||
type ShareParams<T = {}> = T & { | ||
type ShareParams<T extends {}> = T & { | ||
liquidityUnits: string; | ||
@@ -10,3 +10,3 @@ poolUnits: string; | ||
type PoolParams<T = {}> = T & { | ||
type PoolParams = { | ||
runeAmount: string; | ||
@@ -152,4 +152,4 @@ assetAmount: string; | ||
if (liquidityUnitsAfterAdd.getBaseValue('number') === 0) { | ||
return estimatedLiquidityUnits.div(P).getBaseValue('number'); | ||
if (liquidityUnitsAfterAdd.getBaseValue("number") === 0) { | ||
return estimatedLiquidityUnits.div(P).getBaseValue("number"); | ||
} | ||
@@ -160,3 +160,3 @@ | ||
return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue('number'); | ||
return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue("number"); | ||
} | ||
@@ -170,3 +170,3 @@ | ||
}: PoolParams) { | ||
if (runeAmount === '0' || assetAmount === '0' || runeDepth === '0' || assetDepth === '0') | ||
if (runeAmount === "0" || assetAmount === "0" || runeDepth === "0" || assetDepth === "0") | ||
return 0; | ||
@@ -183,3 +183,3 @@ // formula: (t * R - T * r)/ (T*r + R*T) | ||
// set absolute value of percent, no negative allowed | ||
return Math.abs(numerator.div(denominator).getBaseValue('number')); | ||
return Math.abs(numerator.div(denominator).getBaseValue("number")); | ||
} |
@@ -1,2 +0,2 @@ | ||
import { Chain, MemoType } from '@swapkit/types'; | ||
import { Chain, MemoType } from "@swapkit/types"; | ||
@@ -12,11 +12,10 @@ export type ThornameRegisterParam = { | ||
type WithAddress<T = {}> = T & { address: string }; | ||
type WithChain<T = {}> = T & { chain: Chain }; | ||
type WithChain<T extends {}> = T & { chain: Chain }; | ||
export type MemoOptions<T extends MemoType> = { | ||
[MemoType.BOND]: WithAddress; | ||
[MemoType.LEAVE]: WithAddress; | ||
[MemoType.CLOSE_LOAN]: WithAddress<{ asset: string; minAmount?: string }>; | ||
[MemoType.OPEN_LOAN]: WithAddress<{ asset: string; minAmount?: string }>; | ||
[MemoType.UNBOND]: WithAddress<{ unbondAmount: number }>; | ||
[MemoType.BOND]: { address: string }; | ||
[MemoType.LEAVE]: { address: string }; | ||
[MemoType.CLOSE_LOAN]: { address: string; asset: string; minAmount?: string }; | ||
[MemoType.OPEN_LOAN]: { address: string; asset: string; minAmount?: string }; | ||
[MemoType.UNBOND]: { address: string; unbondAmount: number }; | ||
[MemoType.DEPOSIT]: WithChain<{ symbol: string; address?: string; singleSide?: boolean }>; | ||
@@ -30,3 +29,3 @@ [MemoType.WITHDRAW]: WithChain<{ | ||
}>; | ||
[MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, 'preferredAsset' | 'expiryBlock'>; | ||
[MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, "preferredAsset" | "expiryBlock">; | ||
}[T]; | ||
@@ -49,3 +48,3 @@ | ||
const { name, chain, address, owner } = options as MemoOptions<MemoType.THORNAME_REGISTER>; | ||
return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : ''}`; | ||
return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : ""}`; | ||
} | ||
@@ -59,7 +58,7 @@ | ||
case Chain.Litecoin: | ||
return 'l'; | ||
return "l"; | ||
case Chain.Dogecoin: | ||
return 'd'; | ||
return "d"; | ||
case Chain.BitcoinCash: | ||
return 'c'; | ||
return "c"; | ||
default: | ||
@@ -71,4 +70,4 @@ return `${chain}.${symbol}`; | ||
return singleSide | ||
? `${memoType}:${chain}/${symbol}::t:0` | ||
: `${memoType}:${getPoolIdentifier(chain, symbol)}:${address || ''}:t:0`; | ||
? `${memoType}:${chain}/${symbol}` | ||
: `${memoType}:${getPoolIdentifier(chain, symbol)}:${address || ""}`; | ||
} | ||
@@ -81,5 +80,5 @@ | ||
const shortenedSymbol = | ||
chain === 'ETH' && ticker !== 'ETH' ? `${ticker}-${symbol.slice(-3)}` : symbol; | ||
const target = !singleSide && targetAssetString ? `:${targetAssetString}` : ''; | ||
const assetDivider = singleSide ? '/' : '.'; | ||
chain === "ETH" && ticker !== "ETH" ? `${ticker}-${symbol.slice(-3)}` : symbol; | ||
const target = !singleSide && targetAssetString ? `:${targetAssetString}` : ""; | ||
const assetDivider = singleSide ? "/" : "."; | ||
@@ -97,4 +96,4 @@ return `${memoType}:${chain}${assetDivider}${shortenedSymbol}:${basisPoints}${target}`; | ||
default: | ||
return ''; | ||
return ""; | ||
} | ||
}; |
// 10 rune for register, 1 rune per year | ||
// MINIMUM_REGISTRATION_FEE = 11 | ||
export function getTHORNameCost(year: number) { | ||
if (year < 0) throw new Error('Invalid number of year'); | ||
if (year < 0) throw new Error("Invalid number of year"); | ||
return 10 + year; | ||
@@ -17,5 +17,5 @@ } | ||
export function derivationPathToString([network, chainId, account, change, index]: number[]) { | ||
const shortPath = typeof index !== 'number'; | ||
const shortPath = typeof index !== "number"; | ||
return `${network}'/${chainId}'/${account}'/${change}${shortPath ? '' : `/${index}`}`; | ||
return `${network}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`; | ||
} |
@@ -1,13 +0,13 @@ | ||
import { Chain } from '@swapkit/types'; | ||
import { Chain } from "@swapkit/types"; | ||
// Backward compatibility | ||
const supportedChains = [...Object.values(Chain), 'TERRA']; | ||
const supportedChains = [...Object.values(Chain), "TERRA"]; | ||
export function validateIdentifier(identifier: string = '') { | ||
export function validateIdentifier(identifier = "") { | ||
const uppercasedIdentifier = identifier.toUpperCase(); | ||
const [chain] = uppercasedIdentifier.split('.') as [Chain, string]; | ||
const [chain] = uppercasedIdentifier.split(".") as [Chain, string]; | ||
if (supportedChains.includes(chain)) return true; | ||
const [synthChain] = uppercasedIdentifier.split('/') as [Chain, string]; | ||
const [synthChain] = uppercasedIdentifier.split("/") as [Chain, string]; | ||
if (supportedChains.includes(synthChain)) return true; | ||
@@ -14,0 +14,0 @@ |
@@ -1,2 +0,2 @@ | ||
export * from '@swapkit/api'; | ||
export * from "@swapkit/api"; | ||
@@ -6,6 +6,6 @@ /** | ||
*/ | ||
export * from './helpers/asset.ts'; | ||
export * from './helpers/liquidity.ts'; | ||
export * from './helpers/memo.ts'; | ||
export * from './helpers/others.ts'; | ||
export * from "./helpers/asset.ts"; | ||
export * from "./helpers/liquidity.ts"; | ||
export * from "./helpers/memo.ts"; | ||
export * from "./helpers/others.ts"; | ||
@@ -15,5 +15,5 @@ /** | ||
*/ | ||
export * from './modules/assetValue.ts'; | ||
export * from './modules/bigIntArithmetics.ts'; | ||
export * from './modules/swapKitError.ts'; | ||
export * from './modules/swapKitNumber.ts'; | ||
export * from "./modules/assetValue.ts"; | ||
export * from "./modules/bigIntArithmetics.ts"; | ||
export * from "./modules/swapKitError.ts"; | ||
export * from "./modules/swapKitNumber.ts"; |
@@ -1,9 +0,9 @@ | ||
import { BaseDecimal, Chain } from '@swapkit/types'; | ||
import { describe, expect, test } from 'vitest'; | ||
import { BaseDecimal, Chain } from "@swapkit/types"; | ||
import { describe, expect, test } from "vitest"; | ||
import { AssetValue, getMinAmountByChain } from '../assetValue.ts'; | ||
import { AssetValue, getMinAmountByChain } from "../assetValue.ts"; | ||
describe('AssetValue', () => { | ||
describe('assetValue', () => { | ||
test('returns asset ticker with value', () => { | ||
describe("AssetValue", () => { | ||
describe("assetValue", () => { | ||
test("returns asset ticker with value", () => { | ||
const fakeAvaxUSDCAsset = new AssetValue({ | ||
@@ -13,6 +13,6 @@ decimal: 6, | ||
chain: Chain.Avalanche, | ||
symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
symbol: "USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
}); | ||
expect(fakeAvaxUSDCAsset.toString()).toBe( | ||
'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
"AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
); | ||
@@ -22,3 +22,3 @@ | ||
chain: Chain.THORChain, | ||
symbol: 'ETH/ETH', | ||
symbol: "ETH/ETH", | ||
decimal: 8, | ||
@@ -28,15 +28,15 @@ value: 1234567890, | ||
expect(ethSynth.toString()).toBe('ETH/ETH'); | ||
expect(ethSynth.mul(21.37).getValue('string')).toBe('26382715809.3'); | ||
expect(ethSynth.toString()).toBe("ETH/ETH"); | ||
expect(ethSynth.mul(21.37).getValue("string")).toBe("26382715809.3"); | ||
const ethThorSynth = new AssetValue({ | ||
chain: Chain.THORChain, | ||
symbol: 'ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044', | ||
symbol: "ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044", | ||
decimal: 8, | ||
value: 1234567890, | ||
}); | ||
expect(ethThorSynth.toString()).toBe('ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044'); | ||
expect(ethThorSynth.toString()).toBe("ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044"); | ||
const atomDerived = new AssetValue({ | ||
identifier: 'THOR.ATOM', | ||
identifier: "THOR.ATOM", | ||
decimal: 6, | ||
@@ -46,8 +46,8 @@ value: 123456789, | ||
expect(atomDerived.toString()).toBe('THOR.ATOM'); | ||
expect(atomDerived.toString()).toBe("THOR.ATOM"); | ||
}); | ||
}); | ||
describe('toUrl', () => { | ||
test('returns asset compliance with url', () => { | ||
describe("toUrl", () => { | ||
test("returns asset compliance with url", () => { | ||
const fakeAvaxUSDCAsset = new AssetValue({ | ||
@@ -57,37 +57,37 @@ decimal: 6, | ||
chain: Chain.Avalanche, | ||
symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
symbol: "USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
}); | ||
expect(fakeAvaxUSDCAsset.toUrl()).toBe( | ||
'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
"AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
); | ||
const thor = AssetValue.fromChainOrSignature('ETH.THOR'); | ||
expect(thor.toUrl()).toBe('ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044'); | ||
const thor = AssetValue.fromChainOrSignature("ETH.THOR"); | ||
expect(thor.toUrl()).toBe("ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"); | ||
const ethSynth = new AssetValue({ | ||
chain: Chain.THORChain, | ||
symbol: 'ETH/ETH', | ||
symbol: "ETH/ETH", | ||
decimal: 8, | ||
value: 1234567890, | ||
}); | ||
expect(ethSynth.toUrl()).toBe('THOR.ETH.ETH'); | ||
expect(ethSynth.toUrl()).toBe("THOR.ETH.ETH"); | ||
const ethThorSynth = new AssetValue({ | ||
chain: Chain.THORChain, | ||
symbol: 'ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044', | ||
symbol: "ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044", | ||
decimal: 8, | ||
value: 1234567890, | ||
}); | ||
expect(ethThorSynth.toUrl()).toBe('THOR.ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044'); | ||
expect(ethThorSynth.toUrl()).toBe("THOR.ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"); | ||
}); | ||
}); | ||
describe('eq', () => { | ||
test('checks if assets are same chain and symbol', () => { | ||
const firstThor = AssetValue.fromChainOrSignature('ETH.THOR'); | ||
const secondThor = AssetValue.fromChainOrSignature('ETH.THOR'); | ||
const vThor = AssetValue.fromChainOrSignature('ETH.vTHOR'); | ||
describe("eq", () => { | ||
test("checks if assets are same chain and symbol", () => { | ||
const firstThor = AssetValue.fromChainOrSignature("ETH.THOR"); | ||
const secondThor = AssetValue.fromChainOrSignature("ETH.THOR"); | ||
const vThor = AssetValue.fromChainOrSignature("ETH.vTHOR"); | ||
const firstUsdc = new AssetValue({ | ||
chain: Chain.Avalanche, | ||
symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
symbol: "USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
decimal: 6, | ||
@@ -98,3 +98,3 @@ value: 1234567890, | ||
chain: Chain.Avalanche, | ||
symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
symbol: "USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
decimal: 6, | ||
@@ -118,4 +118,4 @@ value: 1234, | ||
describe('from bigint', () => { | ||
test('returns asset value with correct decimal', async () => { | ||
describe("from bigint", () => { | ||
test.todo("returns asset value with correct decimal", async () => { | ||
const avaxUSDCAsset = await AssetValue.fromIdentifier( | ||
@@ -125,8 +125,8 @@ `${Chain.Avalanche}.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e`, | ||
); | ||
expect(avaxUSDCAsset.getValue('string')).toBe('1234.5678'); | ||
expect(avaxUSDCAsset.getValue("string")).toBe("1234.5678"); | ||
}); | ||
}); | ||
describe('toString', () => { | ||
test('returns asset value string/identifier', async () => { | ||
describe("toString", () => { | ||
test("returns asset value string/identifier", async () => { | ||
const avaxUSDCAsset = new AssetValue({ | ||
@@ -136,18 +136,18 @@ decimal: 6, | ||
chain: Chain.Avalanche, | ||
symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
symbol: "USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
}); | ||
expect(avaxUSDCAsset.toString()).toBe('AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e'); | ||
expect(avaxUSDCAsset.toString()).toBe("AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e"); | ||
const thor = AssetValue.fromChainOrSignature('ETH.THOR'); | ||
expect(thor.toString()).toBe('ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044'); | ||
const thor = AssetValue.fromChainOrSignature("ETH.THOR"); | ||
expect(thor.toString()).toBe("ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"); | ||
const ethSynth = await AssetValue.fromIdentifier('ETH/ETH'); | ||
expect(ethSynth.toString()).toBe('ETH/ETH'); | ||
const ethSynth = await AssetValue.fromIdentifier("ETH/ETH"); | ||
expect(ethSynth.toString()).toBe("ETH/ETH"); | ||
}); | ||
}); | ||
describe('fromIdentifier', () => { | ||
test('creates AssetValue from string', async () => { | ||
describe("fromIdentifier", () => { | ||
test.skip("creates AssetValue from string", async () => { | ||
const avaxUSDCAsset = await AssetValue.fromIdentifier( | ||
'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
"AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
); | ||
@@ -157,3 +157,3 @@ | ||
expect.objectContaining({ | ||
address: '0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
address: "0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
chain: Chain.Avalanche, | ||
@@ -163,4 +163,4 @@ decimal: 6, | ||
isSynthetic: false, | ||
symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e', | ||
ticker: 'USDC', | ||
symbol: "USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
ticker: "USDC", | ||
}), | ||
@@ -171,5 +171,5 @@ ); | ||
describe('fromString', () => { | ||
test('creates AssetValue from string', async () => { | ||
const fakeAvaxAssetString = 'AVAX.ASDF-1234'; | ||
describe("fromString", () => { | ||
test("creates AssetValue from string", async () => { | ||
const fakeAvaxAssetString = "AVAX.ASDF-1234"; | ||
const fakeAvaxAsset = await AssetValue.fromString(fakeAvaxAssetString); | ||
@@ -179,3 +179,3 @@ | ||
expect.objectContaining({ | ||
address: '1234', | ||
address: "1234", | ||
chain: Chain.Avalanche, | ||
@@ -185,4 +185,4 @@ decimal: 18, | ||
isSynthetic: false, | ||
symbol: 'ASDF-1234', | ||
ticker: 'ASDF', | ||
symbol: "ASDF-1234", | ||
ticker: "ASDF", | ||
}), | ||
@@ -193,9 +193,30 @@ ); | ||
describe('fromUrl', () => { | ||
test('creates AssetValue from url like format', async () => { | ||
const synthETHString = 'THOR.ETH.ETH'; | ||
const ethString = 'ETH.ETH'; | ||
const thorString = 'ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044'; | ||
const synthThorString = 'THOR.ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044'; | ||
describe("fromStringWithBase", () => { | ||
test("creates AssetValue from string with base", async () => { | ||
const fakeAvaxAssetString = "AVAX.ASDF-1234"; | ||
const fakeAvaxAsset = await AssetValue.fromStringWithBase(fakeAvaxAssetString, 1, 8); | ||
expect(fakeAvaxAsset).toEqual( | ||
expect.objectContaining({ | ||
address: "1234", | ||
chain: Chain.Avalanche, | ||
decimal: 18, | ||
isGasAsset: false, | ||
isSynthetic: false, | ||
symbol: "ASDF-1234", | ||
ticker: "ASDF", | ||
}), | ||
); | ||
expect(fakeAvaxAsset.getValue("string")).toBe("100000000"); | ||
expect(fakeAvaxAsset.getBaseValue("string")).toBe("100000000000000000000000000"); | ||
}); | ||
}); | ||
describe("fromUrl", () => { | ||
test("creates AssetValue from url like format", async () => { | ||
const synthETHString = "THOR.ETH.ETH"; | ||
const ethString = "ETH.ETH"; | ||
const thorString = "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"; | ||
const synthThorString = "THOR.ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"; | ||
const synthETH = await AssetValue.fromUrl(synthETHString); | ||
@@ -206,14 +227,14 @@ const eth = await AssetValue.fromUrl(ethString); | ||
expect(synthETH.toString()).toBe('ETH/ETH'); | ||
expect(eth.toString()).toBe('ETH.ETH'); | ||
expect(thor.toString()).toBe('ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044'); | ||
expect(synthThor.toString()).toBe('ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044'); | ||
expect(synthETH.toString()).toBe("ETH/ETH"); | ||
expect(eth.toString()).toBe("ETH.ETH"); | ||
expect(thor.toString()).toBe("ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"); | ||
expect(synthThor.toString()).toBe("ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044"); | ||
}); | ||
}); | ||
describe('fromIdentifierSync', () => { | ||
test('(same as fromIdentifier) - creates AssetValue from string via `@swapkit/tokens` lists', async () => { | ||
describe("fromIdentifierSync", () => { | ||
test("(same as fromIdentifier) - creates AssetValue from string via `@swapkit/tokens` lists", async () => { | ||
await AssetValue.loadStaticAssets(); | ||
const thor = AssetValue.fromIdentifierSync( | ||
'ARB.USDT-0XFD086BC7CD5C481DCC9C85EBE478A1C0B69FCBB9', | ||
"ARB.USDT-0XFD086BC7CD5C481DCC9C85EBE478A1C0B69FCBB9", | ||
); | ||
@@ -224,3 +245,3 @@ | ||
expect.objectContaining({ | ||
address: '0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9', | ||
address: "0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9", | ||
chain: Chain.Arbitrum, | ||
@@ -230,4 +251,4 @@ decimal: 6, | ||
isSynthetic: false, | ||
symbol: 'USDT-0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9', | ||
ticker: 'USDT', | ||
symbol: "USDT-0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9", | ||
ticker: "USDT", | ||
}), | ||
@@ -238,6 +259,6 @@ ); | ||
describe('fromStringSync', () => { | ||
test('creates AssetValue from string via `@swapkit/tokens` lists', async () => { | ||
describe("fromStringSync", () => { | ||
test("creates AssetValue from string via `@swapkit/tokens` lists", async () => { | ||
await AssetValue.loadStaticAssets(); | ||
const thor = AssetValue.fromStringSync('ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044'); | ||
const thor = AssetValue.fromStringSync("ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"); | ||
@@ -247,3 +268,3 @@ expect(thor).toBeDefined(); | ||
expect.objectContaining({ | ||
address: '0xa5f2211b9b8170f694421f2046281775e8468044', | ||
address: "0xa5f2211b9b8170f694421f2046281775e8468044", | ||
chain: Chain.Ethereum, | ||
@@ -253,11 +274,25 @@ decimal: 18, | ||
isSynthetic: false, | ||
symbol: 'THOR-0xa5f2211b9b8170f694421f2046281775e8468044', | ||
ticker: 'THOR', | ||
symbol: "THOR-0xa5f2211b9b8170f694421f2046281775e8468044", | ||
ticker: "THOR", | ||
}), | ||
); | ||
const usdc = AssetValue.fromStringSync("ETH.USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48"); | ||
expect(usdc).toBeDefined(); | ||
expect(usdc).toEqual( | ||
expect.objectContaining({ | ||
address: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", | ||
chain: Chain.Ethereum, | ||
decimal: 6, | ||
isGasAsset: false, | ||
isSynthetic: false, | ||
symbol: "USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", | ||
ticker: "USDC", | ||
}), | ||
); | ||
}); | ||
test('returns safe decimals if string is not in `@swapkit/tokens` lists', async () => { | ||
test("returns safe decimals if string is not in `@swapkit/tokens` lists", async () => { | ||
await AssetValue.loadStaticAssets(); | ||
const fakeAvaxUSDCAssetString = 'AVAX.USDC-1234'; | ||
const fakeAvaxUSDCAssetString = "AVAX.USDC-1234"; | ||
const fakeAvaxUSDCAsset = AssetValue.fromStringSync(fakeAvaxUSDCAssetString); | ||
@@ -268,3 +303,3 @@ | ||
expect.objectContaining({ | ||
address: '1234', | ||
address: "1234", | ||
chain: Chain.Avalanche, | ||
@@ -274,4 +309,4 @@ decimal: 18, | ||
isSynthetic: false, | ||
symbol: 'USDC-1234', | ||
ticker: 'USDC', | ||
symbol: "USDC-1234", | ||
ticker: "USDC", | ||
}), | ||
@@ -281,5 +316,5 @@ ); | ||
test('returns proper avax string with address from `@swapkit/tokens` lists', async () => { | ||
test("returns proper avax string with address from `@swapkit/tokens` lists", async () => { | ||
await AssetValue.loadStaticAssets(); | ||
const avaxBTCb = 'AVAX.BTC.b-0x152b9d0fdc40c096757f570a51e494bd4b943e50'; | ||
const avaxBTCb = "AVAX.BTC.b-0x152b9d0fdc40c096757f570a51e494bd4b943e50"; | ||
const AvaxBTCb = AssetValue.fromStringSync(avaxBTCb); | ||
@@ -290,3 +325,3 @@ | ||
expect.objectContaining({ | ||
address: '0x152b9d0fdc40c096757f570a51e494bd4b943e50', | ||
address: "0x152b9d0fdc40c096757f570a51e494bd4b943e50", | ||
chain: Chain.Avalanche, | ||
@@ -296,4 +331,4 @@ decimal: 8, | ||
isSynthetic: false, | ||
symbol: 'BTC.b-0x152b9d0fdc40c096757f570a51e494bd4b943e50', | ||
ticker: 'BTC.b', | ||
symbol: "BTC.b-0x152b9d0fdc40c096757f570a51e494bd4b943e50", | ||
ticker: "BTC.b", | ||
}), | ||
@@ -304,23 +339,89 @@ ); | ||
describe('fromChainOrSignature', () => { | ||
test('creates AssetValue from common asset string or chain', () => { | ||
describe("fromStringWithBaseSync", () => { | ||
test("creates AssetValue from string with base decimals via `@swapkit/tokens` lists", async () => { | ||
await AssetValue.loadStaticAssets(); | ||
const btc = AssetValue.fromStringWithBaseSync("BTC.BTC", 5200000000000, 8); | ||
expect(btc).toBeDefined(); | ||
expect(btc).toEqual( | ||
expect.objectContaining({ | ||
chain: Chain.Bitcoin, | ||
decimal: 8, | ||
isGasAsset: true, | ||
isSynthetic: false, | ||
symbol: "BTC", | ||
ticker: "BTC", | ||
}), | ||
); | ||
expect(btc.getValue("string")).toBe("52000"); | ||
expect(btc.getBaseValue("string")).toBe("5200000000000"); | ||
}); | ||
test("returns safe decimals if string is not in `@swapkit/tokens` lists", async () => { | ||
await AssetValue.loadStaticAssets(); | ||
const fakeAvaxUSDCAssetString = "AVAX.USDC-1234"; | ||
const fakeAvaxUSDCAsset = AssetValue.fromStringWithBaseSync(fakeAvaxUSDCAssetString, 1, 8); | ||
expect(fakeAvaxUSDCAsset).toBeDefined(); | ||
expect(fakeAvaxUSDCAsset).toEqual( | ||
expect.objectContaining({ | ||
address: "1234", | ||
chain: Chain.Avalanche, | ||
decimal: 18, | ||
isGasAsset: false, | ||
isSynthetic: false, | ||
symbol: "USDC-1234", | ||
ticker: "USDC", | ||
}), | ||
); | ||
expect(fakeAvaxUSDCAsset.getValue("string")).toBe("0.00000001"); | ||
expect(fakeAvaxUSDCAsset.getBaseValue("string")).toBe("10000000000"); | ||
}); | ||
test("returns proper avax string with address from `@swapkit/tokens` lists", async () => { | ||
await AssetValue.loadStaticAssets(); | ||
const avaxUSDC = "AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e"; | ||
const AvaxUSDC = AssetValue.fromStringWithBaseSync(avaxUSDC, 100000000, 8); | ||
expect(AvaxUSDC).toBeDefined(); | ||
expect(AvaxUSDC).toEqual( | ||
expect.objectContaining({ | ||
address: "0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
chain: Chain.Avalanche, | ||
decimal: 6, | ||
isGasAsset: false, | ||
isSynthetic: false, | ||
symbol: "USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e", | ||
ticker: "USDC", | ||
}), | ||
); | ||
expect(AvaxUSDC.getValue("string")).toBe("1"); | ||
expect(AvaxUSDC.getBaseValue("string")).toBe("1000000"); | ||
}); | ||
}); | ||
describe("fromChainOrSignature", () => { | ||
test("creates AssetValue from common asset string or chain", () => { | ||
const customBaseAsset = [Chain.Cosmos, Chain.BinanceSmartChain, Chain.THORChain, Chain.Maya]; | ||
Object.values(Chain) | ||
.filter((c) => !customBaseAsset.includes(c)) | ||
.forEach((chain) => { | ||
const asset = AssetValue.fromChainOrSignature(chain); | ||
expect(asset).toEqual( | ||
expect.objectContaining({ | ||
address: undefined, | ||
chain, | ||
decimal: BaseDecimal[chain], | ||
isGasAsset: ![Chain.Arbitrum, Chain.Optimism].includes(chain), | ||
isSynthetic: false, | ||
symbol: chain, | ||
ticker: chain, | ||
type: 'Native', | ||
}), | ||
); | ||
}); | ||
const filteredChains = Object.values(Chain).filter((c) => !customBaseAsset.includes(c)); | ||
for (const chain of filteredChains) { | ||
const asset = AssetValue.fromChainOrSignature(chain); | ||
expect(asset).toEqual( | ||
expect.objectContaining({ | ||
address: undefined, | ||
chain, | ||
decimal: BaseDecimal[chain], | ||
isGasAsset: ![Chain.Arbitrum, Chain.Optimism].includes(chain), | ||
isSynthetic: false, | ||
symbol: chain, | ||
ticker: chain, | ||
type: "Native", | ||
}), | ||
); | ||
} | ||
const cosmosAsset = AssetValue.fromChainOrSignature(Chain.Cosmos); | ||
@@ -334,5 +435,5 @@ expect(cosmosAsset).toEqual( | ||
isSynthetic: false, | ||
symbol: 'ATOM', | ||
ticker: 'ATOM', | ||
type: 'Native', | ||
symbol: "ATOM", | ||
ticker: "ATOM", | ||
type: "Native", | ||
}), | ||
@@ -349,5 +450,5 @@ ); | ||
isSynthetic: false, | ||
symbol: 'BNB', | ||
ticker: 'BNB', | ||
type: 'Native', | ||
symbol: "BNB", | ||
ticker: "BNB", | ||
type: "Native", | ||
}), | ||
@@ -364,5 +465,5 @@ ); | ||
isSynthetic: false, | ||
symbol: 'RUNE', | ||
ticker: 'RUNE', | ||
type: 'Native', | ||
symbol: "RUNE", | ||
ticker: "RUNE", | ||
type: "Native", | ||
}), | ||
@@ -379,12 +480,12 @@ ); | ||
isSynthetic: false, | ||
symbol: 'CACAO', | ||
ticker: 'CACAO', | ||
type: 'Native', | ||
symbol: "CACAO", | ||
ticker: "CACAO", | ||
type: "Native", | ||
}), | ||
); | ||
const thor = AssetValue.fromChainOrSignature('ETH.THOR'); | ||
const thor = AssetValue.fromChainOrSignature("ETH.THOR"); | ||
expect(thor).toEqual( | ||
expect.objectContaining({ | ||
address: '0xa5f2211b9b8170f694421f2046281775e8468044', | ||
address: "0xa5f2211b9b8170f694421f2046281775e8468044", | ||
chain: Chain.Ethereum, | ||
@@ -394,11 +495,11 @@ decimal: 18, | ||
isSynthetic: false, | ||
symbol: 'THOR-0xa5f2211b9b8170f694421f2046281775e8468044', | ||
ticker: 'THOR', | ||
symbol: "THOR-0xa5f2211b9b8170f694421f2046281775e8468044", | ||
ticker: "THOR", | ||
}), | ||
); | ||
const vthor = AssetValue.fromChainOrSignature('ETH.vTHOR'); | ||
const vthor = AssetValue.fromChainOrSignature("ETH.vTHOR"); | ||
expect(vthor).toEqual( | ||
expect.objectContaining({ | ||
address: '0x815c23eca83261b6ec689b60cc4a58b54bc24d8d', | ||
address: "0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", | ||
chain: Chain.Ethereum, | ||
@@ -408,4 +509,4 @@ decimal: 18, | ||
isSynthetic: false, | ||
symbol: 'vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d', | ||
ticker: 'vTHOR', | ||
symbol: "vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", | ||
ticker: "vTHOR", | ||
}), | ||
@@ -416,4 +517,4 @@ ); | ||
describe('loadStaticAssets', () => { | ||
test('loads static assets from `@swapkit/tokens` lists', async () => { | ||
describe("loadStaticAssets", () => { | ||
test("loads static assets from `@swapkit/tokens` lists", async () => { | ||
// Dummy test - think of sth more meaningful | ||
@@ -426,19 +527,19 @@ const { ok } = await AssetValue.loadStaticAssets(); | ||
describe('getMinAmountByChain', () => { | ||
test('returns min amount for chain', () => { | ||
expect(getMinAmountByChain(Chain.THORChain).getValue('string')).toBe('0'); | ||
expect(getMinAmountByChain(Chain.Maya).getValue('string')).toBe('0'); | ||
expect(getMinAmountByChain(Chain.Cosmos).getValue('string')).toBe('0.000001'); | ||
describe("getMinAmountByChain", () => { | ||
test("returns min amount for chain", () => { | ||
expect(getMinAmountByChain(Chain.THORChain).getValue("string")).toBe("0"); | ||
expect(getMinAmountByChain(Chain.Maya).getValue("string")).toBe("0"); | ||
expect(getMinAmountByChain(Chain.Cosmos).getValue("string")).toBe("0.000001"); | ||
expect(getMinAmountByChain(Chain.Bitcoin).getValue('string')).toBe('0.00010001'); | ||
expect(getMinAmountByChain(Chain.Litecoin).getValue('string')).toBe('0.00010001'); | ||
expect(getMinAmountByChain(Chain.BitcoinCash).getValue('string')).toBe('0.00010001'); | ||
expect(getMinAmountByChain(Chain.Dogecoin).getValue('string')).toBe('1.00000001'); | ||
expect(getMinAmountByChain(Chain.Bitcoin).getValue("string")).toBe("0.00010001"); | ||
expect(getMinAmountByChain(Chain.Litecoin).getValue("string")).toBe("0.00010001"); | ||
expect(getMinAmountByChain(Chain.BitcoinCash).getValue("string")).toBe("0.00010001"); | ||
expect(getMinAmountByChain(Chain.Dogecoin).getValue("string")).toBe("1.00000001"); | ||
expect(getMinAmountByChain(Chain.BinanceSmartChain).getValue('string')).toBe('0.00000001'); | ||
expect(getMinAmountByChain(Chain.Ethereum).getValue('string')).toBe('0.00000001'); | ||
expect(getMinAmountByChain(Chain.Avalanche).getValue('string')).toBe('0.00000001'); | ||
expect(getMinAmountByChain(Chain.Arbitrum).getValue('string')).toBe('0.00000001'); | ||
expect(getMinAmountByChain(Chain.Optimism).getValue('string')).toBe('0.00000001'); | ||
expect(getMinAmountByChain(Chain.BinanceSmartChain).getValue("string")).toBe("0.00000001"); | ||
expect(getMinAmountByChain(Chain.Ethereum).getValue("string")).toBe("0.00000001"); | ||
expect(getMinAmountByChain(Chain.Avalanche).getValue("string")).toBe("0.00000001"); | ||
expect(getMinAmountByChain(Chain.Arbitrum).getValue("string")).toBe("0.00000001"); | ||
expect(getMinAmountByChain(Chain.Optimism).getValue("string")).toBe("0.00000001"); | ||
}); | ||
}); |
@@ -1,8 +0,8 @@ | ||
import { describe, expect, test } from 'vitest'; | ||
import { describe, expect, test } from "vitest"; | ||
import { formatBigIntToSafeValue } from '../bigIntArithmetics.ts'; | ||
import { formatBigIntToSafeValue } from "../bigIntArithmetics.ts"; | ||
describe('BigIntArithmatics', () => { | ||
describe('formatBigIntToSafeValue', () => { | ||
test('parse bigint with decimals to string', () => { | ||
describe("BigIntArithmatics", () => { | ||
describe("formatBigIntToSafeValue", () => { | ||
test("parse bigint with decimals to string", () => { | ||
const safeValue1 = formatBigIntToSafeValue({ | ||
@@ -13,3 +13,3 @@ value: BigInt(0), | ||
}); | ||
expect(safeValue1).toBe('0'); | ||
expect(safeValue1).toBe("0"); | ||
@@ -21,3 +21,3 @@ const safeValue2 = formatBigIntToSafeValue({ | ||
}); | ||
expect(safeValue2).toBe('15'); | ||
expect(safeValue2).toBe("15"); | ||
@@ -29,5 +29,5 @@ const safeValue3 = formatBigIntToSafeValue({ | ||
}); | ||
expect(safeValue3).toBe('12345.6789'); | ||
expect(safeValue3).toBe("12345.6789"); | ||
}); | ||
}); | ||
}); |
@@ -1,16 +0,16 @@ | ||
import { describe, expect, test } from 'vitest'; | ||
import { describe, expect, test } from "vitest"; | ||
import { SwapKitNumber } from '../swapKitNumber.ts'; | ||
import { SwapKitNumber } from "../swapKitNumber.ts"; | ||
describe('SwapKitNumber', () => { | ||
describe('constructors', () => { | ||
test('creates numbers correctly', () => { | ||
describe("SwapKitNumber", () => { | ||
describe("constructors", () => { | ||
test("creates numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(1); | ||
expect(skNumber1.getValue('string')).toBe('1'); | ||
expect(skNumber1.getValue('number')).toBe(1); | ||
expect(skNumber1.getBaseValue('bigint')).toBe(100000000n); | ||
expect(skNumber1.getValue("string")).toBe("1"); | ||
expect(skNumber1.getValue("number")).toBe(1); | ||
expect(skNumber1.getBaseValue("bigint")).toBe(100000000n); | ||
const skNumber2 = new SwapKitNumber('1'); | ||
expect(skNumber2.getValue('string')).toBe('1'); | ||
expect(skNumber2.getBaseValue('bigint')).toBe(100000000n); | ||
const skNumber2 = new SwapKitNumber("1"); | ||
expect(skNumber2.getValue("string")).toBe("1"); | ||
expect(skNumber2.getBaseValue("bigint")).toBe(100000000n); | ||
@@ -20,35 +20,35 @@ /** | ||
*/ | ||
const skNumber3 = new SwapKitNumber('0.0000000001'); | ||
expect(skNumber3.getValue('string')).toBe('0.0000000001'); | ||
expect(skNumber3.getBaseValue('bigint')).toBe(0n); | ||
const skNumber3 = new SwapKitNumber("0.0000000001"); | ||
expect(skNumber3.getValue("string")).toBe("0.0000000001"); | ||
expect(skNumber3.getBaseValue("bigint")).toBe(0n); | ||
const skNumber4 = new SwapKitNumber({ value: '0.0000000001', decimal: 10 }); | ||
expect(skNumber4.getValue('string')).toBe('0.0000000001'); | ||
expect(skNumber4.getBaseValue('bigint')).toBe(1n); | ||
const skNumber4 = new SwapKitNumber({ value: "0.0000000001", decimal: 10 }); | ||
expect(skNumber4.getValue("string")).toBe("0.0000000001"); | ||
expect(skNumber4.getBaseValue("bigint")).toBe(1n); | ||
const skNumber5 = new SwapKitNumber({ value: 0.1005, decimal: 3 }); | ||
expect(skNumber5.getValue('string')).toBe('0.101'); | ||
expect(skNumber5.getBaseValue('bigint')).toBe(100n); | ||
expect(skNumber5.getValue("string")).toBe("0.101"); | ||
expect(skNumber5.getBaseValue("bigint")).toBe(100n); | ||
const skNumber6 = new SwapKitNumber({ value: -0.1005, decimal: 3 }); | ||
expect(skNumber6.getValue('string')).toBe('-0.101'); | ||
expect(skNumber6.getBaseValue('bigint')).toBe(-100n); | ||
expect(skNumber6.getValue("string")).toBe("-0.101"); | ||
expect(skNumber6.getBaseValue("bigint")).toBe(-100n); | ||
expect(skNumber6.decimal).toBe(3); | ||
expect(skNumber6.getValue('number')).toBe(-0.101); | ||
expect(skNumber6.getValue("number")).toBe(-0.101); | ||
expect(skNumber6.decimalMultiplier).toBe(100000000n); | ||
}); | ||
test('creates SwapKitInstance from BigInt: (12.345678901234, decimals: 12)', () => { | ||
test("creates SwapKitInstance from BigInt: (12.345678901234, decimals: 12)", () => { | ||
const skNumber = SwapKitNumber.fromBigInt(12345678901234n, 12); | ||
expect(skNumber.getValue('string')).toBe('12.345678901234'); | ||
expect(skNumber.getBaseValue('bigint')).toBe(12345678901234n); | ||
expect(skNumber.getValue("string")).toBe("12.345678901234"); | ||
expect(skNumber.getBaseValue("bigint")).toBe(12345678901234n); | ||
}); | ||
}); | ||
describe('shiftDecimals', () => { | ||
test('shifts up and bumps number', () => { | ||
describe("shiftDecimals", () => { | ||
test("shifts up and bumps number", () => { | ||
const skNumber = new SwapKitNumber(1); | ||
expect(skNumber.getValue('string')).toBe('1'); | ||
expect(skNumber.getBaseValue('bigint')).toBe(100000000n); | ||
expect(skNumber.getValue("string")).toBe("1"); | ||
expect(skNumber.getBaseValue("bigint")).toBe(100000000n); | ||
@@ -61,10 +61,10 @@ const shiftedSkNumber = SwapKitNumber.shiftDecimals({ | ||
expect(shiftedSkNumber.getValue('string')).toBe('1'); | ||
expect(shiftedSkNumber.getBaseValue('bigint')).toBe(1000000n); | ||
expect(shiftedSkNumber.getValue("string")).toBe("1"); | ||
expect(shiftedSkNumber.getBaseValue("bigint")).toBe(1000000n); | ||
}); | ||
test('shifts down and rounds down number', () => { | ||
test("shifts down and rounds down number", () => { | ||
const skNumber = new SwapKitNumber(2.12345678); | ||
expect(skNumber.getValue('string')).toBe('2.12345678'); | ||
expect(skNumber.getBaseValue('bigint')).toBe(212345678n); | ||
expect(skNumber.getValue("string")).toBe("2.12345678"); | ||
expect(skNumber.getBaseValue("bigint")).toBe(212345678n); | ||
@@ -77,8 +77,8 @@ const shiftedSkNumber = SwapKitNumber.shiftDecimals({ | ||
expect(shiftedSkNumber.getValue('string')).toBe('2.123456'); | ||
expect(shiftedSkNumber.getBaseValue('bigint')).toBe(2123456n); | ||
expect(shiftedSkNumber.getValue("string")).toBe("2.123456"); | ||
expect(shiftedSkNumber.getBaseValue("bigint")).toBe(2123456n); | ||
}); | ||
test('shift eth from 18 to 8', () => { | ||
const skNumber = new SwapKitNumber({ value: '0.2', decimal: 18 }); | ||
test("shift eth from 18 to 8", () => { | ||
const skNumber = new SwapKitNumber({ value: "0.2", decimal: 18 }); | ||
@@ -91,36 +91,36 @@ const shiftedSkNumber = SwapKitNumber.shiftDecimals({ | ||
expect(shiftedSkNumber.getValue('string')).toBe('0.2'); | ||
expect(shiftedSkNumber.getBaseValue('bigint')).toBe(20000000n); | ||
expect(shiftedSkNumber.getValue("string")).toBe("0.2"); | ||
expect(shiftedSkNumber.getBaseValue("bigint")).toBe(20000000n); | ||
}); | ||
}); | ||
describe('getValue', () => { | ||
describe('string', () => { | ||
test('returns string value', () => { | ||
describe("getValue", () => { | ||
describe("string", () => { | ||
test("returns string value", () => { | ||
const skNumber = new SwapKitNumber(1); | ||
expect(skNumber.getValue('string')).toBe('1'); | ||
expect(skNumber.getValue("string")).toBe("1"); | ||
}); | ||
test('returns string value with decimals', () => { | ||
test("returns string value with decimals", () => { | ||
const skNumber = new SwapKitNumber(0.01); | ||
expect(skNumber.getValue('string')).toBe('0.01'); | ||
expect(skNumber.getValue("string")).toBe("0.01"); | ||
}); | ||
}); | ||
describe('number', () => { | ||
test('returns number value', () => { | ||
describe("number", () => { | ||
test("returns number value", () => { | ||
const skNumber = new SwapKitNumber(1); | ||
expect(skNumber.getValue('number')).toBe(1); | ||
expect(skNumber.getValue("number")).toBe(1); | ||
}); | ||
test('returns number value with decimals', () => { | ||
test("returns number value with decimals", () => { | ||
const skNumber = new SwapKitNumber(0.01); | ||
expect(skNumber.getValue('number')).toBe(0.01); | ||
expect(skNumber.getValue("number")).toBe(0.01); | ||
}); | ||
}); | ||
describe('bigint', () => { | ||
test('returns bigint value', () => { | ||
describe("bigint", () => { | ||
test("returns bigint value", () => { | ||
const skNumber = new SwapKitNumber(1); | ||
expect(skNumber.getBaseValue('bigint')).toBe(100000000n); | ||
expect(skNumber.getBaseValue("bigint")).toBe(100000000n); | ||
}); | ||
@@ -130,41 +130,41 @@ }); | ||
describe('toSignificant', () => { | ||
describe('normal cases', () => { | ||
test('returns first significant number of digits', () => { | ||
describe("toSignificant", () => { | ||
describe("normal cases", () => { | ||
test("returns first significant number of digits", () => { | ||
const usdLikeNumber = new SwapKitNumber(1234.5678); | ||
expect(usdLikeNumber.toSignificant(2)).toBe('1200'); | ||
expect(usdLikeNumber.toSignificant(3)).toBe('1230'); | ||
expect(usdLikeNumber.toSignificant(4)).toBe('1234'); | ||
expect(usdLikeNumber.toSignificant(5)).toBe('1234.5'); | ||
expect(usdLikeNumber.toSignificant(6)).toBe('1234.56'); | ||
expect(usdLikeNumber.toSignificant(7)).toBe('1234.567'); | ||
expect(usdLikeNumber.toSignificant(8)).toBe('1234.5678'); | ||
expect(usdLikeNumber.toSignificant(2)).toBe("1200"); | ||
expect(usdLikeNumber.toSignificant(3)).toBe("1230"); | ||
expect(usdLikeNumber.toSignificant(4)).toBe("1234"); | ||
expect(usdLikeNumber.toSignificant(5)).toBe("1234.5"); | ||
expect(usdLikeNumber.toSignificant(6)).toBe("1234.56"); | ||
expect(usdLikeNumber.toSignificant(7)).toBe("1234.567"); | ||
expect(usdLikeNumber.toSignificant(8)).toBe("1234.5678"); | ||
const btcLikeNumber = new SwapKitNumber(0.00005678); | ||
expect(btcLikeNumber.toSignificant(2)).toBe('0.000056'); | ||
expect(btcLikeNumber.toSignificant(3)).toBe('0.0000567'); | ||
expect(btcLikeNumber.toSignificant(4)).toBe('0.00005678'); | ||
expect(btcLikeNumber.toSignificant(5)).toBe('0.00005678'); | ||
expect(btcLikeNumber.toSignificant(8)).toBe('0.00005678'); | ||
expect(btcLikeNumber.toSignificant(2)).toBe("0.000056"); | ||
expect(btcLikeNumber.toSignificant(3)).toBe("0.0000567"); | ||
expect(btcLikeNumber.toSignificant(4)).toBe("0.00005678"); | ||
expect(btcLikeNumber.toSignificant(5)).toBe("0.00005678"); | ||
expect(btcLikeNumber.toSignificant(8)).toBe("0.00005678"); | ||
}); | ||
}); | ||
describe('custom decimals', () => { | ||
test('returns first significant number of digits', () => { | ||
describe("custom decimals", () => { | ||
test("returns first significant number of digits", () => { | ||
const usdLikeNumber = new SwapKitNumber({ value: 1234.5678, decimal: 2 }); | ||
expect(usdLikeNumber.toSignificant(2)).toBe('1200'); | ||
expect(usdLikeNumber.toSignificant(3)).toBe('1230'); | ||
expect(usdLikeNumber.toSignificant(4)).toBe('1234'); | ||
expect(usdLikeNumber.toSignificant(5)).toBe('1234.5'); | ||
expect(usdLikeNumber.toSignificant(6)).toBe('1234.57'); | ||
expect(usdLikeNumber.toSignificant(7)).toBe('1234.57'); | ||
expect(usdLikeNumber.toSignificant(8)).toBe('1234.57'); | ||
expect(usdLikeNumber.toSignificant(2)).toBe("1200"); | ||
expect(usdLikeNumber.toSignificant(3)).toBe("1230"); | ||
expect(usdLikeNumber.toSignificant(4)).toBe("1234"); | ||
expect(usdLikeNumber.toSignificant(5)).toBe("1234.5"); | ||
expect(usdLikeNumber.toSignificant(6)).toBe("1234.57"); | ||
expect(usdLikeNumber.toSignificant(7)).toBe("1234.57"); | ||
expect(usdLikeNumber.toSignificant(8)).toBe("1234.57"); | ||
const ethLikeNumber = new SwapKitNumber({ value: 0.00005678, decimal: 18 }); | ||
expect(ethLikeNumber.toSignificant(2)).toBe('0.000056'); | ||
expect(ethLikeNumber.toSignificant(3)).toBe('0.0000567'); | ||
expect(ethLikeNumber.toSignificant(4)).toBe('0.00005678'); | ||
expect(ethLikeNumber.toSignificant(5)).toBe('0.00005678'); | ||
expect(ethLikeNumber.toSignificant(8)).toBe('0.00005678'); | ||
expect(ethLikeNumber.toSignificant(18)).toBe('0.00005678'); | ||
expect(ethLikeNumber.toSignificant(2)).toBe("0.000056"); | ||
expect(ethLikeNumber.toSignificant(3)).toBe("0.0000567"); | ||
expect(ethLikeNumber.toSignificant(4)).toBe("0.00005678"); | ||
expect(ethLikeNumber.toSignificant(5)).toBe("0.00005678"); | ||
expect(ethLikeNumber.toSignificant(8)).toBe("0.00005678"); | ||
expect(ethLikeNumber.toSignificant(18)).toBe("0.00005678"); | ||
}); | ||
@@ -174,158 +174,158 @@ }); | ||
describe('toAbbreviation', () => { | ||
test('returns abbreviation with up to 3 integer digits', () => { | ||
describe("toAbbreviation", () => { | ||
test("returns abbreviation with up to 3 integer digits", () => { | ||
const skNumber = new SwapKitNumber(1234.5678); | ||
expect(skNumber.toAbbreviation()).toBe('1.23K'); | ||
expect(skNumber.toAbbreviation()).toBe("1.23K"); | ||
const skNumber2 = new SwapKitNumber(1234567.5678); | ||
expect(skNumber2.toAbbreviation()).toBe('1.23M'); | ||
expect(skNumber2.toAbbreviation()).toBe("1.23M"); | ||
const skNumber3 = new SwapKitNumber(1234567890.5678); | ||
expect(skNumber3.toAbbreviation()).toBe('1.23B'); | ||
expect(skNumber3.toAbbreviation()).toBe("1.23B"); | ||
const skNumber4 = new SwapKitNumber(1234567890123.5678); | ||
expect(skNumber4.toAbbreviation()).toBe('1.23T'); | ||
const skNumber4 = new SwapKitNumber("1234567890123.5678"); | ||
expect(skNumber4.toAbbreviation()).toBe("1.23T"); | ||
const skNumber5 = new SwapKitNumber(1234567890123456.5678); | ||
expect(skNumber5.toAbbreviation()).toBe('1.23Q'); | ||
const skNumber5 = new SwapKitNumber("1234567890123456.5678"); | ||
expect(skNumber5.toAbbreviation()).toBe("1.23Q"); | ||
const skNumber6 = new SwapKitNumber(1234567890123456789.5678); | ||
expect(skNumber6.toAbbreviation()).toBe('1.23Qi'); | ||
const skNumber6 = new SwapKitNumber("1234567890123456789.5678"); | ||
expect(skNumber6.toAbbreviation()).toBe("1.23Qi"); | ||
const skNumber7 = new SwapKitNumber(1234567890123456789012.5678); | ||
expect(skNumber7.toAbbreviation()).toBe('1.23S'); | ||
const skNumber7 = new SwapKitNumber("1234567890123456789012.5678"); | ||
expect(skNumber7.toAbbreviation()).toBe("1.23S"); | ||
const skNumber8 = new SwapKitNumber(1234.5678); | ||
expect(skNumber8.toAbbreviation(0)).toBe('1K'); | ||
expect(skNumber8.toAbbreviation(0)).toBe("1K"); | ||
const skNumber9 = new SwapKitNumber(1234.5678); | ||
expect(skNumber9.toAbbreviation(1)).toBe('1.2K'); | ||
expect(skNumber9.toAbbreviation(1)).toBe("1.2K"); | ||
const skNumber10 = new SwapKitNumber(123456.78); | ||
expect(skNumber10.toAbbreviation()).toBe('123.46K'); | ||
expect(skNumber10.toAbbreviation()).toBe("123.46K"); | ||
}); | ||
}); | ||
describe('toCurrency', () => { | ||
test('returns abbreviation with up to 3 integer digits', () => { | ||
describe("toCurrency", () => { | ||
test("returns abbreviation with up to 3 integer digits", () => { | ||
const skNumber = new SwapKitNumber(1234.5678); | ||
expect(skNumber.toCurrency()).toBe('$1,234.56'); | ||
expect(skNumber.toCurrency()).toBe("$1,234.56"); | ||
expect( | ||
skNumber.toCurrency('€', { | ||
decimalSeparator: ',', | ||
thousandSeparator: ' ', | ||
currencyPosition: 'end', | ||
skNumber.toCurrency("€", { | ||
decimalSeparator: ",", | ||
thousandSeparator: " ", | ||
currencyPosition: "end", | ||
}), | ||
).toBe('1 234,56€'); | ||
).toBe("1 234,56€"); | ||
const skNumber2 = new SwapKitNumber(0.5678); | ||
expect(skNumber2.toCurrency()).toBe('$0.5678'); | ||
expect(skNumber2.toCurrency()).toBe("$0.5678"); | ||
expect( | ||
skNumber2.toCurrency('€', { | ||
decimalSeparator: ',', | ||
currencyPosition: 'end', | ||
skNumber2.toCurrency("€", { | ||
decimalSeparator: ",", | ||
currencyPosition: "end", | ||
}), | ||
).toBe('0,5678€'); | ||
).toBe("0,5678€"); | ||
const skNumber3 = new SwapKitNumber(0.00005678); | ||
expect(skNumber3.toCurrency()).toBe('$0.000057'); | ||
expect(skNumber3.toCurrency()).toBe("$0.000057"); | ||
expect( | ||
skNumber3.toCurrency('€', { | ||
decimalSeparator: ',', | ||
thousandSeparator: ' ', | ||
currencyPosition: 'end', | ||
skNumber3.toCurrency("€", { | ||
decimalSeparator: ",", | ||
thousandSeparator: " ", | ||
currencyPosition: "end", | ||
}), | ||
).toBe('0,000057€'); | ||
).toBe("0,000057€"); | ||
const skNumber4 = new SwapKitNumber(12345); | ||
expect(skNumber4.toCurrency()).toBe('$12,345'); | ||
expect(skNumber4.toCurrency()).toBe("$12,345"); | ||
}); | ||
}); | ||
describe('add', () => { | ||
test('adds same type numbers correctly', () => { | ||
describe("add", () => { | ||
test("adds same type numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber3 = new SwapKitNumber('0.5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
const skNumber3 = new SwapKitNumber("0.5"); | ||
const result = skNumber1.add(skNumber2, skNumber3); | ||
expect(result.getValue('string')).toBe('15.5'); | ||
expect(result.getBaseValue('bigint')).toBe(1550000000n); | ||
expect(result.getValue("string")).toBe("15.5"); | ||
expect(result.getBaseValue("bigint")).toBe(1550000000n); | ||
}); | ||
test('adds different type numbers correctly', () => { | ||
test("adds different type numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const result = skNumber1.add(6, '0.5'); | ||
const result = skNumber1.add(6, "0.5"); | ||
expect(result.getValue('string')).toBe('16.5'); | ||
expect(result.getBaseValue('bigint')).toBe(1650000000n); | ||
expect(result.getValue("string")).toBe("16.5"); | ||
expect(result.getBaseValue("bigint")).toBe(1650000000n); | ||
}); | ||
test('adds large decimal numbers correctly', () => { | ||
test("adds large decimal numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(0.0000000001); | ||
const result = skNumber1.add(6.000000000001, '0.0000000000000005'); | ||
expect(result.getValue('string')).toBe('6.0000000001010005'); | ||
expect(result.getBaseValue('bigint')).toBe(600000000n); | ||
const result = skNumber1.add(6.000000000001, "0.0000000000000005"); | ||
expect(result.getValue("string")).toBe("6.0000000001010005"); | ||
expect(result.getBaseValue("bigint")).toBe(600000000n); | ||
}); | ||
}); | ||
describe('sub', () => { | ||
test('subtracts same type numbers correctly', () => { | ||
describe("sub", () => { | ||
test("subtracts same type numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
const skNumber3 = new SwapKitNumber(0.5); | ||
const result = skNumber1.sub(skNumber2, skNumber3); | ||
expect(result.getValue('string')).toBe('4.5'); | ||
expect(result.getBaseValue('bigint')).toBe(450000000n); | ||
expect(result.getValue("string")).toBe("4.5"); | ||
expect(result.getBaseValue("bigint")).toBe(450000000n); | ||
}); | ||
test('subtracts different type numbers correctly', () => { | ||
test("subtracts different type numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const result = skNumber1.sub(6, '0.5'); | ||
const result = skNumber1.sub(6, "0.5"); | ||
expect(result.getValue('string')).toBe('3.5'); | ||
expect(result.getBaseValue('bigint')).toBe(350000000n); | ||
expect(result.getValue("string")).toBe("3.5"); | ||
expect(result.getBaseValue("bigint")).toBe(350000000n); | ||
}); | ||
test('can process negative results', () => { | ||
test("can process negative results", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const result0 = skNumber1.sub(10); | ||
const resultMinus = result0.sub('10'); | ||
const resultMinus = result0.sub("10"); | ||
expect(result0.getValue('string')).toBe('0'); | ||
expect(resultMinus.getValue('string')).toBe('-10'); | ||
expect(result0.getBaseValue('bigint')).toBe(0n); | ||
expect(resultMinus.getBaseValue('bigint')).toBe(-1000000000n); | ||
expect(result0.getValue("string")).toBe("0"); | ||
expect(resultMinus.getValue("string")).toBe("-10"); | ||
expect(result0.getBaseValue("bigint")).toBe(0n); | ||
expect(resultMinus.getBaseValue("bigint")).toBe(-1000000000n); | ||
}); | ||
}); | ||
describe('mul', () => { | ||
test('multiplies same type numbers correctly', () => { | ||
describe("mul", () => { | ||
test("multiplies same type numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
const skNumber3 = new SwapKitNumber(0.5); | ||
const result = skNumber1.mul(skNumber2, skNumber3); | ||
expect(result.getValue('string')).toBe('25'); | ||
expect(result.getBaseValue('bigint')).toBe(2500000000n); | ||
expect(result.getValue("string")).toBe("25"); | ||
expect(result.getBaseValue("bigint")).toBe(2500000000n); | ||
}); | ||
test('multiplies different type numbers correctly', () => { | ||
test("multiplies different type numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const result = skNumber1.mul(6, '0.5'); | ||
const result = skNumber1.mul(6, "0.5"); | ||
expect(result.getValue('string')).toBe('30'); | ||
expect(result.getBaseValue('bigint')).toBe(3000000000n); | ||
expect(result.getValue("string")).toBe("30"); | ||
expect(result.getBaseValue("bigint")).toBe(3000000000n); | ||
}); | ||
test('multiplies numbers correctly if decimals of SKN is lower than number multiplied with', () => { | ||
test("multiplies numbers correctly if decimals of SKN is lower than number multiplied with", () => { | ||
const skNumber1 = new SwapKitNumber({ value: 1000000, decimal: 4 }); | ||
const result = skNumber1.mul('0.00001'); | ||
const result = skNumber1.mul("0.00001"); | ||
expect(result.getValue('string')).toBe('10'); | ||
expect(result.getBaseValue('bigint')).toBe(100000n); | ||
expect(result.getValue("string")).toBe("10"); | ||
expect(result.getBaseValue("bigint")).toBe(100000n); | ||
}); | ||
test('should correctly round the result of multiplication', () => { | ||
test("should correctly round the result of multiplication", () => { | ||
const skNumber1 = new SwapKitNumber({ decimal: 3, value: 1.23 }); | ||
@@ -337,4 +337,4 @@ const skNumber2 = new SwapKitNumber({ decimal: 4, value: 4.56 }); | ||
// The exact result of 1.23 * 4.56 is 5.6088 | ||
expect(result.getValue('string')).toBe('5.609'); | ||
expect(result.getBaseValue('bigint')).toBe(5608n); | ||
expect(result.getValue("string")).toBe("5.609"); | ||
expect(result.getBaseValue("bigint")).toBe(5608n); | ||
@@ -348,16 +348,16 @@ const skNumber3 = new SwapKitNumber({ decimal: 2, value: 1.23 }); | ||
// If we round it to 2 decimal places, we should get 5.61 | ||
expect(result2.getValue('string')).toBe('-1.52'); | ||
expect(result2.getBaseValue('bigint')).toBe(-151n); | ||
expect(result2.getValue("string")).toBe("-1.52"); | ||
expect(result2.getBaseValue("bigint")).toBe(-151n); | ||
}); | ||
}); | ||
describe('div', () => { | ||
test('divides same type numbers correctly', () => { | ||
describe("div", () => { | ||
test("divides same type numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
const skNumber3 = new SwapKitNumber(0.5); | ||
const result = skNumber1.div(skNumber2, skNumber3); | ||
expect(result.getValue('string')).toBe('4'); | ||
expect(result.getBaseValue('bigint')).toBe(400000000n); | ||
expect(result.getValue("string")).toBe("4"); | ||
expect(result.getBaseValue("bigint")).toBe(400000000n); | ||
@@ -367,33 +367,33 @@ const skNumber4 = new SwapKitNumber(10.12); | ||
expect(result2.getValue('string')).toBe('101200'); | ||
expect(result2.getBaseValue('bigint')).toBe(10120000000000n); | ||
expect(result2.getValue("string")).toBe("101200"); | ||
expect(result2.getBaseValue("bigint")).toBe(10120000000000n); | ||
}); | ||
test('divides different type numbers correctly', () => { | ||
test("divides different type numbers correctly", () => { | ||
const skNumber1 = new SwapKitNumber(20); | ||
const result = skNumber1.div(5, '0.5'); | ||
const result = skNumber1.div(5, "0.5"); | ||
expect(result.getValue('string')).toBe('8'); | ||
expect(result.getBaseValue('bigint')).toBe(800000000n); | ||
expect(result.getValue("string")).toBe("8"); | ||
expect(result.getBaseValue("bigint")).toBe(800000000n); | ||
}); | ||
test('divides different type numbers correctly when decimal is set', () => { | ||
const skNumber1 = new SwapKitNumber({ value: '1.2', decimal: 2 }); | ||
test("divides different type numbers correctly when decimal is set", () => { | ||
const skNumber1 = new SwapKitNumber({ value: "1.2", decimal: 2 }); | ||
const result = skNumber1.div(0.001); | ||
expect(result.getValue('string')).toBe('1200'); | ||
expect(result.getBaseValue('bigint')).toBe(120000n); | ||
expect(result.getValue("string")).toBe("1200"); | ||
expect(result.getBaseValue("bigint")).toBe(120000n); | ||
}); | ||
test('divides smaller number by larger number', () => { | ||
test("divides smaller number by larger number", () => { | ||
const skNumber1 = new SwapKitNumber(1); | ||
const result = skNumber1.div(2); | ||
expect(result.getValue('string')).toBe('0.5'); | ||
expect(result.getBaseValue('bigint')).toBe(50000000n); | ||
expect(result.getValue("string")).toBe("0.5"); | ||
expect(result.getBaseValue("bigint")).toBe(50000000n); | ||
}); | ||
test('divides a number with 18 decimals by a negative number with less decimals', () => { | ||
const skNumber1 = new SwapKitNumber({ value: '1.000000000000000010', decimal: 18 }); | ||
const skNumber2 = new SwapKitNumber({ value: '-2', decimal: 1 }); | ||
test("divides a number with 18 decimals by a negative number with less decimals", () => { | ||
const skNumber1 = new SwapKitNumber({ value: "1.000000000000000010", decimal: 18 }); | ||
const skNumber2 = new SwapKitNumber({ value: "-2", decimal: 1 }); | ||
@@ -403,9 +403,9 @@ const result = skNumber1.div(skNumber2); | ||
// The exact result of 1.000000000000000010 / -2 is -0.500000000000000005 | ||
expect(result.getValue('string')).toBe('-0.500000000000000005'); | ||
expect(result.getBaseValue('bigint')).toBe(-500000000000000005n); | ||
expect(result.getValue("string")).toBe("-0.500000000000000005"); | ||
expect(result.getBaseValue("bigint")).toBe(-500000000000000005n); | ||
}); | ||
test('divides a number with 2 decimals by a negative number with more decimals', () => { | ||
const skNumber1 = new SwapKitNumber({ value: '2', decimal: 2 }); | ||
const skNumber2 = new SwapKitNumber({ value: '-0.000005', decimal: 18 }); | ||
test("divides a number with 2 decimals by a negative number with more decimals", () => { | ||
const skNumber1 = new SwapKitNumber({ value: "2", decimal: 2 }); | ||
const skNumber2 = new SwapKitNumber({ value: "-0.000005", decimal: 18 }); | ||
@@ -415,9 +415,9 @@ const result = skNumber1.div(skNumber2); | ||
// The exact result of 2 / -0.000005 is -400000 | ||
expect(result.getValue('string')).toBe('-400000'); | ||
expect(result.getBaseValue('bigint')).toBe(-40000000n); | ||
expect(result.getValue("string")).toBe("-400000"); | ||
expect(result.getBaseValue("bigint")).toBe(-40000000n); | ||
}); | ||
}); | ||
describe('shitcoin cases', () => { | ||
test('multiply huge numbers', () => { | ||
describe("shitcoin cases", () => { | ||
test("multiply huge numbers", () => { | ||
const skNumber1 = new SwapKitNumber({ value: 1_000_000_000_000_001, decimal: 18 }); | ||
@@ -427,7 +427,7 @@ const skNumber2 = new SwapKitNumber({ value: 987_654_321_000, decimal: 18 }); | ||
const result = skNumber1.mul(skNumber2); | ||
expect(result.getValue('string')).toBe('987654321000000987654321000'); | ||
expect(result.getBaseValue('bigint')).toBe(987654321000000987654321000000000000000000000n); | ||
expect(result.getValue("string")).toBe("987654321000000987654321000"); | ||
expect(result.getBaseValue("bigint")).toBe(987654321000000987654321000000000000000000000n); | ||
}); | ||
test('divide huge numbers', () => { | ||
test("divide huge numbers", () => { | ||
const skNumber1 = new SwapKitNumber({ value: 1_000_000_000_000_001, decimal: 18 }); | ||
@@ -437,9 +437,9 @@ const skNumber2 = new SwapKitNumber({ value: 987_654_321_000, decimal: 18 }); | ||
const result = skNumber1.div(skNumber2); | ||
expect(result.getValue('string')).toBe('1012.4999999873447625'); | ||
expect(result.getBaseValue('bigint')).toBe(1012499999987344762500n); | ||
expect(result.getValue("string")).toBe("1012.4999999873447625"); | ||
expect(result.getBaseValue("bigint")).toBe(1012499999987344762500n); | ||
}); | ||
}); | ||
describe('extending multiplier without loosing precision', () => { | ||
test('edge case 1', () => { | ||
describe("extending multiplier without loosing precision", () => { | ||
test("edge case 1", () => { | ||
const asset1 = new SwapKitNumber({ value: 41.90963702, decimal: 8 }); | ||
@@ -450,19 +450,19 @@ const multiplier = 5.337952274462478; | ||
expect(result.getValue('string')).toBe('2.12539953'); | ||
expect(result.getValue("string")).toBe("2.12539953"); | ||
}); | ||
test('edge case 2', () => { | ||
const asset1 = new SwapKitNumber('41.90963702'); | ||
const multiplier = new SwapKitNumber('5.337952274462478'); | ||
const divider = new SwapKitNumber('105.2562773915526'); | ||
test("edge case 2", () => { | ||
const asset1 = new SwapKitNumber("41.90963702"); | ||
const multiplier = new SwapKitNumber("5.337952274462478"); | ||
const divider = new SwapKitNumber("105.2562773915526"); | ||
const result = asset1.mul(multiplier).div(divider); | ||
expect(result.getValue('string')).toBe('2.125399527674726'); | ||
expect(result.getValue("string")).toBe("2.125399527674726"); | ||
}); | ||
}); | ||
describe('gt', () => { | ||
test('greater than', () => { | ||
describe("gt", () => { | ||
test("greater than", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
@@ -475,3 +475,3 @@ expect(skNumber1.gt(skNumber2)).toBe(true); | ||
const skNumber1 = new SwapKitNumber({ value: 10, decimal: 18 }); | ||
const skNumber2 = new SwapKitNumber({ value: '50', decimal: 8 }); | ||
const skNumber2 = new SwapKitNumber({ value: "50", decimal: 8 }); | ||
@@ -483,6 +483,6 @@ expect(skNumber1.lt(skNumber2)).toBe(true); | ||
describe('gte', () => { | ||
test('greater than or equal', () => { | ||
describe("gte", () => { | ||
test("greater than or equal", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
@@ -495,6 +495,6 @@ expect(skNumber1.gte(skNumber2)).toBe(true); | ||
describe('lt', () => { | ||
test('less than', () => { | ||
describe("lt", () => { | ||
test("less than", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
@@ -506,6 +506,6 @@ expect(skNumber1.lt(skNumber2)).toBe(false); | ||
describe('lte', () => { | ||
test('less than or equal', () => { | ||
describe("lte", () => { | ||
test("less than or equal", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
@@ -518,6 +518,6 @@ expect(skNumber1.lte(skNumber2)).toBe(false); | ||
describe('eq', () => { | ||
test('equal', () => { | ||
describe("eq", () => { | ||
test("equal", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('5'); | ||
const skNumber2 = new SwapKitNumber("5"); | ||
@@ -530,6 +530,6 @@ expect(skNumber1.eq(skNumber2)).toBe(false); | ||
describe('comparison edge cases with decimals', () => { | ||
test('compare on cut decimals', () => { | ||
describe("comparison edge cases with decimals", () => { | ||
test("compare on cut decimals", () => { | ||
const skNumber1 = new SwapKitNumber({ value: 0.001, decimal: 3 }); | ||
const value = '0.0019'; | ||
const value = "0.0019"; | ||
@@ -544,6 +544,6 @@ expect(skNumber1.lt(value)).toBe(true); | ||
describe('Throws', () => { | ||
test('throws if division by zero', () => { | ||
describe("Throws", () => { | ||
test("throws if division by zero", () => { | ||
const skNumber1 = new SwapKitNumber(10); | ||
const skNumber2 = new SwapKitNumber('0'); | ||
const skNumber2 = new SwapKitNumber("0"); | ||
@@ -550,0 +550,0 @@ expect(() => skNumber1.div(skNumber2)).toThrow(RangeError); |
@@ -1,11 +0,11 @@ | ||
import { BaseDecimal, Chain, ChainToChainId } from '@swapkit/types'; | ||
import { BaseDecimal, Chain, ChainToChainId } from "@swapkit/types"; | ||
import type { CommonAssetString } from '../helpers/asset.ts'; | ||
import { getAssetType, getCommonAssetInfo, getDecimal, isGasAsset } from '../helpers/asset.ts'; | ||
import { validateIdentifier } from '../helpers/validators.ts'; | ||
import type { TokenNames, TokenTax } from '../types.ts'; | ||
import type { CommonAssetString } from "../helpers/asset.ts"; | ||
import { getAssetType, getCommonAssetInfo, getDecimal, isGasAsset } from "../helpers/asset.ts"; | ||
import { validateIdentifier } from "../helpers/validators.ts"; | ||
import type { TokenNames, TokenTax } from "../types.ts"; | ||
import type { NumberPrimitives } from './bigIntArithmetics.ts'; | ||
import { BigIntArithmetics, formatBigIntToSafeValue } from './bigIntArithmetics.ts'; | ||
import type { SwapKitValueType } from './swapKitNumber.ts'; | ||
import type { NumberPrimitives } from "./bigIntArithmetics.ts"; | ||
import { BigIntArithmetics, formatBigIntToSafeValue } from "./bigIntArithmetics.ts"; | ||
import { SwapKitNumber, type SwapKitValueType } from "./swapKitNumber.ts"; | ||
@@ -38,3 +38,3 @@ const staticTokensMap = new Map< | ||
)) { | ||
super(typeof value === 'object' ? value : { decimal, value }); | ||
super(typeof value === "object" ? value : { decimal, value }); | ||
@@ -58,3 +58,3 @@ const assetInfo = getAssetInfo(identifier || `${chain}.${symbol}`); | ||
toUrl() { | ||
return this.isSynthetic ? `${this.chain}.${this.symbol.replace('/', '.')}` : this.toString(); | ||
return this.isSynthetic ? `${this.chain}.${this.symbol.replace("/", ".")}` : this.toString(); | ||
} | ||
@@ -74,4 +74,4 @@ | ||
static fromUrl(urlAsset: string, value: NumberPrimitives = 0) { | ||
const [chain, ticker, symbol] = urlAsset.split('.'); | ||
if (!chain || !ticker) throw new Error('Invalid asset url'); | ||
const [chain, ticker, symbol] = urlAsset.split("."); | ||
if (!(chain && ticker)) throw new Error("Invalid asset url"); | ||
@@ -123,2 +123,40 @@ const assetString = | ||
static async fromStringWithBase( | ||
assetString: string, | ||
value: NumberPrimitives = 0, | ||
baseDecimal: number = BaseDecimal.THOR, | ||
) { | ||
const shiftedAmount = BigIntArithmetics.shiftDecimals({ | ||
value: SwapKitNumber.fromBigInt(BigInt(value)), | ||
from: 0, | ||
to: baseDecimal, | ||
}).getBaseValue("string"); | ||
const assetValue = await AssetValue.fromString(assetString, value); | ||
return assetValue.set(shiftedAmount); | ||
} | ||
static fromStringWithBaseSync( | ||
assetString: string, | ||
value: NumberPrimitives = 0, | ||
baseDecimal: number = BaseDecimal.THOR, | ||
) { | ||
const { chain, isSynthetic } = getAssetInfo(assetString); | ||
const tokenInfo = staticTokensMap.get(assetString.toUpperCase() as TokenNames); | ||
if (isSynthetic) return createSyntheticAssetValue(assetString, value); | ||
const { tax, decimal, identifier } = tokenInfo || { | ||
decimal: BaseDecimal[chain], | ||
identifier: assetString, | ||
}; | ||
return new AssetValue({ | ||
tax, | ||
value: safeValue(BigInt(value), baseDecimal), | ||
identifier, | ||
decimal, | ||
}); | ||
} | ||
static fromIdentifierSync(assetString: TokenNames, value: NumberPrimitives = 0) { | ||
@@ -150,16 +188,16 @@ const { chain, isSynthetic } = getAssetInfo(assetString); | ||
return new Promise<{ ok: true } | { ok: false; message: string; error: any }>( | ||
async (resolve, reject) => { | ||
(resolve, reject) => { | ||
try { | ||
const tokenPackages = await import('@swapkit/tokens'); | ||
import("@swapkit/tokens").then((tokenPackages) => { | ||
for (const tokenList of Object.values(tokenPackages)) { | ||
for (const { identifier, chain, ...rest } of tokenList.tokens) { | ||
staticTokensMap.set(identifier.toUpperCase() as TokenNames, { | ||
identifier, | ||
decimal: "decimals" in rest ? rest.decimals : BaseDecimal[chain as Chain], | ||
}); | ||
} | ||
} | ||
Object.values(tokenPackages).forEach((tokenList) => { | ||
tokenList?.tokens?.forEach(({ identifier, chain, ...rest }) => { | ||
staticTokensMap.set(identifier.toUpperCase() as TokenNames, { | ||
identifier, | ||
decimal: 'decimals' in rest ? rest.decimals : BaseDecimal[chain as Chain], | ||
}); | ||
}); | ||
resolve({ ok: true }); | ||
}); | ||
resolve({ ok: true }); | ||
} catch (error) { | ||
@@ -221,7 +259,7 @@ console.error(error); | ||
const [synthChain, symbol] = | ||
identifier.split('.')[0].toUpperCase() === Chain.THORChain | ||
? identifier.split('.').slice(1)!.join().split('/') | ||
: identifier.split('/'); | ||
identifier.split(".")[0].toUpperCase() === Chain.THORChain | ||
? identifier.split(".").slice(1).join().split("/") | ||
: identifier.split("/"); | ||
if (!synthChain || !symbol) throw new Error('Invalid asset identifier'); | ||
if (!(synthChain && symbol)) throw new Error("Invalid asset identifier"); | ||
@@ -236,3 +274,3 @@ return new AssetValue({ | ||
function safeValue(value: NumberPrimitives, decimal: number) { | ||
return typeof value === 'bigint' | ||
return typeof value === "bigint" | ||
? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) | ||
@@ -244,20 +282,20 @@ : value; | ||
function getAssetInfo(identifier: string) { | ||
const isSynthetic = identifier.slice(0, 14).includes('/'); | ||
const isSynthetic = identifier.slice(0, 14).includes("/"); | ||
const [synthChain, synthSymbol] = | ||
identifier.split('.')[0].toUpperCase() === Chain.THORChain | ||
? identifier.split('.').slice(1)!.join().split('/') | ||
: identifier.split('/'); | ||
identifier.split(".")[0].toUpperCase() === Chain.THORChain | ||
? identifier.split(".").slice(1).join().split("/") | ||
: identifier.split("/"); | ||
if (isSynthetic && (!synthChain || !synthSymbol)) throw new Error('Invalid asset identifier'); | ||
if (isSynthetic && !(synthChain && synthSymbol)) throw new Error("Invalid asset identifier"); | ||
const adjustedIdentifier = | ||
identifier.includes('.') && !isSynthetic ? identifier : `${Chain.THORChain}.${synthSymbol}`; | ||
identifier.includes(".") && !isSynthetic ? identifier : `${Chain.THORChain}.${synthSymbol}`; | ||
const [chain, ...rest] = adjustedIdentifier.split('.') as [Chain, string]; | ||
const [ticker, address] = (isSynthetic ? synthSymbol : rest.join('.')).split('-') as [ | ||
const [chain, ...rest] = adjustedIdentifier.split(".") as [Chain, string]; | ||
const [ticker, address] = (isSynthetic ? synthSymbol : rest.join(".")).split("-") as [ | ||
string, | ||
string?, | ||
]; | ||
const symbol = isSynthetic ? synthSymbol : rest.join('.'); | ||
const symbol = isSynthetic ? synthSymbol : rest.join("."); | ||
@@ -270,6 +308,6 @@ return { | ||
symbol: | ||
(isSynthetic ? `${synthChain}/` : '') + | ||
(address ? `${ticker}-${address?.toLowerCase() ?? ''}` : symbol), | ||
(isSynthetic ? `${synthChain}/` : "") + | ||
(address ? `${ticker}-${address?.toLowerCase() ?? ""}` : symbol), | ||
ticker, | ||
}; | ||
} |
@@ -1,4 +0,4 @@ | ||
import { BaseDecimal } from '@swapkit/types'; | ||
import { BaseDecimal } from "@swapkit/types"; | ||
import type { SwapKitNumber } from './swapKitNumber.ts'; | ||
import type { SwapKitNumber } from "./swapKitNumber.ts"; | ||
@@ -14,3 +14,3 @@ type NumberPrimitivesType = { | ||
type SKBigIntParams = InitialisationValueType | { decimal?: number; value: number | string }; | ||
type AllowedNumberTypes = 'bigint' | 'number' | 'string'; | ||
type AllowedNumberTypes = "bigint" | "number" | "string"; | ||
@@ -37,3 +37,3 @@ const DEFAULT_DECIMAL = 8; | ||
if (padLength > 0) { | ||
valueString = '0'.repeat(padLength) + valueString; | ||
valueString = "0".repeat(padLength) + valueString; | ||
} | ||
@@ -55,5 +55,5 @@ | ||
return `${isNegative ? '-' : ''}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace( | ||
return `${isNegative ? "-" : ""}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace( | ||
/\.?0*$/, | ||
'', | ||
"", | ||
); | ||
@@ -64,3 +64,3 @@ } | ||
decimalMultiplier: bigint = 10n ** 8n; | ||
bigIntValue: bigint = 0n; | ||
bigIntValue = 0n; | ||
decimal?: number; | ||
@@ -84,4 +84,4 @@ | ||
}) { | ||
return this.fromBigInt( | ||
(value.getBaseValue('bigint') * toMultiplier(to)) / toMultiplier(from), | ||
return BigIntArithmetics.fromBigInt( | ||
(value.getBaseValue("bigint") * toMultiplier(to)) / toMultiplier(from), | ||
to, | ||
@@ -93,3 +93,3 @@ ); | ||
const value = getStringValue(params); | ||
const isComplex = typeof params === 'object'; | ||
const isComplex = typeof params === "object"; | ||
this.decimal = isComplex ? params.decimal : undefined; | ||
@@ -99,3 +99,3 @@ | ||
this.decimalMultiplier = | ||
isComplex && 'decimalMultiplier' in params | ||
isComplex && "decimalMultiplier" in params | ||
? params.decimalMultiplier | ||
@@ -111,27 +111,27 @@ : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0)); | ||
add(...args: InitialisationValueType[]) { | ||
return this.#arithmetics('add', ...args); | ||
return this.#arithmetics("add", ...args); | ||
} | ||
sub(...args: InitialisationValueType[]) { | ||
return this.#arithmetics('sub', ...args); | ||
return this.#arithmetics("sub", ...args); | ||
} | ||
mul(...args: InitialisationValueType[]) { | ||
return this.#arithmetics('mul', ...args); | ||
return this.#arithmetics("mul", ...args); | ||
} | ||
div(...args: InitialisationValueType[]) { | ||
return this.#arithmetics('div', ...args); | ||
return this.#arithmetics("div", ...args); | ||
} | ||
gt(value: InitialisationValueType) { | ||
return this.#comparison('gt', value); | ||
return this.#comparison("gt", value); | ||
} | ||
gte(value: InitialisationValueType) { | ||
return this.#comparison('gte', value); | ||
return this.#comparison("gte", value); | ||
} | ||
lt(value: InitialisationValueType) { | ||
return this.#comparison('lt', value); | ||
return this.#comparison("lt", value); | ||
} | ||
lte(value: InitialisationValueType) { | ||
return this.#comparison('lte', value); | ||
return this.#comparison("lte", value); | ||
} | ||
eqValue(value: InitialisationValueType) { | ||
return this.#comparison('eqValue', value); | ||
return this.#comparison("eqValue", value); | ||
} | ||
@@ -147,7 +147,7 @@ | ||
switch (type) { | ||
case 'number': | ||
case "number": | ||
return Number(value) as NumberPrimitivesType[T]; | ||
case 'string': | ||
case "string": | ||
return value as NumberPrimitivesType[T]; | ||
case 'bigint': | ||
case "bigint": | ||
return ((this.bigIntValue * 10n ** BigInt(this.decimal || 8n)) / | ||
@@ -164,7 +164,7 @@ this.decimalMultiplier) as NumberPrimitivesType[T]; | ||
switch (type) { | ||
case 'number': | ||
case "number": | ||
return Number(baseValue) as NumberPrimitivesType[T]; | ||
case 'string': | ||
case "string": | ||
return baseValue.toString() as NumberPrimitivesType[T]; | ||
case 'bigint': | ||
case "bigint": | ||
return baseValue as NumberPrimitivesType[T]; | ||
@@ -175,3 +175,3 @@ } | ||
getBigIntValue(value: InitialisationValueType, decimal?: number) { | ||
if (!decimal && typeof value === 'object') return value.bigIntValue; | ||
if (!decimal && typeof value === "object") return value.bigIntValue; | ||
@@ -181,18 +181,18 @@ const stringValue = getStringValue(value); | ||
if (safeValue === '0' || safeValue === 'undefined') return 0n; | ||
if (safeValue === "0" || safeValue === "undefined") return 0n; | ||
return this.#toBigInt(safeValue, decimal); | ||
} | ||
toSignificant(significantDigits: number = 6) { | ||
const [int, dec] = this.getValue('string').split('.'); | ||
const integer = int || ''; | ||
const decimal = dec || ''; | ||
toSignificant(significantDigits = 6) { | ||
const [int, dec] = this.getValue("string").split("."); | ||
const integer = int || ""; | ||
const decimal = dec || ""; | ||
const valueLength = parseInt(integer) ? integer.length + decimal.length : decimal.length; | ||
if (valueLength <= significantDigits) { | ||
return this.getValue('string'); | ||
return this.getValue("string"); | ||
} | ||
if (integer.length >= significantDigits) { | ||
return integer.slice(0, significantDigits).padEnd(integer.length, '0'); | ||
return integer.slice(0, significantDigits).padEnd(integer.length, "0"); | ||
} | ||
@@ -203,3 +203,3 @@ | ||
significantDigits - integer.length, | ||
'0', | ||
"0", | ||
); | ||
@@ -213,13 +213,13 @@ } | ||
decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, | ||
'0', | ||
"0", | ||
)}`; | ||
} | ||
toFixed(fixedDigits: number = 6) { | ||
const [int, dec] = this.getValue('string').split('.'); | ||
const integer = int || ''; | ||
const decimal = dec || ''; | ||
toFixed(fixedDigits = 6) { | ||
const [int, dec] = this.getValue("string").split("."); | ||
const integer = int || ""; | ||
const decimal = dec || ""; | ||
if (parseInt(integer)) { | ||
return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, '0'); | ||
return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, "0"); | ||
} | ||
@@ -232,3 +232,3 @@ | ||
decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, | ||
'0', | ||
"0", | ||
)}`; | ||
@@ -238,8 +238,8 @@ } | ||
toAbbreviation(digits = 2) { | ||
const value = this.getValue('number'); | ||
const abbreviations = ['', 'K', 'M', 'B', 'T', 'Q', 'Qi', 'S']; | ||
const value = this.getValue("number"); | ||
const abbreviations = ["", "K", "M", "B", "T", "Q", "Qi", "S"]; | ||
const tier = Math.floor(Math.log10(Math.abs(value)) / 3); | ||
const suffix = abbreviations[tier]; | ||
if (!suffix) return this.getValue('string'); | ||
if (!suffix) return this.getValue("string"); | ||
@@ -253,23 +253,23 @@ const scale = 10 ** (tier * 3); | ||
toCurrency( | ||
currency = '$', | ||
currency = "$", | ||
{ | ||
currencyPosition = 'start', | ||
currencyPosition = "start", | ||
decimal = 2, | ||
decimalSeparator = '.', | ||
thousandSeparator = ',', | ||
decimalSeparator = ".", | ||
thousandSeparator = ",", | ||
} = {}, | ||
) { | ||
const value = this.getValue('number'); | ||
const [int, dec = ''] = value.toFixed(6).split('.'); | ||
const value = this.getValue("number"); | ||
const [int, dec = ""] = value.toFixed(6).split("."); | ||
const integer = int.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator); | ||
const parsedValue = | ||
!int && !dec | ||
? '0.00' | ||
: int === '0' | ||
? `${parseFloat(`0.${dec}`)}`.replace('.', decimalSeparator) | ||
: `${integer}${parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ''}`; | ||
int || dec | ||
? int === "0" | ||
? `${parseFloat(`0.${dec}`)}`.replace(".", decimalSeparator) | ||
: `${integer}${parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ""}` | ||
: "0.00"; | ||
return `${currencyPosition === 'start' ? currency : ''}${parsedValue}${ | ||
currencyPosition === 'end' ? currency : '' | ||
return `${currencyPosition === "start" ? currency : ""}${parsedValue}${ | ||
currencyPosition === "end" ? currency : "" | ||
}`; | ||
@@ -289,3 +289,3 @@ } | ||
const parsedValueString = padLength > 0 ? '0'.repeat(padLength) + valueString : valueString; | ||
const parsedValueString = padLength > 0 ? "0".repeat(padLength) + valueString : valueString; | ||
@@ -306,9 +306,9 @@ const decimalIndex = parsedValueString.length - decimalToUseForConversion; | ||
return `${isNegative ? '-' : ''}${parsedValueString.slice( | ||
return `${isNegative ? "-" : ""}${parsedValueString.slice( | ||
0, | ||
decimalIndex, | ||
)}.${decimalString}`.replace(/\.?0*$/, ''); | ||
)}.${decimalString}`.replace(/\.?0*$/, ""); | ||
} | ||
#arithmetics(method: 'add' | 'sub' | 'mul' | 'div', ...args: InitialisationValueType[]): this { | ||
#arithmetics(method: "add" | "sub" | "mul" | "div", ...args: InitialisationValueType[]): this { | ||
const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args); | ||
@@ -323,5 +323,5 @@ const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier)); | ||
switch (method) { | ||
case 'add': | ||
case "add": | ||
return acc + value; | ||
case 'sub': | ||
case "sub": | ||
return acc - value; | ||
@@ -336,6 +336,6 @@ /** | ||
*/ | ||
case 'mul': | ||
case "mul": | ||
return (acc * value) / precisionDecimalMultiplier; | ||
case 'div': { | ||
if (value === 0n) throw new RangeError('Division by zero'); | ||
case "div": { | ||
if (value === 0n) throw new RangeError("Division by zero"); | ||
return (acc * precisionDecimalMultiplier) / value; | ||
@@ -366,3 +366,3 @@ } | ||
#comparison(method: 'gt' | 'gte' | 'lt' | 'lte' | 'eqValue', ...args: InitialisationValueType[]) { | ||
#comparison(method: "gt" | "gte" | "lt" | "lte" | "eqValue", ...args: InitialisationValueType[]) { | ||
const decimal = this.#retrievePrecisionDecimal(this, ...args); | ||
@@ -373,11 +373,11 @@ const value = this.getBigIntValue(args[0], decimal); | ||
switch (method) { | ||
case 'gt': | ||
case "gt": | ||
return compareToValue > value; | ||
case 'gte': | ||
case "gte": | ||
return compareToValue >= value; | ||
case 'lt': | ||
case "lt": | ||
return compareToValue < value; | ||
case 'lte': | ||
case "lte": | ||
return compareToValue <= value; | ||
case 'eqValue': | ||
case "eqValue": | ||
return compareToValue === value; | ||
@@ -388,3 +388,3 @@ } | ||
#setValue(value: InitialisationValueType) { | ||
const safeValue = toSafeValue(value) || '0'; | ||
const safeValue = toSafeValue(value) || "0"; | ||
this.bigIntValue = this.#toBigInt(safeValue); | ||
@@ -396,3 +396,3 @@ } | ||
.map((arg) => { | ||
const isObject = typeof arg === 'object'; | ||
const isObject = typeof arg === "object"; | ||
const value = isObject | ||
@@ -412,9 +412,9 @@ ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier) | ||
const padDecimal = decimalFromMultiplier(multiplier); | ||
const [integerPart = '', decimalPart = ''] = value.split('.'); | ||
const [integerPart = "", decimalPart = ""] = value.split("."); | ||
return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, '0')}`); | ||
return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, "0")}`); | ||
} | ||
} | ||
const numberFormatter = Intl.NumberFormat('fullwide', { | ||
const numberFormatter = Intl.NumberFormat("fullwide", { | ||
useGrouping: false, | ||
@@ -426,7 +426,7 @@ maximumFractionDigits: 20, | ||
const parsedValue = | ||
typeof value === 'number' ? numberFormatter.format(value) : getStringValue(value); | ||
const splitValue = `${parsedValue}`.replaceAll(',', '.').split('.'); | ||
typeof value === "number" ? numberFormatter.format(value) : getStringValue(value); | ||
const splitValue = `${parsedValue}`.replaceAll(",", ".").split("."); | ||
return splitValue.length > 1 | ||
? `${splitValue.slice(0, -1).join('')}.${splitValue.at(-1)}` | ||
? `${splitValue.slice(0, -1).join("")}.${splitValue.at(-1)}` | ||
: splitValue[0]; | ||
@@ -436,3 +436,3 @@ } | ||
function getFloatDecimals(value: string) { | ||
const decimals = value.split('.')[1]?.length || 0; | ||
const decimals = value.split(".")[1]?.length || 0; | ||
return Math.max(decimals, DEFAULT_DECIMAL); | ||
@@ -442,7 +442,7 @@ } | ||
function getStringValue(param: SKBigIntParams) { | ||
return typeof param === 'object' | ||
? 'getValue' in param | ||
? param.getValue('string') | ||
return typeof param === "object" | ||
? "getValue" in param | ||
? param.getValue("string") | ||
: param.value | ||
: param; | ||
} |
@@ -34,2 +34,3 @@ const errorMessages = { | ||
core_swap_quote_mode_not_supported: 10207, | ||
core_swap_provider_not_found: 10208, | ||
/** | ||
@@ -64,2 +65,11 @@ * Core - Transaction | ||
/** | ||
* Chainflip | ||
*/ | ||
chainflip_channel_error: 30001, | ||
/** | ||
* THORChain | ||
*/ | ||
/** | ||
* Helpers | ||
@@ -75,8 +85,13 @@ */ | ||
if (sourceError) { | ||
console.error(sourceError, { stack: sourceError?.stack, message: sourceError?.message }); | ||
console.error(sourceError, { | ||
stack: sourceError?.stack, | ||
message: sourceError?.message, | ||
}); | ||
} | ||
super(errorKey, { cause: { code: errorMessages[errorKey], message: errorKey } }); | ||
super(errorKey, { | ||
cause: { code: errorMessages[errorKey], message: errorKey }, | ||
}); | ||
Object.setPrototypeOf(this, SwapKitError.prototype); | ||
} | ||
} |
@@ -1,2 +0,2 @@ | ||
import { BigIntArithmetics, formatBigIntToSafeValue } from './bigIntArithmetics.ts'; | ||
import { BigIntArithmetics, formatBigIntToSafeValue } from "./bigIntArithmetics.ts"; | ||
@@ -3,0 +3,0 @@ export type SwapKitValueType = BigIntArithmetics | string | number; |
@@ -14,3 +14,3 @@ import type { | ||
WoofiList, | ||
} from '@swapkit/tokens'; | ||
} from "@swapkit/tokens"; | ||
@@ -20,13 +20,13 @@ export type TokenTax = { buy: number; sell: number }; | ||
export type TokenNames = | ||
| (typeof ThorchainList)['tokens'][number]['identifier'] | ||
| (typeof CoinGeckoList)['tokens'][number]['identifier'] | ||
| (typeof MayaList)['tokens'][number]['identifier'] | ||
| (typeof PancakeswapETHList)['tokens'][number]['identifier'] | ||
| (typeof PancakeswapList)['tokens'][number]['identifier'] | ||
| (typeof PangolinList)['tokens'][number]['identifier'] | ||
| (typeof StargateARBList)['tokens'][number]['identifier'] | ||
| (typeof SushiswapList)['tokens'][number]['identifier'] | ||
| (typeof TraderjoeList)['tokens'][number]['identifier'] | ||
| (typeof WoofiList)['tokens'][number]['identifier'] | ||
| (typeof UniswapList)['tokens'][number]['identifier'] | ||
| (typeof ChainflipList)['tokens'][number]['identifier']; | ||
| (typeof ThorchainList)["tokens"][number]["identifier"] | ||
| (typeof CoinGeckoList)["tokens"][number]["identifier"] | ||
| (typeof MayaList)["tokens"][number]["identifier"] | ||
| (typeof PancakeswapETHList)["tokens"][number]["identifier"] | ||
| (typeof PancakeswapList)["tokens"][number]["identifier"] | ||
| (typeof PangolinList)["tokens"][number]["identifier"] | ||
| (typeof StargateARBList)["tokens"][number]["identifier"] | ||
| (typeof SushiswapList)["tokens"][number]["identifier"] | ||
| (typeof TraderjoeList)["tokens"][number]["identifier"] | ||
| (typeof WoofiList)["tokens"][number]["identifier"] | ||
| (typeof UniswapList)["tokens"][number]["identifier"] | ||
| (typeof ChainflipList)["tokens"][number]["identifier"]; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
5
2
414803
24
4103
+ Added@swapkit/api@0.0.0-nightly-20240223171610(transitive)
+ Added@swapkit/tokens@0.0.0-nightly-20240223171610(transitive)
+ Added@swapkit/types@0.0.0-nightly-20240223171610(transitive)
- Removed@swapkit/api@0.0.0-nightly-20240208140027(transitive)
- Removed@swapkit/tokens@0.0.0-nightly-20240208140027(transitive)
- Removed@swapkit/types@0.0.0-nightly-20240208140027(transitive)