@swapkit/helpers 1.0.0-rc.83 → 1.0.0-rc.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/helpers/asset.ts", "../src/helpers/liquidity.ts", "../src/helpers/liquidity.ts", "../src/helpers/memo.ts", "../src/modules/swapKitError.ts", "../src/helpers/others.ts", "../src/modules/assetValue.ts", "../src/helpers/validators.ts", "../src/helpers/validators.ts", "../src/modules/bigIntArithmetics.ts", "../src/modules/swapKitNumber.ts", "../src/modules/assetValue.ts"],
4
+ "sourcesContent": [
5
+ "export * from \"@swapkit/api\";\n\n/**\n * Helpers\n */\nexport * from \"./helpers/asset.ts\";\nexport * from \"./helpers/liquidity.ts\";\nexport * from \"./helpers/memo.ts\";\nexport * from \"./helpers/others.ts\";\n\n/**\n * Modules\n */\nexport * from \"./modules/assetValue.ts\";\nexport * from \"./modules/bigIntArithmetics.ts\";\nexport * from \"./modules/swapKitError.ts\";\nexport * from \"./modules/swapKitNumber.ts\";\n",
6
+ "import { RequestClient } from \"@swapkit/api\";\nimport type { EVMChain } from \"@swapkit/types\";\nimport { BaseDecimal, Chain, ChainToRPC, EVMChains, FeeOption } from \"@swapkit/types\";\nimport type { TokenNames } from \"../types.ts\";\n\nconst getDecimalMethodHex = \"0x313ce567\";\n\nexport type CommonAssetString =\n | `${Chain.Maya}.MAYA`\n | `${Chain.Ethereum}.THOR`\n | `${Chain.Ethereum}.vTHOR`\n | `${Chain.Kujira}.USK`\n | Chain;\n\nconst getContractDecimals = async ({ chain, to }: { chain: EVMChain; to: string }) => {\n try {\n const { result } = await RequestClient.post<{ result: string }>(ChainToRPC[chain], {\n headers: {\n accept: \"*/*\",\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-cache\",\n },\n body: JSON.stringify({\n id: 44,\n jsonrpc: \"2.0\",\n method: \"eth_call\",\n params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, \"latest\"],\n }),\n });\n\n return Number.parseInt(BigInt(result || BaseDecimal[chain]).toString());\n } catch (error) {\n console.error(error);\n return BaseDecimal[chain];\n }\n};\n\nconst getETHAssetDecimal = (symbol: string) => {\n if (symbol === Chain.Ethereum) return BaseDecimal.ETH;\n const [, address] = symbol.split(\"-\");\n\n return address?.startsWith(\"0x\")\n ? getContractDecimals({ chain: Chain.Ethereum, to: address })\n : BaseDecimal.ETH;\n};\n\nconst getAVAXAssetDecimal = (symbol: string) => {\n const [, address] = symbol.split(\"-\");\n\n return address?.startsWith(\"0x\")\n ? getContractDecimals({ chain: Chain.Avalanche, to: address.toLowerCase() })\n : BaseDecimal.AVAX;\n};\n\nconst getBSCAssetDecimal = (symbol: string) => {\n if (symbol === Chain.BinanceSmartChain) return BaseDecimal.BSC;\n\n return BaseDecimal.BSC;\n};\n\nexport const getDecimal = ({ chain, symbol }: { chain: Chain; symbol: string }) => {\n switch (chain) {\n case Chain.Ethereum:\n return getETHAssetDecimal(symbol);\n case Chain.Avalanche:\n return getAVAXAssetDecimal(symbol);\n case Chain.BinanceSmartChain:\n return getBSCAssetDecimal(symbol);\n default:\n return BaseDecimal[chain];\n }\n};\n\nexport const gasFeeMultiplier: Record<FeeOption, number> = {\n [FeeOption.Average]: 1.2,\n [FeeOption.Fast]: 1.5,\n [FeeOption.Fastest]: 2,\n};\n\nexport const isGasAsset = ({ chain, symbol }: { chain: Chain; symbol: string }) => {\n switch (chain) {\n case Chain.Arbitrum:\n case Chain.Optimism:\n return symbol === \"ETH\";\n case Chain.Maya:\n return symbol === \"CACAO\";\n case Chain.Kujira:\n return symbol === \"KUJI\";\n case Chain.Cosmos:\n return symbol === \"ATOM\";\n case Chain.Polygon:\n return symbol === \"MATIC\";\n case Chain.BinanceSmartChain:\n return symbol === \"BNB\";\n case Chain.THORChain:\n return symbol === \"RUNE\";\n\n default:\n return symbol === chain;\n }\n};\n\nexport const getCommonAssetInfo = (\n assetString: CommonAssetString,\n): { identifier: string; decimal: number } => {\n switch (assetString) {\n case `${Chain.Ethereum}.THOR`:\n return { identifier: \"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044\", decimal: 18 };\n case `${Chain.Ethereum}.vTHOR`:\n return { identifier: \"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d\", decimal: 18 };\n\n case Chain.Cosmos:\n return { identifier: \"GAIA.ATOM\", decimal: BaseDecimal[assetString] };\n case Chain.THORChain:\n return { identifier: \"THOR.RUNE\", decimal: BaseDecimal[assetString] };\n case Chain.BinanceSmartChain:\n return { identifier: \"BSC.BNB\", decimal: BaseDecimal[assetString] };\n case Chain.Maya:\n return { identifier: \"MAYA.CACAO\", decimal: BaseDecimal.MAYA };\n case `${Chain.Maya}.MAYA`:\n return { identifier: \"MAYA.MAYA\", decimal: 4 };\n\n case `${Chain.Kujira}.USK`:\n return { identifier: `${Chain.Kujira}.USK`, decimal: 6 };\n\n default:\n return { identifier: `${assetString}.${assetString}`, decimal: BaseDecimal[assetString] };\n }\n};\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: Refactor\nexport const getAssetType = ({ chain, symbol }: { chain: Chain; symbol: string }) => {\n if (symbol.includes(\"/\")) return \"Synth\";\n\n switch (chain) {\n case Chain.Cosmos:\n return symbol === \"ATOM\" ? \"Native\" : Chain.Cosmos;\n case Chain.Kujira:\n return symbol === Chain.Kujira ? \"Native\" : Chain.Kujira;\n case Chain.Binance:\n return symbol === Chain.Binance ? \"Native\" : \"BEP2\";\n case Chain.BinanceSmartChain:\n return symbol === Chain.Binance ? \"Native\" : \"BEP20\";\n case Chain.Ethereum:\n return symbol === Chain.Ethereum ? \"Native\" : \"ERC20\";\n case Chain.Avalanche:\n return symbol === Chain.Avalanche ? \"Native\" : Chain.Avalanche;\n case Chain.Polygon:\n return symbol === Chain.Polygon ? \"Native\" : \"POLYGON\";\n\n case Chain.Arbitrum:\n return [Chain.Ethereum, Chain.Arbitrum].includes(symbol as Chain) ? \"Native\" : \"ARBITRUM\";\n case Chain.Optimism:\n return [Chain.Ethereum, Chain.Optimism].includes(symbol as Chain) ? \"Native\" : \"OPTIMISM\";\n\n default:\n return \"Native\";\n }\n};\n\nexport const assetFromString = (assetString: string) => {\n const [chain, ...symbolArray] = assetString.split(\".\") as [Chain, ...(string | undefined)[]];\n const synth = assetString.includes(\"/\");\n const symbol = symbolArray.join(\".\");\n const ticker = symbol?.split(\"-\")?.[0];\n\n return { chain, symbol, ticker, synth };\n};\n\nconst potentialScamRegex = new RegExp(\n /(.)\\1{6}|\\.ORG|\\.NET|\\.FINANCE|\\.COM|WWW|HTTP|\\\\\\\\|\\/\\/|[\\s$%:[\\]]/,\n \"gmi\",\n);\n\nconst evmAssetHasAddress = (assetString: string) => {\n const [chain, symbol] = assetString.split(\".\") as [EVMChain, string];\n if (!EVMChains.includes(chain as EVMChain)) return true;\n const [, address] = symbol.split(\"-\") as [string, string?];\n\n return isGasAsset({ chain: chain as Chain, symbol }) || !!address;\n};\n\nexport const filterAssets = (\n tokens: {\n value: string;\n decimal: number;\n chain: Chain;\n symbol: string;\n }[],\n) =>\n tokens.filter(({ chain, value, symbol }) => {\n const assetString = `${chain}.${symbol}`;\n\n return (\n !potentialScamRegex.test(assetString) && evmAssetHasAddress(assetString) && value !== \"0\"\n );\n });\n\nexport async function findAssetBy(\n params: { chain: EVMChain; contract: string } | { identifier: `${Chain}.${string}` },\n) {\n const tokenPackages = await import(\"@swapkit/tokens\");\n\n for (const tokenList of Object.values(tokenPackages)) {\n for (const { identifier, chain: tokenChain, ...rest } of tokenList.tokens) {\n if (\"identifier\" in params && identifier === params.identifier) {\n return identifier as TokenNames;\n }\n\n if (\n \"address\" in rest &&\n \"chain\" in params &&\n tokenChain === params.chain &&\n rest.address.toLowerCase() === params.contract.toLowerCase()\n )\n return identifier as TokenNames;\n }\n }\n\n return;\n}\n",
7
+ "import { BaseDecimal } from \"@swapkit/types\";\n\nimport { SwapKitNumber } from \"../index.ts\";\n\ntype ShareParams<T extends {}> = T & {\n liquidityUnits: string;\n poolUnits: string;\n};\n\ntype PoolParams = {\n runeAmount: string;\n assetAmount: string;\n runeDepth: string;\n assetDepth: string;\n};\n\n/**\n * Ref: https://gitlab.com/thorchain/thornode/-/issues/657\n * share = (s * A * (2 * T^2 - 2 * T * s + s^2))/T^3\n * s = stakeUnits for member (after factoring in withdrawBasisPoints)\n * T = totalPoolUnits for pool\n * A = assetDepth to be withdrawn\n *\n * Formula:\n * share = (s * A * (2 * T^2 - 2 * T * s + s^2))/T^3\n * (part1 * (part2 - part3 + part4)) / part5\n */\nexport function getAsymmetricRuneShare({\n liquidityUnits,\n poolUnits,\n runeDepth,\n}: ShareParams<{ runeDepth: string }>) {\n const s = toTCSwapKitNumber(liquidityUnits);\n const T = toTCSwapKitNumber(poolUnits);\n const A = toTCSwapKitNumber(runeDepth);\n\n const part1 = s.mul(A);\n const part2 = T.mul(T).mul(2);\n const part3 = T.mul(s).mul(2);\n const part4 = s.mul(s);\n const part5 = T.mul(T).mul(T);\n\n const numerator = part1.mul(part2.sub(part3).add(part4));\n\n return numerator.div(part5);\n}\n\nexport function getAsymmetricAssetShare({\n liquidityUnits,\n poolUnits,\n assetDepth,\n}: ShareParams<{ assetDepth: string }>) {\n const s = toTCSwapKitNumber(liquidityUnits);\n const T = toTCSwapKitNumber(poolUnits);\n const A = toTCSwapKitNumber(assetDepth);\n\n const part1 = s.mul(A);\n const part2 = T.mul(T).mul(2);\n const part3 = T.mul(s).mul(2);\n const part4 = s.mul(s);\n const numerator = part1.mul(part2.sub(part3).add(part4));\n const part5 = T.mul(T).mul(T);\n\n return numerator.div(part5);\n}\n\nexport function getAsymmetricRuneWithdrawAmount({\n percent,\n runeDepth,\n liquidityUnits,\n poolUnits,\n}: ShareParams<{ percent: number; runeDepth: string }>) {\n return getAsymmetricRuneShare({ runeDepth, liquidityUnits, poolUnits }).mul(percent);\n}\n\nexport function getAsymmetricAssetWithdrawAmount({\n percent,\n assetDepth,\n liquidityUnits,\n poolUnits,\n}: ShareParams<{ percent: number; assetDepth: string }>) {\n return getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);\n}\n\nfunction toTCSwapKitNumber(value: string) {\n return SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal.THOR);\n}\n\nexport function getSymmetricPoolShare({\n liquidityUnits,\n poolUnits,\n runeDepth,\n assetDepth,\n}: ShareParams<{\n runeDepth: string;\n assetDepth: string;\n}>) {\n return {\n assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),\n runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits),\n };\n}\n\nexport function getSymmetricWithdraw({\n liquidityUnits,\n poolUnits,\n runeDepth,\n assetDepth,\n percent,\n}: ShareParams<{\n runeDepth: string;\n assetDepth: string;\n percent: number;\n}>) {\n return Object.fromEntries(\n Object.entries(getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth })).map(\n ([name, value]) => [name, value.mul(percent)],\n ),\n );\n}\n\nexport function getEstimatedPoolShare({\n runeDepth,\n poolUnits,\n assetDepth,\n liquidityUnits,\n runeAmount,\n assetAmount,\n}: ShareParams<{\n runeAmount: string;\n assetAmount: string;\n runeDepth: string;\n assetDepth: string;\n}>) {\n const R = new SwapKitNumber({ value: runeDepth, decimal: 8 });\n const A = new SwapKitNumber({ value: assetDepth, decimal: 8 });\n const P = new SwapKitNumber({ value: poolUnits, decimal: 8 });\n const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 });\n const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 });\n\n // liquidityUnits = P * (r*A + a*R + 2*r*a) / (r*A + a*R + 2*R*A)\n const rA = runeAddAmount.mul(A);\n const aR = assetAddAmount.mul(R);\n const ra = runeAddAmount.mul(assetAddAmount);\n const RA = R.mul(A);\n const numerator = P.mul(rA.add(aR.add(ra.mul(2))));\n const denominator = rA.add(aR.add(RA.mul(2)));\n const liquidityUnitsAfterAdd = numerator.div(denominator);\n const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);\n\n if (liquidityUnitsAfterAdd.getBaseValue(\"number\") === 0) {\n return estimatedLiquidityUnits.div(P).getBaseValue(\"number\");\n }\n\n // get pool units after add\n const newPoolUnits = P.add(estimatedLiquidityUnits);\n\n return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue(\"number\");\n}\n\nexport function getLiquiditySlippage({\n runeAmount,\n assetAmount,\n runeDepth,\n assetDepth,\n}: PoolParams) {\n if (runeAmount === \"0\" || assetAmount === \"0\" || runeDepth === \"0\" || assetDepth === \"0\")\n return 0;\n // formula: (t * R - T * r)/ (T*r + R*T)\n const R = toTCSwapKitNumber(runeDepth);\n const T = toTCSwapKitNumber(assetDepth);\n const assetAddAmount = toTCSwapKitNumber(assetAmount);\n const runeAddAmount = toTCSwapKitNumber(runeAmount);\n\n const numerator = assetAddAmount.mul(R).sub(T.mul(runeAddAmount));\n const denominator = T.mul(runeAddAmount).add(R.mul(T));\n\n // set absolute value of percent, no negative allowed\n return Math.abs(numerator.div(denominator).getBaseValue(\"number\"));\n}\n",
8
+ "import { BaseDecimal } from \"@swapkit/types\";\n\nimport { SwapKitNumber } from \"../index.ts\";\n\ntype ShareParams<T extends {}> = T & {\n liquidityUnits: string;\n poolUnits: string;\n};\n\ntype PoolParams = {\n runeAmount: string;\n assetAmount: string;\n runeDepth: string;\n assetDepth: string;\n};\n\n/**\n * Ref: https://gitlab.com/thorchain/thornode/-/issues/657\n * share = (s * A * (2 * T^2 - 2 * T * s + s^2))/T^3\n * s = stakeUnits for member (after factoring in withdrawBasisPoints)\n * T = totalPoolUnits for pool\n * A = assetDepth to be withdrawn\n *\n * Formula:\n * share = (s * A * (2 * T^2 - 2 * T * s + s^2))/T^3\n * (part1 * (part2 - part3 + part4)) / part5\n */\nexport function getAsymmetricRuneShare({\n liquidityUnits,\n poolUnits,\n runeDepth,\n}: ShareParams<{ runeDepth: string }>) {\n const s = toTCSwapKitNumber(liquidityUnits);\n const T = toTCSwapKitNumber(poolUnits);\n const A = toTCSwapKitNumber(runeDepth);\n\n const part1 = s.mul(A);\n const part2 = T.mul(T).mul(2);\n const part3 = T.mul(s).mul(2);\n const part4 = s.mul(s);\n const part5 = T.mul(T).mul(T);\n\n const numerator = part1.mul(part2.sub(part3).add(part4));\n\n return numerator.div(part5);\n}\n\nexport function getAsymmetricAssetShare({\n liquidityUnits,\n poolUnits,\n assetDepth,\n}: ShareParams<{ assetDepth: string }>) {\n const s = toTCSwapKitNumber(liquidityUnits);\n const T = toTCSwapKitNumber(poolUnits);\n const A = toTCSwapKitNumber(assetDepth);\n\n const part1 = s.mul(A);\n const part2 = T.mul(T).mul(2);\n const part3 = T.mul(s).mul(2);\n const part4 = s.mul(s);\n const numerator = part1.mul(part2.sub(part3).add(part4));\n const part5 = T.mul(T).mul(T);\n\n return numerator.div(part5);\n}\n\nexport function getAsymmetricRuneWithdrawAmount({\n percent,\n runeDepth,\n liquidityUnits,\n poolUnits,\n}: ShareParams<{ percent: number; runeDepth: string }>) {\n return getAsymmetricRuneShare({ runeDepth, liquidityUnits, poolUnits }).mul(percent);\n}\n\nexport function getAsymmetricAssetWithdrawAmount({\n percent,\n assetDepth,\n liquidityUnits,\n poolUnits,\n}: ShareParams<{ percent: number; assetDepth: string }>) {\n return getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);\n}\n\nfunction toTCSwapKitNumber(value: string) {\n return SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal.THOR);\n}\n\nexport function getSymmetricPoolShare({\n liquidityUnits,\n poolUnits,\n runeDepth,\n assetDepth,\n}: ShareParams<{\n runeDepth: string;\n assetDepth: string;\n}>) {\n return {\n assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),\n runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits),\n };\n}\n\nexport function getSymmetricWithdraw({\n liquidityUnits,\n poolUnits,\n runeDepth,\n assetDepth,\n percent,\n}: ShareParams<{\n runeDepth: string;\n assetDepth: string;\n percent: number;\n}>) {\n return Object.fromEntries(\n Object.entries(getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth })).map(\n ([name, value]) => [name, value.mul(percent)],\n ),\n );\n}\n\nexport function getEstimatedPoolShare({\n runeDepth,\n poolUnits,\n assetDepth,\n liquidityUnits,\n runeAmount,\n assetAmount,\n}: ShareParams<{\n runeAmount: string;\n assetAmount: string;\n runeDepth: string;\n assetDepth: string;\n}>) {\n const R = new SwapKitNumber({ value: runeDepth, decimal: 8 });\n const A = new SwapKitNumber({ value: assetDepth, decimal: 8 });\n const P = new SwapKitNumber({ value: poolUnits, decimal: 8 });\n const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 });\n const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 });\n\n // liquidityUnits = P * (r*A + a*R + 2*r*a) / (r*A + a*R + 2*R*A)\n const rA = runeAddAmount.mul(A);\n const aR = assetAddAmount.mul(R);\n const ra = runeAddAmount.mul(assetAddAmount);\n const RA = R.mul(A);\n const numerator = P.mul(rA.add(aR.add(ra.mul(2))));\n const denominator = rA.add(aR.add(RA.mul(2)));\n const liquidityUnitsAfterAdd = numerator.div(denominator);\n const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);\n\n if (liquidityUnitsAfterAdd.getBaseValue(\"number\") === 0) {\n return estimatedLiquidityUnits.div(P).getBaseValue(\"number\");\n }\n\n // get pool units after add\n const newPoolUnits = P.add(estimatedLiquidityUnits);\n\n return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue(\"number\");\n}\n\nexport function getLiquiditySlippage({\n runeAmount,\n assetAmount,\n runeDepth,\n assetDepth,\n}: PoolParams) {\n if (runeAmount === \"0\" || assetAmount === \"0\" || runeDepth === \"0\" || assetDepth === \"0\")\n return 0;\n // formula: (t * R - T * r)/ (T*r + R*T)\n const R = toTCSwapKitNumber(runeDepth);\n const T = toTCSwapKitNumber(assetDepth);\n const assetAddAmount = toTCSwapKitNumber(assetAmount);\n const runeAddAmount = toTCSwapKitNumber(runeAmount);\n\n const numerator = assetAddAmount.mul(R).sub(T.mul(runeAddAmount));\n const denominator = T.mul(runeAddAmount).add(R.mul(T));\n\n // set absolute value of percent, no negative allowed\n return Math.abs(numerator.div(denominator).getBaseValue(\"number\"));\n}\n",
9
+ "import { Chain, MemoType } from \"@swapkit/types\";\n\nexport type ThornameRegisterParam = {\n name: string;\n chain: string;\n address: string;\n owner?: string;\n preferredAsset?: string;\n expiryBlock?: string;\n};\n\ntype WithChain<T extends {}> = T & { chain: Chain };\n\nexport type MemoOptions<T extends MemoType> = {\n [MemoType.BOND]: { address: string };\n [MemoType.LEAVE]: { address: string };\n [MemoType.CLOSE_LOAN]: { address: string; asset: string; minAmount?: string };\n [MemoType.OPEN_LOAN]: { address: string; asset: string; minAmount?: string };\n [MemoType.UNBOND]: { address: string; unbondAmount: number };\n [MemoType.DEPOSIT]: WithChain<{ symbol: string; address?: string; singleSide?: boolean }>;\n [MemoType.WITHDRAW]: WithChain<{\n ticker: string;\n symbol: string;\n basisPoints: number;\n targetAssetString?: string;\n singleSide?: boolean;\n }>;\n [MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, \"preferredAsset\" | \"expiryBlock\">;\n}[T];\n\nexport const getMemoFor = <T extends MemoType>(memoType: T, options: MemoOptions<T>) => {\n switch (memoType) {\n case MemoType.LEAVE:\n case MemoType.BOND: {\n const { address } = options as MemoOptions<MemoType.BOND>;\n return `${memoType}:${address}`;\n }\n\n case MemoType.UNBOND: {\n const { address, unbondAmount } = options as MemoOptions<MemoType.UNBOND>;\n return `${memoType}:${address}:${unbondAmount}`;\n }\n\n case MemoType.THORNAME_REGISTER: {\n const { name, chain, address, owner } = options as MemoOptions<MemoType.THORNAME_REGISTER>;\n return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : \"\"}`;\n }\n\n case MemoType.DEPOSIT: {\n const { chain, symbol, address, singleSide } = options as MemoOptions<MemoType.DEPOSIT>;\n\n const getPoolIdentifier = (chain: Chain, symbol: string): string => {\n switch (chain) {\n case Chain.Litecoin:\n return \"l\";\n case Chain.Dogecoin:\n return \"d\";\n case Chain.BitcoinCash:\n return \"c\";\n default:\n return `${chain}.${symbol}`;\n }\n };\n\n return singleSide\n ? `${memoType}:${chain}/${symbol}`\n : `${memoType}:${getPoolIdentifier(chain, symbol)}:${address || \"\"}`;\n }\n\n case MemoType.WITHDRAW: {\n const { chain, ticker, symbol, basisPoints, targetAssetString, singleSide } =\n options as MemoOptions<MemoType.WITHDRAW>;\n\n const shortenedSymbol =\n chain === \"ETH\" && ticker !== \"ETH\" ? `${ticker}-${symbol.slice(-3)}` : symbol;\n const target = !singleSide && targetAssetString ? `:${targetAssetString}` : \"\";\n const assetDivider = singleSide ? \"/\" : \".\";\n\n return `${memoType}:${chain}${assetDivider}${shortenedSymbol}:${basisPoints}${target}`;\n }\n\n case MemoType.OPEN_LOAN:\n case MemoType.CLOSE_LOAN: {\n const { asset, address } = options as MemoOptions<MemoType.OPEN_LOAN>;\n\n return `${memoType}:${asset}:${address}`; //:${minAmount ? `${minAmount}` : ''}:t:0`;\n }\n\n default:\n return \"\";\n }\n};\n",
10
+ "const errorMessages = {\n /**\n * Core\n */\n core_wallet_connection_not_found: 10001,\n core_estimated_max_spendable_chain_not_supported: 10002,\n core_extend_error: 10003,\n core_inbound_data_not_found: 10004,\n core_approve_asset_address_or_from_not_found: 10005,\n core_plugin_not_found: 10006,\n core_chain_halted: 10099,\n /**\n * Core - Wallet Connection\n */\n core_wallet_xdefi_not_installed: 10101,\n core_wallet_evmwallet_not_installed: 10102,\n core_wallet_walletconnect_not_installed: 10103,\n core_wallet_keystore_not_installed: 10104,\n core_wallet_ledger_not_installed: 10105,\n core_wallet_trezor_not_installed: 10106,\n core_wallet_keplr_not_installed: 10107,\n core_wallet_okx_not_installed: 10108,\n core_wallet_keepkey_not_installed: 10109,\n /**\n * Core - Swap\n */\n core_swap_invalid_params: 10200,\n core_swap_route_not_complete: 10201,\n core_swap_asset_not_recognized: 10202,\n core_swap_contract_not_found: 10203,\n core_swap_route_transaction_not_found: 10204,\n core_swap_contract_not_supported: 10205,\n core_swap_transaction_error: 10206,\n core_swap_quote_mode_not_supported: 10207,\n /**\n * Core - Transaction\n */\n core_transaction_deposit_error: 10301,\n core_transaction_create_liquidity_rune_error: 10302,\n core_transaction_create_liquidity_asset_error: 10303,\n core_transaction_create_liquidity_invalid_params: 10304,\n core_transaction_add_liquidity_invalid_params: 10305,\n core_transaction_add_liquidity_no_rune_address: 10306,\n core_transaction_add_liquidity_rune_error: 10307,\n core_transaction_add_liquidity_asset_error: 10308,\n core_transaction_withdraw_error: 10309,\n core_transaction_deposit_to_pool_error: 10310,\n core_transaction_deposit_insufficient_funds_error: 10311,\n core_transaction_deposit_gas_error: 10312,\n core_transaction_invalid_sender_address: 10313,\n core_transaction_deposit_server_error: 10314,\n core_transaction_user_rejected: 10315,\n\n /**\n * Wallets\n */\n wallet_ledger_connection_error: 20001,\n wallet_ledger_connection_claimed: 20002,\n wallet_ledger_get_address_error: 20003,\n wallet_ledger_device_not_found: 20004,\n wallet_ledger_device_locked: 20005,\n\n /**\n * Chainflip\n */\n chainflip_channel_error: 30001,\n chainflip_broker_recipient_error: 30002,\n\n /**\n * THORChain\n */\n\n /**\n * Helpers\n */\n helpers_number_different_decimals: 99101,\n} as const;\n\nexport type ErrorKeys = keyof typeof errorMessages;\n\nexport class SwapKitError extends Error {\n constructor(errorKey: ErrorKeys, sourceError?: NotWorth) {\n if (sourceError) {\n console.error(sourceError, {\n stack: sourceError?.stack,\n message: sourceError?.message,\n });\n }\n\n super(errorKey, {\n cause: { code: errorMessages[errorKey], message: errorKey },\n });\n Object.setPrototypeOf(this, SwapKitError.prototype);\n }\n}\n",
11
+ "import type { DerivationPathArray } from \"@swapkit/types\";\nimport { type ErrorKeys, SwapKitError } from \"../modules/swapKitError\";\n\n// 10 rune for register, 1 rune per year\n// MINIMUM_REGISTRATION_FEE = 11\nexport function getTHORNameCost(year: number) {\n if (year < 0) throw new Error(\"Invalid number of year\");\n return 10 + year;\n}\n\n// 10 CACAO for register\n// 1.0512 CACAO per year\nexport function getMAYANameCost(year: number) {\n if (year < 0) throw new Error(\"Invalid number of year\");\n // round to max 10 decimals\n return Math.round((10 + year * 1.0512) * 1e10) / 1e10;\n}\n\nexport function derivationPathToString([network, chainId, account, change, index]:\n | [number, number, number, number, number | undefined]\n | DerivationPathArray) {\n const shortPath = typeof index !== \"number\";\n\n return `m/${network}'/${chainId}'/${account}'/${change}${shortPath ? \"\" : `/${index}`}`;\n}\n\nexport function wrapWithThrow<T>(fn: () => T, errorKey?: ErrorKeys) {\n try {\n return fn();\n } catch (error) {\n if (errorKey) {\n throw new SwapKitError(errorKey, error);\n }\n\n return console.error(error);\n }\n}\n",
12
+ "import { BaseDecimal, Chain, ChainToChainId } from \"@swapkit/types\";\n\nimport type { CommonAssetString } from \"../helpers/asset.ts\";\nimport { getAssetType, getCommonAssetInfo, getDecimal, isGasAsset } from \"../helpers/asset.ts\";\nimport { validateIdentifier } from \"../helpers/validators.ts\";\nimport type { TokenNames, TokenTax } from \"../types.ts\";\n\nimport type { NumberPrimitives } from \"./bigIntArithmetics.ts\";\nimport { BigIntArithmetics, formatBigIntToSafeValue } from \"./bigIntArithmetics.ts\";\nimport { SwapKitNumber, type SwapKitValueType } from \"./swapKitNumber.ts\";\n\nconst staticTokensMap = new Map<\n TokenNames,\n { tax?: TokenTax; decimal: number; identifier: string }\n>();\n\nexport class AssetValue extends BigIntArithmetics {\n address?: string;\n chain: Chain;\n isGasAsset = false;\n isSynthetic = false;\n symbol: string;\n tax?: TokenTax;\n ticker: string;\n type: ReturnType<typeof getAssetType>;\n\n constructor({\n value,\n decimal,\n tax,\n chain,\n symbol,\n identifier,\n }: { decimal: number; value: SwapKitValueType; tax?: TokenTax } & (\n | { chain: Chain; symbol: string; identifier?: never }\n | { identifier: string; chain?: never; symbol?: never }\n )) {\n super(typeof value === \"object\" ? value : { decimal, value });\n\n const assetInfo = getAssetInfo(identifier || `${chain}.${symbol}`);\n\n this.type = getAssetType(assetInfo);\n this.tax = tax;\n this.chain = assetInfo.chain;\n this.ticker = assetInfo.ticker;\n this.symbol = assetInfo.symbol;\n this.address = assetInfo.address;\n this.isSynthetic = assetInfo.isSynthetic;\n this.isGasAsset = assetInfo.isGasAsset;\n }\n\n toString() {\n return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;\n }\n\n toUrl() {\n return this.isSynthetic ? `${this.chain}.${this.symbol.replace(\"/\", \".\")}` : this.toString();\n }\n\n eq({ chain, symbol }: { chain: Chain; symbol: string }) {\n return this.chain === chain && this.symbol === symbol;\n }\n\n chainId() {\n return ChainToChainId[this.chain];\n }\n\n // THOR.RUNE\n // THOR.ETH.ETH\n // ETH.THOR-0x1234567890\n static fromUrl(urlAsset: string, value: NumberPrimitives = 0) {\n const [chain, ticker, symbol] = urlAsset.split(\".\");\n if (!(chain && ticker)) throw new Error(\"Invalid asset url\");\n\n const assetString =\n chain === Chain.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset;\n\n return createAssetValue(assetString, value);\n }\n\n static fromString(assetString: string, value: NumberPrimitives = 0) {\n return createAssetValue(assetString, value);\n }\n static fromIdentifier(\n assetString:\n | `${Chain}.${string}`\n | `${Chain}/${string}`\n | `${Chain}.${string}-${string}`\n | TokenNames,\n value: NumberPrimitives = 0,\n ) {\n return createAssetValue(assetString, value);\n }\n\n static fromStringSync(assetString: string, value: NumberPrimitives = 0) {\n const { chain, isSynthetic } = getAssetInfo(assetString);\n const tokenInfo = staticTokensMap.get(assetString.toUpperCase() as TokenNames);\n\n if (isSynthetic) return createSyntheticAssetValue(assetString, value);\n // TODO: write logger that will only run in dev mode with some flag\n // if (!tokenInfo) {\n // console.error(\n // `Asset ${assetString} is not loaded. Use AssetValue.loadStaticAssets() to load it`,\n // );\n // }\n\n const { tax, decimal, identifier } = tokenInfo || {\n decimal: BaseDecimal[chain],\n identifier: assetString,\n };\n\n return new AssetValue({\n tax,\n value: safeValue(value, decimal),\n identifier: isSynthetic ? assetString : identifier,\n decimal: isSynthetic ? 8 : decimal,\n });\n }\n\n static async fromStringWithBase(\n assetString: string,\n value: NumberPrimitives = 0,\n baseDecimal: number = BaseDecimal.THOR,\n ) {\n const shiftedAmount = BigIntArithmetics.shiftDecimals({\n value: SwapKitNumber.fromBigInt(BigInt(value)),\n from: 0,\n to: baseDecimal,\n }).getBaseValue(\"string\");\n const assetValue = await AssetValue.fromString(assetString, value);\n\n return assetValue.set(shiftedAmount);\n }\n\n static fromStringWithBaseSync(\n assetString: string,\n value: NumberPrimitives = 0,\n baseDecimal: number = BaseDecimal.THOR,\n ) {\n const { chain, isSynthetic } = getAssetInfo(assetString);\n const tokenInfo = staticTokensMap.get(assetString.toUpperCase() as TokenNames);\n\n if (isSynthetic) return createSyntheticAssetValue(assetString, value);\n\n const { tax, decimal, identifier } = tokenInfo || {\n decimal: BaseDecimal[chain],\n identifier: assetString,\n };\n\n return new AssetValue({\n tax,\n value: safeValue(BigInt(value), baseDecimal),\n identifier,\n decimal,\n });\n }\n\n static fromIdentifierSync(assetString: TokenNames, value: NumberPrimitives = 0) {\n const { chain, isSynthetic } = getAssetInfo(assetString);\n const tokenInfo = staticTokensMap.get(assetString);\n\n if (isSynthetic) return createSyntheticAssetValue(assetString, value);\n // TODO: write logger that will only run in dev mode with some flag\n // if (!tokenInfo) {\n // console.error(\n // `Asset ${assetString} is not loaded. - Loading with base Chain. Use AssetValue.loadStaticAssets() to load it`,\n // );\n // }\n\n const { tax, decimal, identifier } = tokenInfo || {\n decimal: BaseDecimal[chain],\n identifier: assetString,\n };\n return new AssetValue({ tax, decimal, identifier, value: safeValue(value, decimal) });\n }\n\n static fromChainOrSignature(assetString: CommonAssetString, value: NumberPrimitives = 0) {\n const { decimal, identifier } = getCommonAssetInfo(assetString);\n return new AssetValue({ value: safeValue(value, decimal), decimal, identifier });\n }\n\n static loadStaticAssets() {\n return new Promise<{ ok: true } | { ok: false; message: string; error: Todo }>(\n (resolve, reject) => {\n try {\n import(\"@swapkit/tokens\").then((tokenPackages) => {\n for (const tokenList of Object.values(tokenPackages)) {\n for (const { identifier, chain, ...rest } of tokenList.tokens) {\n staticTokensMap.set(identifier.toUpperCase() as TokenNames, {\n identifier,\n decimal: \"decimals\" in rest ? rest.decimals : BaseDecimal[chain as Chain],\n });\n }\n }\n\n resolve({ ok: true });\n });\n } catch (error) {\n console.error(error);\n reject({\n ok: false,\n error,\n message:\n \"Couldn't load static assets. Ensure you have installed @swapkit/tokens package\",\n });\n }\n },\n );\n }\n}\n\nexport function getMinAmountByChain(chain: Chain) {\n const asset = AssetValue.fromChainOrSignature(chain);\n\n switch (chain) {\n case Chain.Bitcoin:\n case Chain.Litecoin:\n case Chain.BitcoinCash:\n return asset.set(0.00010001);\n\n case Chain.Dogecoin:\n return asset.set(1.00000001);\n\n case Chain.Avalanche:\n case Chain.Ethereum:\n return asset.set(0.00000001);\n\n case Chain.THORChain:\n case Chain.Maya:\n return asset.set(0);\n\n case Chain.Cosmos:\n return asset.set(0.000001);\n\n default:\n return asset.set(0.00000001);\n }\n}\n\nasync function createAssetValue(identifier: string, value: NumberPrimitives = 0) {\n validateIdentifier(identifier);\n\n const staticToken = staticTokensMap.get(identifier.toUpperCase() as TokenNames);\n const decimal = staticToken?.decimal || (await getDecimal(getAssetInfo(identifier)));\n if (!staticToken) {\n staticTokensMap.set(identifier.toUpperCase() as TokenNames, { identifier, decimal });\n }\n\n return new AssetValue({ decimal, value: safeValue(value, decimal), identifier });\n}\n\nfunction createSyntheticAssetValue(identifier: string, value: NumberPrimitives = 0) {\n const [synthChain, symbol] =\n identifier.split(\".\")?.[0]?.toUpperCase() === Chain.THORChain\n ? identifier.split(\".\").slice(1).join().split(\"/\")\n : identifier.split(\"/\");\n\n if (!(synthChain && symbol)) throw new Error(\"Invalid asset identifier\");\n\n return new AssetValue({\n decimal: 8,\n value: safeValue(value, 8),\n identifier: `${Chain.THORChain}.${synthChain}/${symbol}`,\n });\n}\n\nfunction safeValue(value: NumberPrimitives, decimal: number) {\n return typeof value === \"bigint\"\n ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })\n : value;\n}\n\n// TODO refactor & split into smaller functions\nfunction getAssetInfo(identifier: string) {\n const isSynthetic = identifier.slice(0, 14).includes(\"/\");\n\n const [synthChain, synthSymbol = \"\"] =\n identifier.split(\".\")?.[0]?.toUpperCase() === Chain.THORChain\n ? identifier.split(\".\").slice(1).join().split(\"/\")\n : identifier.split(\"/\");\n\n if (isSynthetic && !(synthChain && synthSymbol)) throw new Error(\"Invalid asset identifier\");\n\n const adjustedIdentifier =\n identifier.includes(\".\") && !isSynthetic ? identifier : `${Chain.THORChain}.${synthSymbol}`;\n\n const [chain, ...rest] = adjustedIdentifier.split(\".\") as [Chain, string];\n const [ticker, address] = (isSynthetic ? synthSymbol : rest.join(\".\")).split(\"-\") as [\n string,\n string?,\n ];\n const symbol = isSynthetic ? synthSymbol : rest.join(\".\");\n\n return {\n address: address?.toLowerCase(),\n chain,\n isGasAsset: isGasAsset({ chain, symbol }),\n isSynthetic,\n symbol:\n (isSynthetic ? `${synthChain}/` : \"\") +\n (address ? `${ticker}-${address?.toLowerCase() ?? \"\"}` : symbol),\n ticker,\n };\n}\n",
13
+ "import { Chain } from \"@swapkit/types\";\n\n// Backward compatibility\nconst supportedChains = [...Object.values(Chain), \"TERRA\"];\n\nexport function validateIdentifier(identifier = \"\") {\n const uppercasedIdentifier = identifier.toUpperCase();\n\n const [chain] = uppercasedIdentifier.split(\".\") as [Chain, string];\n if (supportedChains.includes(chain)) return true;\n\n const [synthChain] = uppercasedIdentifier.split(\"/\") as [Chain, string];\n if (supportedChains.includes(synthChain)) return true;\n\n throw new Error(\n `Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`,\n );\n}\n\nexport function validateTNS(name: string) {\n if (name.length > 30) return false;\n\n const regex = /^[a-zA-Z0-9+_-]+$/g;\n\n return !!name.match(regex);\n}\n",
14
+ "import { Chain } from \"@swapkit/types\";\n\n// Backward compatibility\nconst supportedChains = [...Object.values(Chain), \"TERRA\"];\n\nexport function validateIdentifier(identifier = \"\") {\n const uppercasedIdentifier = identifier.toUpperCase();\n\n const [chain] = uppercasedIdentifier.split(\".\") as [Chain, string];\n if (supportedChains.includes(chain)) return true;\n\n const [synthChain] = uppercasedIdentifier.split(\"/\") as [Chain, string];\n if (supportedChains.includes(synthChain)) return true;\n\n throw new Error(\n `Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`,\n );\n}\n\nexport function validateTNS(name: string) {\n if (name.length > 30) return false;\n\n const regex = /^[a-zA-Z0-9+_-]+$/g;\n\n return !!name.match(regex);\n}\n",
15
+ "import { BaseDecimal } from \"@swapkit/types\";\n\nimport type { SwapKitNumber } from \"./swapKitNumber.ts\";\n\ntype NumberPrimitivesType = {\n bigint: bigint;\n number: number;\n string: string;\n};\nexport type NumberPrimitives = bigint | number | string;\ntype InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber;\n\ntype SKBigIntParams = InitialisationValueType | { decimal?: number; value: number | string };\ntype AllowedNumberTypes = \"bigint\" | \"number\" | \"string\";\n\nconst DEFAULT_DECIMAL = 8;\nconst toMultiplier = (decimal: number) => 10n ** BigInt(decimal);\nconst decimalFromMultiplier = (multiplier: bigint) =>\n Math.log10(Number.parseFloat(multiplier.toString()));\n\nexport function formatBigIntToSafeValue({\n value,\n bigIntDecimal = DEFAULT_DECIMAL,\n decimal = DEFAULT_DECIMAL,\n}: {\n value: bigint;\n bigIntDecimal?: number;\n decimal?: number;\n}) {\n if (decimal === 0) return value.toString();\n const isNegative = value < 0n;\n let valueString = value.toString().substring(isNegative ? 1 : 0);\n\n const padLength = decimal - (valueString.length - 1);\n\n if (padLength > 0) {\n valueString = \"0\".repeat(padLength) + valueString;\n }\n\n const decimalIndex = valueString.length - decimal;\n let decimalString = valueString.slice(-decimal);\n\n // Check if we need to round up\n if (Number.parseInt(decimalString[bigIntDecimal] || \"0\") >= 5) {\n // Increment the last decimal place and slice off the rest\n decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(\n Number.parseInt(decimalString[bigIntDecimal - 1] || \"0\") + 1\n ).toString()}`;\n } else {\n // Just slice off the extra digits\n decimalString = decimalString.substring(0, bigIntDecimal);\n }\n\n return `${isNegative ? \"-\" : \"\"}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(\n /\\.?0*$/,\n \"\",\n );\n}\n\nexport class BigIntArithmetics {\n decimalMultiplier: bigint = 10n ** 8n;\n bigIntValue = 0n;\n decimal?: number;\n\n static fromBigInt(value: bigint, decimal?: number) {\n return new BigIntArithmetics({\n decimal,\n value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }),\n });\n }\n\n static shiftDecimals({\n value,\n from,\n to,\n }: {\n value: InstanceType<typeof SwapKitNumber>;\n from: number;\n to: number;\n }) {\n return BigIntArithmetics.fromBigInt(\n (value.getBaseValue(\"bigint\") * toMultiplier(to)) / toMultiplier(from),\n to,\n );\n }\n\n constructor(params: SKBigIntParams) {\n const value = getStringValue(params);\n const isComplex = typeof params === \"object\";\n this.decimal = isComplex ? params.decimal : undefined;\n\n // use the multiplier to keep track of decimal point - defaults to 8 if lower than 8\n this.decimalMultiplier =\n isComplex && \"decimalMultiplier\" in params\n ? params.decimalMultiplier\n : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0));\n this.#setValue(value);\n }\n\n set(value: SKBigIntParams): this {\n // @ts-expect-error False positive\n return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });\n }\n add(...args: InitialisationValueType[]) {\n return this.#arithmetics(\"add\", ...args);\n }\n sub(...args: InitialisationValueType[]) {\n return this.#arithmetics(\"sub\", ...args);\n }\n mul(...args: InitialisationValueType[]) {\n return this.#arithmetics(\"mul\", ...args);\n }\n div(...args: InitialisationValueType[]) {\n return this.#arithmetics(\"div\", ...args);\n }\n gt(value: InitialisationValueType) {\n return this.#comparison(\"gt\", value);\n }\n gte(value: InitialisationValueType) {\n return this.#comparison(\"gte\", value);\n }\n lt(value: InitialisationValueType) {\n return this.#comparison(\"lt\", value);\n }\n lte(value: InitialisationValueType) {\n return this.#comparison(\"lte\", value);\n }\n eqValue(value: InitialisationValueType) {\n return this.#comparison(\"eqValue\", value);\n }\n\n // @ts-expect-error False positive\n getValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T] {\n const value = this.formatBigIntToSafeValue(\n this.bigIntValue,\n this.decimal || decimalFromMultiplier(this.decimalMultiplier),\n );\n\n switch (type) {\n case \"number\":\n return Number(value) as NumberPrimitivesType[T];\n case \"string\":\n return value as NumberPrimitivesType[T];\n case \"bigint\":\n return ((this.bigIntValue * 10n ** BigInt(this.decimal || 8n)) /\n this.decimalMultiplier) as NumberPrimitivesType[T];\n }\n }\n\n // @ts-expect-error\n getBaseValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T] {\n const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);\n const baseValue = this.bigIntValue / divisor;\n\n switch (type) {\n case \"number\":\n return Number(baseValue) as NumberPrimitivesType[T];\n case \"string\":\n return baseValue.toString() as NumberPrimitivesType[T];\n case \"bigint\":\n return baseValue as NumberPrimitivesType[T];\n }\n }\n\n getBigIntValue(value: InitialisationValueType, decimal?: number) {\n if (!decimal && typeof value === \"object\") return value.bigIntValue;\n\n const stringValue = getStringValue(value);\n const safeValue = toSafeValue(stringValue);\n\n if (safeValue === \"0\" || safeValue === \"undefined\") return 0n;\n return this.#toBigInt(safeValue, decimal);\n }\n\n toSignificant(significantDigits = 6) {\n const [int, dec] = this.getValue(\"string\").split(\".\");\n const integer = int || \"\";\n const decimal = dec || \"\";\n const valueLength = Number.parseInt(integer) ? integer.length + decimal.length : decimal.length;\n\n if (valueLength <= significantDigits) {\n return this.getValue(\"string\");\n }\n\n if (integer.length >= significantDigits) {\n return integer.slice(0, significantDigits).padEnd(integer.length, \"0\");\n }\n\n if (Number.parseInt(integer)) {\n return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(\n significantDigits - integer.length,\n \"0\",\n );\n }\n\n const trimmedDecimal = Number.parseInt(decimal);\n const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits);\n\n return `0.${slicedDecimal.padStart(\n decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length,\n \"0\",\n )}`;\n }\n\n toFixed(fixedDigits = 6) {\n const [int, dec] = this.getValue(\"string\").split(\".\");\n const integer = int || \"\";\n const decimal = dec || \"\";\n\n if (Number.parseInt(integer)) {\n return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, \"0\");\n }\n\n const trimmedDecimal = Number.parseInt(decimal);\n const slicedDecimal = `${trimmedDecimal}`.slice(0, fixedDigits);\n\n return `0.${slicedDecimal.padStart(\n decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length,\n \"0\",\n )}`;\n }\n\n toAbbreviation(digits = 2) {\n const value = this.getValue(\"number\");\n const abbreviations = [\"\", \"K\", \"M\", \"B\", \"T\", \"Q\", \"Qi\", \"S\"];\n const tier = Math.floor(Math.log10(Math.abs(value)) / 3);\n const suffix = abbreviations[tier];\n\n if (!suffix) return this.getValue(\"string\");\n\n const scale = 10 ** (tier * 3);\n const scaled = value / scale;\n\n return `${scaled.toFixed(digits)}${suffix}`;\n }\n\n toCurrency(\n currency = \"$\",\n {\n currencyPosition = \"start\",\n decimal = 2,\n decimalSeparator = \".\",\n thousandSeparator = \",\",\n } = {},\n ) {\n const value = this.getValue(\"number\");\n const [int = \"\", dec = \"\"] = value.toFixed(6).split(\".\");\n const integer = int.replace(/\\B(?=(\\d{3})+(?!\\d))/g, thousandSeparator);\n\n const parsedValue =\n int || dec\n ? int === \"0\"\n ? `${Number.parseFloat(`0.${dec}`)}`.replace(\".\", decimalSeparator)\n : `${integer}${Number.parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : \"\"}`\n : \"0.00\";\n\n return `${currencyPosition === \"start\" ? currency : \"\"}${parsedValue}${\n currencyPosition === \"end\" ? currency : \"\"\n }`;\n }\n\n formatBigIntToSafeValue(value: bigint, decimal?: number) {\n const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;\n const decimalToUseForConversion = Math.max(\n bigIntDecimal,\n decimalFromMultiplier(this.decimalMultiplier),\n );\n const isNegative = value < 0n;\n\n const valueString = value.toString().substring(isNegative ? 1 : 0);\n const padLength = decimalToUseForConversion - (valueString.length - 1);\n\n const parsedValueString = padLength > 0 ? \"0\".repeat(padLength) + valueString : valueString;\n\n const decimalIndex = parsedValueString.length - decimalToUseForConversion;\n let decimalString = parsedValueString.slice(-decimalToUseForConversion);\n\n // Check if we need to round up\n if (Number.parseInt(decimalString[bigIntDecimal] || \"0\") >= 5) {\n // Increment the last decimal place and slice off the rest\n decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(\n Number.parseInt(decimalString[bigIntDecimal - 1] || \"0\") + 1\n ).toString()}`;\n } else {\n // Just slice off the extra digits\n decimalString = decimalString.substring(0, bigIntDecimal);\n }\n\n return `${isNegative ? \"-\" : \"\"}${parsedValueString.slice(\n 0,\n decimalIndex,\n )}.${decimalString}`.replace(/\\.?0*$/, \"\");\n }\n\n #arithmetics(method: \"add\" | \"sub\" | \"mul\" | \"div\", ...args: InitialisationValueType[]): this {\n const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);\n const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier));\n const precisionDecimalMultiplier = toMultiplier(decimal);\n\n const result = args.reduce(\n (acc: bigint, arg) => {\n const value = this.getBigIntValue(arg, decimal);\n\n switch (method) {\n case \"add\":\n return acc + value;\n case \"sub\":\n return acc - value;\n /**\n * Multiplication & division would end up with wrong result if we don't adjust the value\n * 200000000n * 200000000n => 40000000000000000n\n * 200000000n / 200000000n => 1n\n * So we do the following:\n * 200000000n * 200000000n = 40000000000000000n / 100000000n (decimals) => 400000000n\n * (200000000n * 100000000n (decimals)) / 200000000n => 100000000n\n */\n case \"mul\":\n return (acc * value) / precisionDecimalMultiplier;\n case \"div\": {\n if (value === 0n) throw new RangeError(\"Division by zero\");\n return (acc * precisionDecimalMultiplier) / value;\n }\n default:\n return acc;\n }\n },\n //normalize is to precision multiplier base\n (this.bigIntValue * precisionDecimalMultiplier) / this.decimalMultiplier,\n );\n\n const value = formatBigIntToSafeValue({\n bigIntDecimal: decimal,\n decimal,\n value: result,\n });\n\n // @ts-expect-error False positive\n return new this.constructor({\n decimalMultiplier: toMultiplier(decimal),\n decimal: this.decimal,\n value,\n identifier: this.toString(),\n });\n }\n\n #comparison(method: \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"eqValue\", ...args: InitialisationValueType[]) {\n const decimal = this.#retrievePrecisionDecimal(this, ...args);\n const value = this.getBigIntValue(args[0] || \"0\", decimal);\n const compareToValue = this.getBigIntValue(this, decimal);\n\n switch (method) {\n case \"gt\":\n return compareToValue > value;\n case \"gte\":\n return compareToValue >= value;\n case \"lt\":\n return compareToValue < value;\n case \"lte\":\n return compareToValue <= value;\n case \"eqValue\":\n return compareToValue === value;\n }\n }\n\n #setValue(value: InitialisationValueType) {\n const safeValue = toSafeValue(value) || \"0\";\n this.bigIntValue = this.#toBigInt(safeValue);\n }\n\n #retrievePrecisionDecimal(...args: InitialisationValueType[]) {\n const decimals = args\n .map((arg) => {\n const isObject = typeof arg === \"object\";\n const value = isObject\n ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier)\n : getFloatDecimals(toSafeValue(arg));\n\n return value;\n })\n .filter(Boolean) as number[];\n\n return Math.max(...decimals, DEFAULT_DECIMAL);\n }\n\n #toBigInt(value: string, decimal?: number) {\n const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;\n const padDecimal = decimalFromMultiplier(multiplier);\n const [integerPart = \"\", decimalPart = \"\"] = value.split(\".\");\n\n return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, \"0\")}`);\n }\n}\n\nconst numberFormatter = Intl.NumberFormat(\"fullwide\", {\n useGrouping: false,\n maximumFractionDigits: 20,\n});\n\nfunction toSafeValue(value: InitialisationValueType) {\n const parsedValue =\n typeof value === \"number\" ? numberFormatter.format(value) : getStringValue(value);\n const splitValue = `${parsedValue}`.replaceAll(\",\", \".\").split(\".\");\n\n return splitValue.length > 1\n ? `${splitValue.slice(0, -1).join(\"\")}.${splitValue.at(-1)}`\n : splitValue[0] || \"0\";\n}\n\nfunction getFloatDecimals(value: string) {\n const decimals = value.split(\".\")[1]?.length || 0;\n return Math.max(decimals, DEFAULT_DECIMAL);\n}\n\nfunction getStringValue(param: SKBigIntParams) {\n return typeof param === \"object\"\n ? \"getValue\" in param\n ? param.getValue(\"string\")\n : param.value\n : param;\n}\n",
16
+ "import { BigIntArithmetics, formatBigIntToSafeValue } from \"./bigIntArithmetics.ts\";\n\nexport type SwapKitValueType = BigIntArithmetics | string | number;\n\nexport class SwapKitNumber extends BigIntArithmetics {\n eq(value: SwapKitValueType) {\n return this.eqValue(value);\n }\n\n static fromBigInt(value: bigint, decimal?: number) {\n return new SwapKitNumber({\n decimal,\n value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }),\n });\n }\n}\n",
17
+ "import { BaseDecimal, Chain, ChainToChainId } from \"@swapkit/types\";\n\nimport type { CommonAssetString } from \"../helpers/asset.ts\";\nimport { getAssetType, getCommonAssetInfo, getDecimal, isGasAsset } from \"../helpers/asset.ts\";\nimport { validateIdentifier } from \"../helpers/validators.ts\";\nimport type { TokenNames, TokenTax } from \"../types.ts\";\n\nimport type { NumberPrimitives } from \"./bigIntArithmetics.ts\";\nimport { BigIntArithmetics, formatBigIntToSafeValue } from \"./bigIntArithmetics.ts\";\nimport { SwapKitNumber, type SwapKitValueType } from \"./swapKitNumber.ts\";\n\nconst staticTokensMap = new Map<\n TokenNames,\n { tax?: TokenTax; decimal: number; identifier: string }\n>();\n\nexport class AssetValue extends BigIntArithmetics {\n address?: string;\n chain: Chain;\n isGasAsset = false;\n isSynthetic = false;\n symbol: string;\n tax?: TokenTax;\n ticker: string;\n type: ReturnType<typeof getAssetType>;\n\n constructor({\n value,\n decimal,\n tax,\n chain,\n symbol,\n identifier,\n }: { decimal: number; value: SwapKitValueType; tax?: TokenTax } & (\n | { chain: Chain; symbol: string; identifier?: never }\n | { identifier: string; chain?: never; symbol?: never }\n )) {\n super(typeof value === \"object\" ? value : { decimal, value });\n\n const assetInfo = getAssetInfo(identifier || `${chain}.${symbol}`);\n\n this.type = getAssetType(assetInfo);\n this.tax = tax;\n this.chain = assetInfo.chain;\n this.ticker = assetInfo.ticker;\n this.symbol = assetInfo.symbol;\n this.address = assetInfo.address;\n this.isSynthetic = assetInfo.isSynthetic;\n this.isGasAsset = assetInfo.isGasAsset;\n }\n\n toString() {\n return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;\n }\n\n toUrl() {\n return this.isSynthetic ? `${this.chain}.${this.symbol.replace(\"/\", \".\")}` : this.toString();\n }\n\n eq({ chain, symbol }: { chain: Chain; symbol: string }) {\n return this.chain === chain && this.symbol === symbol;\n }\n\n chainId() {\n return ChainToChainId[this.chain];\n }\n\n // THOR.RUNE\n // THOR.ETH.ETH\n // ETH.THOR-0x1234567890\n static fromUrl(urlAsset: string, value: NumberPrimitives = 0) {\n const [chain, ticker, symbol] = urlAsset.split(\".\");\n if (!(chain && ticker)) throw new Error(\"Invalid asset url\");\n\n const assetString =\n chain === Chain.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset;\n\n return createAssetValue(assetString, value);\n }\n\n static fromString(assetString: string, value: NumberPrimitives = 0) {\n return createAssetValue(assetString, value);\n }\n static fromIdentifier(\n assetString:\n | `${Chain}.${string}`\n | `${Chain}/${string}`\n | `${Chain}.${string}-${string}`\n | TokenNames,\n value: NumberPrimitives = 0,\n ) {\n return createAssetValue(assetString, value);\n }\n\n static fromStringSync(assetString: string, value: NumberPrimitives = 0) {\n const { chain, isSynthetic } = getAssetInfo(assetString);\n const tokenInfo = staticTokensMap.get(assetString.toUpperCase() as TokenNames);\n\n if (isSynthetic) return createSyntheticAssetValue(assetString, value);\n // TODO: write logger that will only run in dev mode with some flag\n // if (!tokenInfo) {\n // console.error(\n // `Asset ${assetString} is not loaded. Use AssetValue.loadStaticAssets() to load it`,\n // );\n // }\n\n const { tax, decimal, identifier } = tokenInfo || {\n decimal: BaseDecimal[chain],\n identifier: assetString,\n };\n\n return new AssetValue({\n tax,\n value: safeValue(value, decimal),\n identifier: isSynthetic ? assetString : identifier,\n decimal: isSynthetic ? 8 : decimal,\n });\n }\n\n static async fromStringWithBase(\n assetString: string,\n value: NumberPrimitives = 0,\n baseDecimal: number = BaseDecimal.THOR,\n ) {\n const shiftedAmount = BigIntArithmetics.shiftDecimals({\n value: SwapKitNumber.fromBigInt(BigInt(value)),\n from: 0,\n to: baseDecimal,\n }).getBaseValue(\"string\");\n const assetValue = await AssetValue.fromString(assetString, value);\n\n return assetValue.set(shiftedAmount);\n }\n\n static fromStringWithBaseSync(\n assetString: string,\n value: NumberPrimitives = 0,\n baseDecimal: number = BaseDecimal.THOR,\n ) {\n const { chain, isSynthetic } = getAssetInfo(assetString);\n const tokenInfo = staticTokensMap.get(assetString.toUpperCase() as TokenNames);\n\n if (isSynthetic) return createSyntheticAssetValue(assetString, value);\n\n const { tax, decimal, identifier } = tokenInfo || {\n decimal: BaseDecimal[chain],\n identifier: assetString,\n };\n\n return new AssetValue({\n tax,\n value: safeValue(BigInt(value), baseDecimal),\n identifier,\n decimal,\n });\n }\n\n static fromIdentifierSync(assetString: TokenNames, value: NumberPrimitives = 0) {\n const { chain, isSynthetic } = getAssetInfo(assetString);\n const tokenInfo = staticTokensMap.get(assetString);\n\n if (isSynthetic) return createSyntheticAssetValue(assetString, value);\n // TODO: write logger that will only run in dev mode with some flag\n // if (!tokenInfo) {\n // console.error(\n // `Asset ${assetString} is not loaded. - Loading with base Chain. Use AssetValue.loadStaticAssets() to load it`,\n // );\n // }\n\n const { tax, decimal, identifier } = tokenInfo || {\n decimal: BaseDecimal[chain],\n identifier: assetString,\n };\n return new AssetValue({ tax, decimal, identifier, value: safeValue(value, decimal) });\n }\n\n static fromChainOrSignature(assetString: CommonAssetString, value: NumberPrimitives = 0) {\n const { decimal, identifier } = getCommonAssetInfo(assetString);\n return new AssetValue({ value: safeValue(value, decimal), decimal, identifier });\n }\n\n static loadStaticAssets() {\n return new Promise<{ ok: true } | { ok: false; message: string; error: Todo }>(\n (resolve, reject) => {\n try {\n import(\"@swapkit/tokens\").then((tokenPackages) => {\n for (const tokenList of Object.values(tokenPackages)) {\n for (const { identifier, chain, ...rest } of tokenList.tokens) {\n staticTokensMap.set(identifier.toUpperCase() as TokenNames, {\n identifier,\n decimal: \"decimals\" in rest ? rest.decimals : BaseDecimal[chain as Chain],\n });\n }\n }\n\n resolve({ ok: true });\n });\n } catch (error) {\n console.error(error);\n reject({\n ok: false,\n error,\n message:\n \"Couldn't load static assets. Ensure you have installed @swapkit/tokens package\",\n });\n }\n },\n );\n }\n}\n\nexport function getMinAmountByChain(chain: Chain) {\n const asset = AssetValue.fromChainOrSignature(chain);\n\n switch (chain) {\n case Chain.Bitcoin:\n case Chain.Litecoin:\n case Chain.BitcoinCash:\n return asset.set(0.00010001);\n\n case Chain.Dogecoin:\n return asset.set(1.00000001);\n\n case Chain.Avalanche:\n case Chain.Ethereum:\n return asset.set(0.00000001);\n\n case Chain.THORChain:\n case Chain.Maya:\n return asset.set(0);\n\n case Chain.Cosmos:\n return asset.set(0.000001);\n\n default:\n return asset.set(0.00000001);\n }\n}\n\nasync function createAssetValue(identifier: string, value: NumberPrimitives = 0) {\n validateIdentifier(identifier);\n\n const staticToken = staticTokensMap.get(identifier.toUpperCase() as TokenNames);\n const decimal = staticToken?.decimal || (await getDecimal(getAssetInfo(identifier)));\n if (!staticToken) {\n staticTokensMap.set(identifier.toUpperCase() as TokenNames, { identifier, decimal });\n }\n\n return new AssetValue({ decimal, value: safeValue(value, decimal), identifier });\n}\n\nfunction createSyntheticAssetValue(identifier: string, value: NumberPrimitives = 0) {\n const [synthChain, symbol] =\n identifier.split(\".\")?.[0]?.toUpperCase() === Chain.THORChain\n ? identifier.split(\".\").slice(1).join().split(\"/\")\n : identifier.split(\"/\");\n\n if (!(synthChain && symbol)) throw new Error(\"Invalid asset identifier\");\n\n return new AssetValue({\n decimal: 8,\n value: safeValue(value, 8),\n identifier: `${Chain.THORChain}.${synthChain}/${symbol}`,\n });\n}\n\nfunction safeValue(value: NumberPrimitives, decimal: number) {\n return typeof value === \"bigint\"\n ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })\n : value;\n}\n\n// TODO refactor & split into smaller functions\nfunction getAssetInfo(identifier: string) {\n const isSynthetic = identifier.slice(0, 14).includes(\"/\");\n\n const [synthChain, synthSymbol = \"\"] =\n identifier.split(\".\")?.[0]?.toUpperCase() === Chain.THORChain\n ? identifier.split(\".\").slice(1).join().split(\"/\")\n : identifier.split(\"/\");\n\n if (isSynthetic && !(synthChain && synthSymbol)) throw new Error(\"Invalid asset identifier\");\n\n const adjustedIdentifier =\n identifier.includes(\".\") && !isSynthetic ? identifier : `${Chain.THORChain}.${synthSymbol}`;\n\n const [chain, ...rest] = adjustedIdentifier.split(\".\") as [Chain, string];\n const [ticker, address] = (isSynthetic ? synthSymbol : rest.join(\".\")).split(\"-\") as [\n string,\n string?,\n ];\n const symbol = isSynthetic ? synthSymbol : rest.join(\".\");\n\n return {\n address: address?.toLowerCase(),\n chain,\n isGasAsset: isGasAsset({ chain, symbol }),\n isSynthetic,\n symbol:\n (isSynthetic ? `${synthChain}/` : \"\") +\n (address ? `${ticker}-${address?.toLowerCase() ?? \"\"}` : symbol),\n ticker,\n };\n}\n"
18
+ ],
19
+ "m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Ac,MAAM,MAAM,MAAM,GAAG;AAE5D,WAAO,OAAO,GAAG,cAAc,YAAY,OAAO,YAAY,GAAG,GAAG;AAAA;AAExE;AAEA,IAAM,kBAAkB,KAAK,aAAa,YAAY;AAAA,EACpD,aAAa;AAAA,EACb,uBAAuB;AACzB,CAAC;;;ACxYM,MAAM,sBAAsB,kBAAkB;AAAA,EAA9C;AAAA;AAAA;AAAA,EACL,EAAE,CAAC,OAAyB;AAC1B,WAAO,KAAK,QAAQ,KAAK;AAAA;AAAA,SAGpB,UAAU,CAAC,OAAe,SAAkB;AACjD,WAAO,IAAI,cAAc;AAAA,MACvB;AAAA,MACA,OAAO,wBAAwB,EAAE,OAAO,eAAe,SAAS,QAAQ,CAAC;AAAA,IAC3E,CAAC;AAAA;AAEL;",
20
+ "debugId": "73252CC82EFDBB7564756e2164756e21",
21
+ "names": []
22
+ }
package/package.json CHANGED
@@ -1,27 +1,18 @@
1
1
  {
2
2
  "author": "swapkit-oss",
3
- "description": "SwapKit Lib swapkit-helpers",
3
+ "description": "SwapKit - Helpers",
4
4
  "dependencies": {
5
- "@swapkit/api": "1.0.0-rc.48"
5
+ "@swapkit/api": "1.0.0-rc.49"
6
6
  },
7
7
  "devDependencies": {
8
- "@vitest/coverage-istanbul": "1.4.0",
9
- "vite": "5.1.6",
10
- "vitest": "1.4.0",
11
- "@swapkit/tokens": "1.0.0-rc.44",
12
- "@swapkit/types": "1.0.0-rc.47"
8
+ "@swapkit/tokens": "1.0.0-rc.45",
9
+ "@swapkit/types": "1.0.0-rc.48",
10
+ "bun-types": "1.1.1"
13
11
  },
14
12
  "peerDependencies": {
15
- "@swapkit/api": "1.0.0-rc.48",
16
- "@swapkit/tokens": "1.0.0-rc.44",
17
- "@swapkit/types": "1.0.0-rc.47"
18
- },
19
- "exports": {
20
- ".": {
21
- "import": "./dist/index.es.js",
22
- "require": "./dist/index.cjs",
23
- "types": "./dist/index.d.ts"
24
- }
13
+ "@swapkit/api": "1.0.0-rc.49",
14
+ "@swapkit/tokens": "1.0.0-rc.45",
15
+ "@swapkit/types": "1.0.0-rc.48"
25
16
  },
26
17
  "files": [
27
18
  "src/",
@@ -29,22 +20,22 @@
29
20
  ],
30
21
  "homepage": "https://github.com/thorswap/SwapKit",
31
22
  "license": "Apache-2.0",
32
- "main": "./dist/index.cjs",
33
- "module": "./dist/index.es.js",
23
+ "main": "./dist/index.js",
34
24
  "name": "@swapkit/helpers",
35
25
  "react-native": "./src/index.ts",
36
26
  "repository": {
37
27
  "type": "git",
38
28
  "url": "git+https://github.com/thorswap/SwapKit.git"
39
29
  },
40
- "type": "module",
41
- "types": "./dist/index.d.ts",
42
- "version": "1.0.0-rc.83",
43
30
  "scripts": {
44
- "build": "vite build",
45
- "clean": "rm -rf dist vite.config.ts.* node_modules",
31
+ "build": "bun run ./build.ts",
32
+ "clean": "rm -rf .turbo dist node_modules tsconfig.tsbuildinfo",
46
33
  "lint": "biome check --apply ./src",
47
- "test": "vitest --run",
48
- "test:coverage": "vitest run --coverage"
49
- }
50
- }
34
+ "test": "bun test",
35
+ "test:coverage": "echo 'bun test --coverage'",
36
+ "type-check": "tsc --noEmit"
37
+ },
38
+ "type": "module",
39
+ "types": "./src/index.ts",
40
+ "version": "1.0.0-rc.84"
41
+ }
@@ -1,5 +1,5 @@
1
+ import { describe, expect, test } from "bun:test";
1
2
  import { BaseDecimal, Chain } from "@swapkit/types";
2
- import { describe, expect, test } from "vitest";
3
3
 
4
4
  import { getAssetType, getDecimal } from "../asset.ts";
5
5
 
@@ -76,84 +76,100 @@ describe("getDecimal", () => {
76
76
 
77
77
  for (const chain of filteredChains) {
78
78
  describe(chain, () => {
79
- test(`returns proper decimal for native ${chain} asset`, async () => {
80
- const decimal = await getDecimal({ chain, symbol: chain });
81
- expect(decimal).toBe(BaseDecimal[chain]);
82
- });
79
+ test(
80
+ `returns proper decimal for native ${chain} asset`,
81
+ async () => {
82
+ const decimal = await getDecimal({ chain, symbol: chain });
83
+ expect(decimal).toBe(BaseDecimal[chain]);
84
+ },
85
+ { retry: 3 },
86
+ );
83
87
  });
84
88
  }
85
89
 
86
90
  describe("ETH", () => {
87
- test("returns proper decimal for eth and it's assets", async () => {
88
- const ethDecimal = await getDecimal({ chain: Chain.Ethereum, symbol: "ETH" });
89
- expect(ethDecimal).toBe(BaseDecimal.ETH);
90
-
91
- const usdcDecimal = await getDecimal({
92
- chain: Chain.Ethereum,
93
- symbol: "USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
94
- });
95
- expect(usdcDecimal).toBe(6);
96
-
97
- const wbtcDecimal = await getDecimal({
98
- chain: Chain.Ethereum,
99
- symbol: "WBTC-0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
100
- });
101
- expect(wbtcDecimal).toBe(8);
91
+ test(
92
+ "returns proper decimal for eth and it's assets",
93
+ async () => {
94
+ const ethDecimal = await getDecimal({ chain: Chain.Ethereum, symbol: "ETH" });
95
+ expect(ethDecimal).toBe(BaseDecimal.ETH);
96
+ await Bun.sleep(500);
97
+
98
+ const usdcDecimal = await getDecimal({
99
+ chain: Chain.Ethereum,
100
+ symbol: "USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
101
+ });
102
+ expect(usdcDecimal).toBe(6);
103
+ await Bun.sleep(500);
102
104
 
103
- const decDecimal = await getDecimal({
104
- chain: Chain.Ethereum,
105
- symbol: "ZIL-0x05f4a42e251f2d52b8ed15e9fedaacfcef1fad27",
106
- });
107
- expect(decDecimal).toBe(12);
105
+ const wbtcDecimal = await getDecimal({
106
+ chain: Chain.Ethereum,
107
+ symbol: "WBTC-0x2260fac5e5542a773aa44fbcfedf7c193bc2c599",
108
+ });
109
+ expect(wbtcDecimal).toBe(8);
110
+ await Bun.sleep(500);
108
111
 
109
- const kindDecimal = await getDecimal({
110
- chain: Chain.Ethereum,
111
- symbol: "KIND-0x4618519de4c304f3444ffa7f812dddc2971cc688",
112
- });
113
- expect(kindDecimal).toBe(8);
112
+ const kindDecimal = await getDecimal({
113
+ chain: Chain.Ethereum,
114
+ symbol: "KIND-0x4618519de4c304f3444ffa7f812dddc2971cc688",
115
+ });
116
+ expect(kindDecimal).toBe(8);
117
+ await Bun.sleep(500);
114
118
 
115
- const shitcoinDecimal = await getDecimal({
116
- chain: Chain.Ethereum,
117
- symbol: "HOMI-0xCa208BfD69ae6D2667f1FCbE681BAe12767c0078",
118
- });
119
- expect(shitcoinDecimal).toBe(0);
120
- });
119
+ const shitcoinDecimal = await getDecimal({
120
+ chain: Chain.Ethereum,
121
+ symbol: "HOMI-0xCa208BfD69ae6D2667f1FCbE681BAe12767c0078",
122
+ });
123
+ expect(shitcoinDecimal).toBe(0);
124
+ await Bun.sleep(500);
125
+ },
126
+ { retry: 3 },
127
+ );
121
128
  });
122
129
 
123
130
  describe("AVAX", () => {
124
- test.skip("returns proper decimal for avax and it's assets", async () => {
125
- const avaxDecimal = await getDecimal({ chain: Chain.Avalanche, symbol: "AVAX" });
126
- expect(avaxDecimal).toBe(BaseDecimal.AVAX);
127
-
128
- const wbtceDecimal = await getDecimal({
129
- chain: Chain.Avalanche,
130
- symbol: "WBTC.e-0x50b7545627a5162f82a992c33b87adc75187b218",
131
- });
132
- expect(wbtceDecimal).toBe(8);
131
+ test(
132
+ "returns proper decimal for avax and it's assets",
133
+ async () => {
134
+ const avaxDecimal = await getDecimal({ chain: Chain.Avalanche, symbol: "AVAX" });
135
+ expect(avaxDecimal).toBe(BaseDecimal.AVAX);
136
+
137
+ const wbtceDecimal = await getDecimal({
138
+ chain: Chain.Avalanche,
139
+ symbol: "WBTC.e-0x50b7545627a5162f82a992c33b87adc75187b218",
140
+ });
141
+ expect(wbtceDecimal).toBe(8);
142
+ await Bun.sleep(500);
133
143
 
134
- const btcbDecimal = await getDecimal({
135
- chain: Chain.Avalanche,
136
- symbol: "BTC.b-0x152b9d0FdC40C096757F570A51E494bd4b943E50",
137
- });
138
- expect(btcbDecimal).toBe(8);
144
+ const btcbDecimal = await getDecimal({
145
+ chain: Chain.Avalanche,
146
+ symbol: "BTC.b-0x152b9d0FdC40C096757F570A51E494bd4b943E50",
147
+ });
148
+ expect(btcbDecimal).toBe(8);
149
+ await Bun.sleep(500);
139
150
 
140
- const timeDecimal = await getDecimal({
141
- chain: Chain.Avalanche,
142
- symbol: "TIME-0xb54f16fB19478766A268F172C9480f8da1a7c9C3",
143
- });
144
- expect(timeDecimal).toBe(9);
151
+ const timeDecimal = await getDecimal({
152
+ chain: Chain.Avalanche,
153
+ symbol: "TIME-0xb54f16fB19478766A268F172C9480f8da1a7c9C3",
154
+ });
155
+ expect(timeDecimal).toBe(9);
156
+ await Bun.sleep(500);
145
157
 
146
- const usdtDecimal = await getDecimal({
147
- chain: Chain.Avalanche,
148
- symbol: "USDT-0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",
149
- });
150
- expect(usdtDecimal).toBe(6);
158
+ const usdtDecimal = await getDecimal({
159
+ chain: Chain.Avalanche,
160
+ symbol: "USDT-0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",
161
+ });
162
+ expect(usdtDecimal).toBe(6);
163
+ await Bun.sleep(500);
151
164
 
152
- const usdcDecimal = await getDecimal({
153
- chain: Chain.Avalanche,
154
- symbol: "USDC-0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
155
- });
156
- expect(usdcDecimal).toBe(6);
157
- });
165
+ const usdcDecimal = await getDecimal({
166
+ chain: Chain.Avalanche,
167
+ symbol: "USDC-0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
168
+ });
169
+ expect(usdcDecimal).toBe(6);
170
+ await Bun.sleep(500);
171
+ },
172
+ { retry: 3 },
173
+ );
158
174
  });
159
175
  });
@@ -1,5 +1,5 @@
1
+ import { describe, expect, test } from "bun:test";
1
2
  import { Chain, MemoType } from "@swapkit/types";
2
- import { describe, expect, test } from "vitest";
3
3
 
4
4
  import { getMemoFor } from "../memo.ts";
5
5
 
@@ -10,7 +10,7 @@ describe("getMemoFor", () => {
10
10
  [MemoType.BOND, "BOND:ABC123"],
11
11
  ];
12
12
 
13
- for (const [memoType, expected] of nodeMemos) {
13
+ for (const [memoType, expected = ""] of nodeMemos) {
14
14
  test(`returns correct memo for ${memoType}`, () => {
15
15
  const result = getMemoFor(memoType as MemoType, { address: "ABC123" });
16
16
  expect(result).toBe(expected);
@@ -1,18 +1,18 @@
1
- import { Chain } from "@swapkit/types";
2
- import { describe, expect, test } from "vitest";
1
+ import { describe, expect, test } from "bun:test";
2
+ import { Chain, type DerivationPathArray } from "@swapkit/types";
3
3
 
4
4
  import { findAssetBy } from "../asset.ts";
5
- import { derivationPathToString, getTHORNameCost, validateTHORName } from "../others.ts";
5
+ import { derivationPathToString, getTHORNameCost } from "../others.ts";
6
6
 
7
7
  describe("derivationPathToString", () => {
8
8
  test("should return the correct string for a full path", () => {
9
- const path = [1, 2, 3, 4, 5];
10
- expect(derivationPathToString(path)).toEqual("1'/2'/3'/4/5");
9
+ const path = [1, 2, 3, 4, 5] as DerivationPathArray;
10
+ expect(derivationPathToString(path)).toEqual("m/1'/2'/3'/4/5");
11
11
  });
12
12
 
13
13
  test("should return the correct string for a short path", () => {
14
- const path = [1, 2, 3, 4];
15
- expect(derivationPathToString(path)).toEqual("1'/2'/3'/4");
14
+ const path = [1, 2, 3, 4] as DerivationPathArray;
15
+ expect(derivationPathToString(path)).toEqual("m/1'/2'/3'/4");
16
16
  });
17
17
  });
18
18
 
@@ -25,7 +25,7 @@ describe("getTHORNameCost", () => {
25
25
  [10, 20],
26
26
  ];
27
27
 
28
- for (const [years, expected] of costCases) {
28
+ for (const [years = 0, expected = 10] of costCases) {
29
29
  test(`returns correct ${expected} cost for ${years} years`, () => {
30
30
  const result = getTHORNameCost(years);
31
31
  expect(result).toBe(expected);
@@ -34,32 +34,10 @@ describe("getTHORNameCost", () => {
34
34
  });
35
35
 
36
36
  test("throws an error for negative years", () => {
37
- expect(() => getTHORNameCost(-1)).toThrowError("Invalid number of year");
37
+ expect(() => getTHORNameCost(-1)).toThrow("Invalid number of year");
38
38
  });
39
39
  });
40
40
 
41
- describe("validateTHORName", () => {
42
- const casesWithExpectation: [string, boolean][] = [
43
- ["validname", true],
44
- ["valid-name", true],
45
- ["valid_name", true],
46
- ["valid+name", true],
47
- ["name_with_numbers123", true],
48
- ["UPPER_CASE", true],
49
- ["toolongname123456789012345678901", false],
50
- ["invalid@name", false],
51
- ["invalid!name", false],
52
- ["invalid#name", false],
53
- ];
54
-
55
- for (const [name, expected] of casesWithExpectation) {
56
- test(`returns ${expected} for THORName "${name}"`, () => {
57
- const result = validateTHORName(name);
58
- expect(result).toBe(expected);
59
- });
60
- }
61
- });
62
-
63
41
  describe("getAssetBy", () => {
64
42
  test("find asset by identifier", async () => {
65
43
  const assetByIdentifier = await findAssetBy({ identifier: "ETH.ETH" });
@@ -80,7 +58,7 @@ describe("getAssetBy", () => {
80
58
  chain: Chain.Ethereum,
81
59
  contract: "NOTFOUND",
82
60
  });
83
- expect(assetByIdentifier).toBe(undefined);
84
- expect(assetByChainAndContract).toBe(undefined);
61
+ expect(assetByIdentifier).toBeUndefined();
62
+ expect(assetByChainAndContract).toBeUndefined();
85
63
  });
86
64
  });
@@ -0,0 +1,24 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { validateTNS } from "../validators";
3
+
4
+ describe("validateTNS", () => {
5
+ const casesWithExpectation: [string, boolean][] = [
6
+ ["validname", true],
7
+ ["valid-name", true],
8
+ ["valid_name", true],
9
+ ["valid+name", true],
10
+ ["name_with_numbers123", true],
11
+ ["UPPER_CASE", true],
12
+ ["toolongname123456789012345678901", false],
13
+ ["invalid@name", false],
14
+ ["invalid!name", false],
15
+ ["invalid#name", false],
16
+ ];
17
+
18
+ for (const [name, expected] of casesWithExpectation) {
19
+ test(`returns ${expected} for THORName "${name}"`, () => {
20
+ const result = validateTNS(name);
21
+ expect(result).toBe(expected);
22
+ });
23
+ }
24
+ });
@@ -28,7 +28,7 @@ const getContractDecimals = async ({ chain, to }: { chain: EVMChain; to: string
28
28
  }),
29
29
  });
30
30
 
31
- return Number.parseInt(BigInt(result).toString());
31
+ return Number.parseInt(BigInt(result || BaseDecimal[chain]).toString());
32
32
  } catch (error) {
33
33
  console.error(error);
34
34
  return BaseDecimal[chain];
@@ -1,3 +1,6 @@
1
+ import type { DerivationPathArray } from "@swapkit/types";
2
+ import { type ErrorKeys, SwapKitError } from "../modules/swapKitError";
3
+
1
4
  // 10 rune for register, 1 rune per year
2
5
  // MINIMUM_REGISTRATION_FEE = 11
3
6
  export function getTHORNameCost(year: number) {
@@ -13,30 +16,22 @@ export function getMAYANameCost(year: number) {
13
16
  return Math.round((10 + year * 1.0512) * 1e10) / 1e10;
14
17
  }
15
18
 
16
- export function validateTHORName(name: string) {
17
- if (name.length > 30) return false;
18
-
19
- const regex = /^[a-zA-Z0-9+_-]+$/g;
20
-
21
- return !!name.match(regex);
22
- }
23
-
24
- export function validateMAYAName(name: string) {
25
- if (name.length > 30) return false;
26
-
27
- const regex = /^[a-zA-Z0-9+_-]+$/g;
19
+ export function derivationPathToString([network, chainId, account, change, index]:
20
+ | [number, number, number, number, number | undefined]
21
+ | DerivationPathArray) {
22
+ const shortPath = typeof index !== "number";
28
23
 
29
- return !!name.match(regex);
24
+ return `m/${network}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`;
30
25
  }
31
26
 
32
- export function derivationPathToString([network, chainId, account, change, index]: [
33
- number,
34
- number,
35
- number,
36
- number,
37
- number | undefined,
38
- ]) {
39
- const shortPath = typeof index !== "number";
27
+ export function wrapWithThrow<T>(fn: () => T, errorKey?: ErrorKeys) {
28
+ try {
29
+ return fn();
30
+ } catch (error) {
31
+ if (errorKey) {
32
+ throw new SwapKitError(errorKey, error);
33
+ }
40
34
 
41
- return `${network}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`;
35
+ return console.error(error);
36
+ }
42
37
  }