@swapkit/helpers 1.0.0-rc.82 → 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.
package/dist/index.js ADDED
@@ -0,0 +1,956 @@
1
+ var __require = ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/index.ts
10
+ export * from "@swapkit/api";
11
+
12
+ // src/helpers/asset.ts
13
+ import {RequestClient} from "@swapkit/api";
14
+ import {BaseDecimal, Chain, ChainToRPC, EVMChains, FeeOption} from "@swapkit/types";
15
+ async function findAssetBy(params) {
16
+ const tokenPackages = await import("@swapkit/tokens");
17
+ for (const tokenList of Object.values(tokenPackages)) {
18
+ for (const { identifier, chain: tokenChain, ...rest } of tokenList.tokens) {
19
+ if ("identifier" in params && identifier === params.identifier) {
20
+ return identifier;
21
+ }
22
+ if ("address" in rest && "chain" in params && tokenChain === params.chain && rest.address.toLowerCase() === params.contract.toLowerCase())
23
+ return identifier;
24
+ }
25
+ }
26
+ return;
27
+ }
28
+ var getDecimalMethodHex = "0x313ce567";
29
+ var getContractDecimals = async ({ chain, to }) => {
30
+ try {
31
+ const { result } = await RequestClient.post(ChainToRPC[chain], {
32
+ headers: {
33
+ accept: "*/*",
34
+ "content-type": "application/json",
35
+ "cache-control": "no-cache"
36
+ },
37
+ body: JSON.stringify({
38
+ id: 44,
39
+ jsonrpc: "2.0",
40
+ method: "eth_call",
41
+ params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, "latest"]
42
+ })
43
+ });
44
+ return Number.parseInt(BigInt(result || BaseDecimal[chain]).toString());
45
+ } catch (error) {
46
+ console.error(error);
47
+ return BaseDecimal[chain];
48
+ }
49
+ };
50
+ var getETHAssetDecimal = (symbol) => {
51
+ if (symbol === Chain.Ethereum)
52
+ return BaseDecimal.ETH;
53
+ const [, address] = symbol.split("-");
54
+ return address?.startsWith("0x") ? getContractDecimals({ chain: Chain.Ethereum, to: address }) : BaseDecimal.ETH;
55
+ };
56
+ var getAVAXAssetDecimal = (symbol) => {
57
+ const [, address] = symbol.split("-");
58
+ return address?.startsWith("0x") ? getContractDecimals({ chain: Chain.Avalanche, to: address.toLowerCase() }) : BaseDecimal.AVAX;
59
+ };
60
+ var getBSCAssetDecimal = (symbol) => {
61
+ if (symbol === Chain.BinanceSmartChain)
62
+ return BaseDecimal.BSC;
63
+ return BaseDecimal.BSC;
64
+ };
65
+ var getDecimal = ({ chain, symbol }) => {
66
+ switch (chain) {
67
+ case Chain.Ethereum:
68
+ return getETHAssetDecimal(symbol);
69
+ case Chain.Avalanche:
70
+ return getAVAXAssetDecimal(symbol);
71
+ case Chain.BinanceSmartChain:
72
+ return getBSCAssetDecimal(symbol);
73
+ default:
74
+ return BaseDecimal[chain];
75
+ }
76
+ };
77
+ var gasFeeMultiplier = {
78
+ [FeeOption.Average]: 1.2,
79
+ [FeeOption.Fast]: 1.5,
80
+ [FeeOption.Fastest]: 2
81
+ };
82
+ var isGasAsset = ({ chain, symbol }) => {
83
+ switch (chain) {
84
+ case Chain.Arbitrum:
85
+ case Chain.Optimism:
86
+ return symbol === "ETH";
87
+ case Chain.Maya:
88
+ return symbol === "CACAO";
89
+ case Chain.Kujira:
90
+ return symbol === "KUJI";
91
+ case Chain.Cosmos:
92
+ return symbol === "ATOM";
93
+ case Chain.Polygon:
94
+ return symbol === "MATIC";
95
+ case Chain.BinanceSmartChain:
96
+ return symbol === "BNB";
97
+ case Chain.THORChain:
98
+ return symbol === "RUNE";
99
+ default:
100
+ return symbol === chain;
101
+ }
102
+ };
103
+ var getCommonAssetInfo = (assetString) => {
104
+ switch (assetString) {
105
+ case `${Chain.Ethereum}.THOR`:
106
+ return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 };
107
+ case `${Chain.Ethereum}.vTHOR`:
108
+ return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 };
109
+ case Chain.Cosmos:
110
+ return { identifier: "GAIA.ATOM", decimal: BaseDecimal[assetString] };
111
+ case Chain.THORChain:
112
+ return { identifier: "THOR.RUNE", decimal: BaseDecimal[assetString] };
113
+ case Chain.BinanceSmartChain:
114
+ return { identifier: "BSC.BNB", decimal: BaseDecimal[assetString] };
115
+ case Chain.Maya:
116
+ return { identifier: "MAYA.CACAO", decimal: BaseDecimal.MAYA };
117
+ case `${Chain.Maya}.MAYA`:
118
+ return { identifier: "MAYA.MAYA", decimal: 4 };
119
+ case `${Chain.Kujira}.USK`:
120
+ return { identifier: `${Chain.Kujira}.USK`, decimal: 6 };
121
+ default:
122
+ return { identifier: `${assetString}.${assetString}`, decimal: BaseDecimal[assetString] };
123
+ }
124
+ };
125
+ var getAssetType = ({ chain, symbol }) => {
126
+ if (symbol.includes("/"))
127
+ return "Synth";
128
+ switch (chain) {
129
+ case Chain.Cosmos:
130
+ return symbol === "ATOM" ? "Native" : Chain.Cosmos;
131
+ case Chain.Kujira:
132
+ return symbol === Chain.Kujira ? "Native" : Chain.Kujira;
133
+ case Chain.Binance:
134
+ return symbol === Chain.Binance ? "Native" : "BEP2";
135
+ case Chain.BinanceSmartChain:
136
+ return symbol === Chain.Binance ? "Native" : "BEP20";
137
+ case Chain.Ethereum:
138
+ return symbol === Chain.Ethereum ? "Native" : "ERC20";
139
+ case Chain.Avalanche:
140
+ return symbol === Chain.Avalanche ? "Native" : Chain.Avalanche;
141
+ case Chain.Polygon:
142
+ return symbol === Chain.Polygon ? "Native" : "POLYGON";
143
+ case Chain.Arbitrum:
144
+ return [Chain.Ethereum, Chain.Arbitrum].includes(symbol) ? "Native" : "ARBITRUM";
145
+ case Chain.Optimism:
146
+ return [Chain.Ethereum, Chain.Optimism].includes(symbol) ? "Native" : "OPTIMISM";
147
+ default:
148
+ return "Native";
149
+ }
150
+ };
151
+ var assetFromString = (assetString) => {
152
+ const [chain, ...symbolArray] = assetString.split(".");
153
+ const synth = assetString.includes("/");
154
+ const symbol = symbolArray.join(".");
155
+ const ticker = symbol?.split("-")?.[0];
156
+ return { chain, symbol, ticker, synth };
157
+ };
158
+ var potentialScamRegex = new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/, "gmi");
159
+ var evmAssetHasAddress = (assetString) => {
160
+ const [chain, symbol] = assetString.split(".");
161
+ if (!EVMChains.includes(chain))
162
+ return true;
163
+ const [, address] = symbol.split("-");
164
+ return isGasAsset({ chain, symbol }) || !!address;
165
+ };
166
+ var filterAssets = (tokens) => tokens.filter(({ chain, value, symbol }) => {
167
+ const assetString = `${chain}.${symbol}`;
168
+ return !potentialScamRegex.test(assetString) && evmAssetHasAddress(assetString) && value !== "0";
169
+ });
170
+ // src/helpers/liquidity.ts
171
+ import {BaseDecimal as BaseDecimal2} from "@swapkit/types";
172
+ function getAsymmetricRuneShare({
173
+ liquidityUnits,
174
+ poolUnits,
175
+ runeDepth
176
+ }) {
177
+ const s = toTCSwapKitNumber(liquidityUnits);
178
+ const T = toTCSwapKitNumber(poolUnits);
179
+ const A = toTCSwapKitNumber(runeDepth);
180
+ const part1 = s.mul(A);
181
+ const part2 = T.mul(T).mul(2);
182
+ const part3 = T.mul(s).mul(2);
183
+ const part4 = s.mul(s);
184
+ const part5 = T.mul(T).mul(T);
185
+ const numerator = part1.mul(part2.sub(part3).add(part4));
186
+ return numerator.div(part5);
187
+ }
188
+ function getAsymmetricAssetShare({
189
+ liquidityUnits,
190
+ poolUnits,
191
+ assetDepth
192
+ }) {
193
+ const s = toTCSwapKitNumber(liquidityUnits);
194
+ const T = toTCSwapKitNumber(poolUnits);
195
+ const A = toTCSwapKitNumber(assetDepth);
196
+ const part1 = s.mul(A);
197
+ const part2 = T.mul(T).mul(2);
198
+ const part3 = T.mul(s).mul(2);
199
+ const part4 = s.mul(s);
200
+ const numerator = part1.mul(part2.sub(part3).add(part4));
201
+ const part5 = T.mul(T).mul(T);
202
+ return numerator.div(part5);
203
+ }
204
+ function getAsymmetricRuneWithdrawAmount({
205
+ percent,
206
+ runeDepth,
207
+ liquidityUnits,
208
+ poolUnits
209
+ }) {
210
+ return getAsymmetricRuneShare({ runeDepth, liquidityUnits, poolUnits }).mul(percent);
211
+ }
212
+ function getAsymmetricAssetWithdrawAmount({
213
+ percent,
214
+ assetDepth,
215
+ liquidityUnits,
216
+ poolUnits
217
+ }) {
218
+ return getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);
219
+ }
220
+ var toTCSwapKitNumber = function(value) {
221
+ return SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal2.THOR);
222
+ };
223
+ function getSymmetricPoolShare({
224
+ liquidityUnits,
225
+ poolUnits,
226
+ runeDepth,
227
+ assetDepth
228
+ }) {
229
+ return {
230
+ assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),
231
+ runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits)
232
+ };
233
+ }
234
+ function getSymmetricWithdraw({
235
+ liquidityUnits,
236
+ poolUnits,
237
+ runeDepth,
238
+ assetDepth,
239
+ percent
240
+ }) {
241
+ return Object.fromEntries(Object.entries(getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth })).map(([name, value]) => [name, value.mul(percent)]));
242
+ }
243
+ function getEstimatedPoolShare({
244
+ runeDepth,
245
+ poolUnits,
246
+ assetDepth,
247
+ liquidityUnits,
248
+ runeAmount,
249
+ assetAmount
250
+ }) {
251
+ const R = new SwapKitNumber({ value: runeDepth, decimal: 8 });
252
+ const A = new SwapKitNumber({ value: assetDepth, decimal: 8 });
253
+ const P = new SwapKitNumber({ value: poolUnits, decimal: 8 });
254
+ const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 });
255
+ const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 });
256
+ const rA = runeAddAmount.mul(A);
257
+ const aR = assetAddAmount.mul(R);
258
+ const ra = runeAddAmount.mul(assetAddAmount);
259
+ const RA = R.mul(A);
260
+ const numerator = P.mul(rA.add(aR.add(ra.mul(2))));
261
+ const denominator = rA.add(aR.add(RA.mul(2)));
262
+ const liquidityUnitsAfterAdd = numerator.div(denominator);
263
+ const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);
264
+ if (liquidityUnitsAfterAdd.getBaseValue("number") === 0) {
265
+ return estimatedLiquidityUnits.div(P).getBaseValue("number");
266
+ }
267
+ const newPoolUnits = P.add(estimatedLiquidityUnits);
268
+ return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue("number");
269
+ }
270
+ function getLiquiditySlippage({
271
+ runeAmount,
272
+ assetAmount,
273
+ runeDepth,
274
+ assetDepth
275
+ }) {
276
+ if (runeAmount === "0" || assetAmount === "0" || runeDepth === "0" || assetDepth === "0")
277
+ return 0;
278
+ const R = toTCSwapKitNumber(runeDepth);
279
+ const T = toTCSwapKitNumber(assetDepth);
280
+ const assetAddAmount = toTCSwapKitNumber(assetAmount);
281
+ const runeAddAmount = toTCSwapKitNumber(runeAmount);
282
+ const numerator = assetAddAmount.mul(R).sub(T.mul(runeAddAmount));
283
+ const denominator = T.mul(runeAddAmount).add(R.mul(T));
284
+ return Math.abs(numerator.div(denominator).getBaseValue("number"));
285
+ }
286
+ // src/helpers/memo.ts
287
+ import {Chain as Chain2, MemoType} from "@swapkit/types";
288
+ var getMemoFor = (memoType, options) => {
289
+ switch (memoType) {
290
+ case MemoType.LEAVE:
291
+ case MemoType.BOND: {
292
+ const { address } = options;
293
+ return `${memoType}:${address}`;
294
+ }
295
+ case MemoType.UNBOND: {
296
+ const { address, unbondAmount } = options;
297
+ return `${memoType}:${address}:${unbondAmount}`;
298
+ }
299
+ case MemoType.THORNAME_REGISTER: {
300
+ const { name, chain, address, owner } = options;
301
+ return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : ""}`;
302
+ }
303
+ case MemoType.DEPOSIT: {
304
+ const { chain, symbol, address, singleSide } = options;
305
+ const getPoolIdentifier = (chain2, symbol2) => {
306
+ switch (chain2) {
307
+ case Chain2.Litecoin:
308
+ return "l";
309
+ case Chain2.Dogecoin:
310
+ return "d";
311
+ case Chain2.BitcoinCash:
312
+ return "c";
313
+ default:
314
+ return `${chain2}.${symbol2}`;
315
+ }
316
+ };
317
+ return singleSide ? `${memoType}:${chain}/${symbol}` : `${memoType}:${getPoolIdentifier(chain, symbol)}:${address || ""}`;
318
+ }
319
+ case MemoType.WITHDRAW: {
320
+ const { chain, ticker, symbol, basisPoints, targetAssetString, singleSide } = options;
321
+ const shortenedSymbol = chain === "ETH" && ticker !== "ETH" ? `${ticker}-${symbol.slice(-3)}` : symbol;
322
+ const target = !singleSide && targetAssetString ? `:${targetAssetString}` : "";
323
+ const assetDivider = singleSide ? "/" : ".";
324
+ return `${memoType}:${chain}${assetDivider}${shortenedSymbol}:${basisPoints}${target}`;
325
+ }
326
+ case MemoType.OPEN_LOAN:
327
+ case MemoType.CLOSE_LOAN: {
328
+ const { asset, address } = options;
329
+ return `${memoType}:${asset}:${address}`;
330
+ }
331
+ default:
332
+ return "";
333
+ }
334
+ };
335
+ // src/modules/swapKitError.ts
336
+ var errorMessages = {
337
+ core_wallet_connection_not_found: 10001,
338
+ core_estimated_max_spendable_chain_not_supported: 10002,
339
+ core_extend_error: 10003,
340
+ core_inbound_data_not_found: 10004,
341
+ core_approve_asset_address_or_from_not_found: 10005,
342
+ core_plugin_not_found: 10006,
343
+ core_chain_halted: 10099,
344
+ core_wallet_xdefi_not_installed: 10101,
345
+ core_wallet_evmwallet_not_installed: 10102,
346
+ core_wallet_walletconnect_not_installed: 10103,
347
+ core_wallet_keystore_not_installed: 10104,
348
+ core_wallet_ledger_not_installed: 10105,
349
+ core_wallet_trezor_not_installed: 10106,
350
+ core_wallet_keplr_not_installed: 10107,
351
+ core_wallet_okx_not_installed: 10108,
352
+ core_wallet_keepkey_not_installed: 10109,
353
+ core_swap_invalid_params: 10200,
354
+ core_swap_route_not_complete: 10201,
355
+ core_swap_asset_not_recognized: 10202,
356
+ core_swap_contract_not_found: 10203,
357
+ core_swap_route_transaction_not_found: 10204,
358
+ core_swap_contract_not_supported: 10205,
359
+ core_swap_transaction_error: 10206,
360
+ core_swap_quote_mode_not_supported: 10207,
361
+ core_transaction_deposit_error: 10301,
362
+ core_transaction_create_liquidity_rune_error: 10302,
363
+ core_transaction_create_liquidity_asset_error: 10303,
364
+ core_transaction_create_liquidity_invalid_params: 10304,
365
+ core_transaction_add_liquidity_invalid_params: 10305,
366
+ core_transaction_add_liquidity_no_rune_address: 10306,
367
+ core_transaction_add_liquidity_rune_error: 10307,
368
+ core_transaction_add_liquidity_asset_error: 10308,
369
+ core_transaction_withdraw_error: 10309,
370
+ core_transaction_deposit_to_pool_error: 10310,
371
+ core_transaction_deposit_insufficient_funds_error: 10311,
372
+ core_transaction_deposit_gas_error: 10312,
373
+ core_transaction_invalid_sender_address: 10313,
374
+ core_transaction_deposit_server_error: 10314,
375
+ core_transaction_user_rejected: 10315,
376
+ wallet_ledger_connection_error: 20001,
377
+ wallet_ledger_connection_claimed: 20002,
378
+ wallet_ledger_get_address_error: 20003,
379
+ wallet_ledger_device_not_found: 20004,
380
+ wallet_ledger_device_locked: 20005,
381
+ chainflip_channel_error: 30001,
382
+ chainflip_broker_recipient_error: 30002,
383
+ helpers_number_different_decimals: 99101
384
+ };
385
+
386
+ class SwapKitError extends Error {
387
+ constructor(errorKey, sourceError) {
388
+ if (sourceError) {
389
+ console.error(sourceError, {
390
+ stack: sourceError?.stack,
391
+ message: sourceError?.message
392
+ });
393
+ }
394
+ super(errorKey, {
395
+ cause: { code: errorMessages[errorKey], message: errorKey }
396
+ });
397
+ Object.setPrototypeOf(this, SwapKitError.prototype);
398
+ }
399
+ }
400
+
401
+ // src/helpers/others.ts
402
+ function getTHORNameCost(year) {
403
+ if (year < 0)
404
+ throw new Error("Invalid number of year");
405
+ return 10 + year;
406
+ }
407
+ function getMAYANameCost(year) {
408
+ if (year < 0)
409
+ throw new Error("Invalid number of year");
410
+ return Math.round((10 + year * 1.0512) * 10000000000) / 10000000000;
411
+ }
412
+ function derivationPathToString([network, chainId, account, change, index]) {
413
+ const shortPath = typeof index !== "number";
414
+ return `m/${network}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`;
415
+ }
416
+ function wrapWithThrow(fn, errorKey) {
417
+ try {
418
+ return fn();
419
+ } catch (error) {
420
+ if (errorKey) {
421
+ throw new SwapKitError(errorKey, error);
422
+ }
423
+ return console.error(error);
424
+ }
425
+ }
426
+ // src/modules/assetValue.ts
427
+ import {BaseDecimal as BaseDecimal4, Chain as Chain4, ChainToChainId} from "@swapkit/types";
428
+
429
+ // src/helpers/validators.ts
430
+ import {Chain as Chain3} from "@swapkit/types";
431
+ function validateIdentifier(identifier = "") {
432
+ const uppercasedIdentifier = identifier.toUpperCase();
433
+ const [chain] = uppercasedIdentifier.split(".");
434
+ if (supportedChains.includes(chain))
435
+ return true;
436
+ const [synthChain] = uppercasedIdentifier.split("/");
437
+ if (supportedChains.includes(synthChain))
438
+ return true;
439
+ throw new Error(`Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`);
440
+ }
441
+ var supportedChains = [...Object.values(Chain3), "TERRA"];
442
+
443
+ // src/modules/bigIntArithmetics.ts
444
+ import {BaseDecimal as BaseDecimal3} from "@swapkit/types";
445
+ function formatBigIntToSafeValue({
446
+ value,
447
+ bigIntDecimal = DEFAULT_DECIMAL,
448
+ decimal = DEFAULT_DECIMAL
449
+ }) {
450
+ if (decimal === 0)
451
+ return value.toString();
452
+ const isNegative = value < 0n;
453
+ let valueString = value.toString().substring(isNegative ? 1 : 0);
454
+ const padLength = decimal - (valueString.length - 1);
455
+ if (padLength > 0) {
456
+ valueString = "0".repeat(padLength) + valueString;
457
+ }
458
+ const decimalIndex = valueString.length - decimal;
459
+ let decimalString = valueString.slice(-decimal);
460
+ if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
461
+ decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`;
462
+ } else {
463
+ decimalString = decimalString.substring(0, bigIntDecimal);
464
+ }
465
+ return `${isNegative ? "-" : ""}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, "");
466
+ }
467
+ var toSafeValue = function(value) {
468
+ const parsedValue = typeof value === "number" ? numberFormatter.format(value) : getStringValue(value);
469
+ const splitValue = `${parsedValue}`.replaceAll(",", ".").split(".");
470
+ return splitValue.length > 1 ? `${splitValue.slice(0, -1).join("")}.${splitValue.at(-1)}` : splitValue[0] || "0";
471
+ };
472
+ var getFloatDecimals = function(value) {
473
+ const decimals = value.split(".")[1]?.length || 0;
474
+ return Math.max(decimals, DEFAULT_DECIMAL);
475
+ };
476
+ var getStringValue = function(param) {
477
+ return typeof param === "object" ? "getValue" in param ? param.getValue("string") : param.value : param;
478
+ };
479
+ var DEFAULT_DECIMAL = 8;
480
+ var toMultiplier = (decimal) => 10n ** BigInt(decimal);
481
+ var decimalFromMultiplier = (multiplier) => Math.log10(Number.parseFloat(multiplier.toString()));
482
+
483
+ class BigIntArithmetics {
484
+ decimalMultiplier = 10n ** 8n;
485
+ bigIntValue = 0n;
486
+ decimal;
487
+ static fromBigInt(value, decimal) {
488
+ return new BigIntArithmetics({
489
+ decimal,
490
+ value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
491
+ });
492
+ }
493
+ static shiftDecimals({
494
+ value,
495
+ from,
496
+ to
497
+ }) {
498
+ return BigIntArithmetics.fromBigInt(value.getBaseValue("bigint") * toMultiplier(to) / toMultiplier(from), to);
499
+ }
500
+ constructor(params) {
501
+ const value = getStringValue(params);
502
+ const isComplex = typeof params === "object";
503
+ this.decimal = isComplex ? params.decimal : undefined;
504
+ this.decimalMultiplier = isComplex && "decimalMultiplier" in params ? params.decimalMultiplier : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0));
505
+ this.#setValue(value);
506
+ }
507
+ set(value) {
508
+ return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
509
+ }
510
+ add(...args) {
511
+ return this.#arithmetics("add", ...args);
512
+ }
513
+ sub(...args) {
514
+ return this.#arithmetics("sub", ...args);
515
+ }
516
+ mul(...args) {
517
+ return this.#arithmetics("mul", ...args);
518
+ }
519
+ div(...args) {
520
+ return this.#arithmetics("div", ...args);
521
+ }
522
+ gt(value) {
523
+ return this.#comparison("gt", value);
524
+ }
525
+ gte(value) {
526
+ return this.#comparison("gte", value);
527
+ }
528
+ lt(value) {
529
+ return this.#comparison("lt", value);
530
+ }
531
+ lte(value) {
532
+ return this.#comparison("lte", value);
533
+ }
534
+ eqValue(value) {
535
+ return this.#comparison("eqValue", value);
536
+ }
537
+ getValue(type) {
538
+ const value = this.formatBigIntToSafeValue(this.bigIntValue, this.decimal || decimalFromMultiplier(this.decimalMultiplier));
539
+ switch (type) {
540
+ case "number":
541
+ return Number(value);
542
+ case "string":
543
+ return value;
544
+ case "bigint":
545
+ return this.bigIntValue * 10n ** BigInt(this.decimal || 8n) / this.decimalMultiplier;
546
+ }
547
+ }
548
+ getBaseValue(type) {
549
+ const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal3.THOR);
550
+ const baseValue = this.bigIntValue / divisor;
551
+ switch (type) {
552
+ case "number":
553
+ return Number(baseValue);
554
+ case "string":
555
+ return baseValue.toString();
556
+ case "bigint":
557
+ return baseValue;
558
+ }
559
+ }
560
+ getBigIntValue(value, decimal) {
561
+ if (!decimal && typeof value === "object")
562
+ return value.bigIntValue;
563
+ const stringValue = getStringValue(value);
564
+ const safeValue = toSafeValue(stringValue);
565
+ if (safeValue === "0" || safeValue === "undefined")
566
+ return 0n;
567
+ return this.#toBigInt(safeValue, decimal);
568
+ }
569
+ toSignificant(significantDigits = 6) {
570
+ const [int, dec] = this.getValue("string").split(".");
571
+ const integer = int || "";
572
+ const decimal = dec || "";
573
+ const valueLength = Number.parseInt(integer) ? integer.length + decimal.length : decimal.length;
574
+ if (valueLength <= significantDigits) {
575
+ return this.getValue("string");
576
+ }
577
+ if (integer.length >= significantDigits) {
578
+ return integer.slice(0, significantDigits).padEnd(integer.length, "0");
579
+ }
580
+ if (Number.parseInt(integer)) {
581
+ return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(significantDigits - integer.length, "0");
582
+ }
583
+ const trimmedDecimal = Number.parseInt(decimal);
584
+ const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits);
585
+ return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`;
586
+ }
587
+ toFixed(fixedDigits = 6) {
588
+ const [int, dec] = this.getValue("string").split(".");
589
+ const integer = int || "";
590
+ const decimal = dec || "";
591
+ if (Number.parseInt(integer)) {
592
+ return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, "0");
593
+ }
594
+ const trimmedDecimal = Number.parseInt(decimal);
595
+ const slicedDecimal = `${trimmedDecimal}`.slice(0, fixedDigits);
596
+ return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`;
597
+ }
598
+ toAbbreviation(digits = 2) {
599
+ const value = this.getValue("number");
600
+ const abbreviations = ["", "K", "M", "B", "T", "Q", "Qi", "S"];
601
+ const tier = Math.floor(Math.log10(Math.abs(value)) / 3);
602
+ const suffix = abbreviations[tier];
603
+ if (!suffix)
604
+ return this.getValue("string");
605
+ const scale = 10 ** (tier * 3);
606
+ const scaled = value / scale;
607
+ return `${scaled.toFixed(digits)}${suffix}`;
608
+ }
609
+ toCurrency(currency = "$", {
610
+ currencyPosition = "start",
611
+ decimal = 2,
612
+ decimalSeparator = ".",
613
+ thousandSeparator = ","
614
+ } = {}) {
615
+ const value = this.getValue("number");
616
+ const [int = "", dec = ""] = value.toFixed(6).split(".");
617
+ const integer = int.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
618
+ const parsedValue = int || dec ? int === "0" ? `${Number.parseFloat(`0.${dec}`)}`.replace(".", decimalSeparator) : `${integer}${Number.parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ""}` : "0.00";
619
+ return `${currencyPosition === "start" ? currency : ""}${parsedValue}${currencyPosition === "end" ? currency : ""}`;
620
+ }
621
+ formatBigIntToSafeValue(value, decimal) {
622
+ const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;
623
+ const decimalToUseForConversion = Math.max(bigIntDecimal, decimalFromMultiplier(this.decimalMultiplier));
624
+ const isNegative = value < 0n;
625
+ const valueString = value.toString().substring(isNegative ? 1 : 0);
626
+ const padLength = decimalToUseForConversion - (valueString.length - 1);
627
+ const parsedValueString = padLength > 0 ? "0".repeat(padLength) + valueString : valueString;
628
+ const decimalIndex = parsedValueString.length - decimalToUseForConversion;
629
+ let decimalString = parsedValueString.slice(-decimalToUseForConversion);
630
+ if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
631
+ decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`;
632
+ } else {
633
+ decimalString = decimalString.substring(0, bigIntDecimal);
634
+ }
635
+ return `${isNegative ? "-" : ""}${parsedValueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, "");
636
+ }
637
+ #arithmetics(method, ...args) {
638
+ const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
639
+ const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier));
640
+ const precisionDecimalMultiplier = toMultiplier(decimal);
641
+ const result = args.reduce((acc, arg) => {
642
+ const value2 = this.getBigIntValue(arg, decimal);
643
+ switch (method) {
644
+ case "add":
645
+ return acc + value2;
646
+ case "sub":
647
+ return acc - value2;
648
+ case "mul":
649
+ return acc * value2 / precisionDecimalMultiplier;
650
+ case "div": {
651
+ if (value2 === 0n)
652
+ throw new RangeError("Division by zero");
653
+ return acc * precisionDecimalMultiplier / value2;
654
+ }
655
+ default:
656
+ return acc;
657
+ }
658
+ }, this.bigIntValue * precisionDecimalMultiplier / this.decimalMultiplier);
659
+ const value = formatBigIntToSafeValue({
660
+ bigIntDecimal: decimal,
661
+ decimal,
662
+ value: result
663
+ });
664
+ return new this.constructor({
665
+ decimalMultiplier: toMultiplier(decimal),
666
+ decimal: this.decimal,
667
+ value,
668
+ identifier: this.toString()
669
+ });
670
+ }
671
+ #comparison(method, ...args) {
672
+ const decimal = this.#retrievePrecisionDecimal(this, ...args);
673
+ const value = this.getBigIntValue(args[0] || "0", decimal);
674
+ const compareToValue = this.getBigIntValue(this, decimal);
675
+ switch (method) {
676
+ case "gt":
677
+ return compareToValue > value;
678
+ case "gte":
679
+ return compareToValue >= value;
680
+ case "lt":
681
+ return compareToValue < value;
682
+ case "lte":
683
+ return compareToValue <= value;
684
+ case "eqValue":
685
+ return compareToValue === value;
686
+ }
687
+ }
688
+ #setValue(value) {
689
+ const safeValue = toSafeValue(value) || "0";
690
+ this.bigIntValue = this.#toBigInt(safeValue);
691
+ }
692
+ #retrievePrecisionDecimal(...args) {
693
+ const decimals = args.map((arg) => {
694
+ const isObject = typeof arg === "object";
695
+ const value = isObject ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier) : getFloatDecimals(toSafeValue(arg));
696
+ return value;
697
+ }).filter(Boolean);
698
+ return Math.max(...decimals, DEFAULT_DECIMAL);
699
+ }
700
+ #toBigInt(value, decimal) {
701
+ const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
702
+ const padDecimal = decimalFromMultiplier(multiplier);
703
+ const [integerPart = "", decimalPart = ""] = value.split(".");
704
+ return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, "0")}`);
705
+ }
706
+ }
707
+ var numberFormatter = Intl.NumberFormat("fullwide", {
708
+ useGrouping: false,
709
+ maximumFractionDigits: 20
710
+ });
711
+
712
+ // src/modules/swapKitNumber.ts
713
+ class SwapKitNumber extends BigIntArithmetics {
714
+ constructor() {
715
+ super(...arguments);
716
+ }
717
+ eq(value) {
718
+ return this.eqValue(value);
719
+ }
720
+ static fromBigInt(value, decimal) {
721
+ return new SwapKitNumber({
722
+ decimal,
723
+ value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
724
+ });
725
+ }
726
+ }
727
+
728
+ // src/modules/assetValue.ts
729
+ function getMinAmountByChain(chain) {
730
+ const asset2 = AssetValue.fromChainOrSignature(chain);
731
+ switch (chain) {
732
+ case Chain4.Bitcoin:
733
+ case Chain4.Litecoin:
734
+ case Chain4.BitcoinCash:
735
+ return asset2.set(0.00010001);
736
+ case Chain4.Dogecoin:
737
+ return asset2.set(1.00000001);
738
+ case Chain4.Avalanche:
739
+ case Chain4.Ethereum:
740
+ return asset2.set(0.00000001);
741
+ case Chain4.THORChain:
742
+ case Chain4.Maya:
743
+ return asset2.set(0);
744
+ case Chain4.Cosmos:
745
+ return asset2.set(0.000001);
746
+ default:
747
+ return asset2.set(0.00000001);
748
+ }
749
+ }
750
+ async function createAssetValue(identifier, value = 0) {
751
+ validateIdentifier(identifier);
752
+ const staticToken = staticTokensMap.get(identifier.toUpperCase());
753
+ const decimal = staticToken?.decimal || await getDecimal(getAssetInfo(identifier));
754
+ if (!staticToken) {
755
+ staticTokensMap.set(identifier.toUpperCase(), { identifier, decimal });
756
+ }
757
+ return new AssetValue({ decimal, value: safeValue(value, decimal), identifier });
758
+ }
759
+ var createSyntheticAssetValue = function(identifier, value = 0) {
760
+ const [synthChain, symbol] = identifier.split(".")?.[0]?.toUpperCase() === Chain4.THORChain ? identifier.split(".").slice(1).join().split("/") : identifier.split("/");
761
+ if (!(synthChain && symbol))
762
+ throw new Error("Invalid asset identifier");
763
+ return new AssetValue({
764
+ decimal: 8,
765
+ value: safeValue(value, 8),
766
+ identifier: `${Chain4.THORChain}.${synthChain}/${symbol}`
767
+ });
768
+ };
769
+ var safeValue = function(value, decimal) {
770
+ return typeof value === "bigint" ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) : value;
771
+ };
772
+ var getAssetInfo = function(identifier) {
773
+ const isSynthetic = identifier.slice(0, 14).includes("/");
774
+ const [synthChain, synthSymbol = ""] = identifier.split(".")?.[0]?.toUpperCase() === Chain4.THORChain ? identifier.split(".").slice(1).join().split("/") : identifier.split("/");
775
+ if (isSynthetic && !(synthChain && synthSymbol))
776
+ throw new Error("Invalid asset identifier");
777
+ const adjustedIdentifier = identifier.includes(".") && !isSynthetic ? identifier : `${Chain4.THORChain}.${synthSymbol}`;
778
+ const [chain, ...rest] = adjustedIdentifier.split(".");
779
+ const [ticker, address] = (isSynthetic ? synthSymbol : rest.join(".")).split("-");
780
+ const symbol = isSynthetic ? synthSymbol : rest.join(".");
781
+ return {
782
+ address: address?.toLowerCase(),
783
+ chain,
784
+ isGasAsset: isGasAsset({ chain, symbol }),
785
+ isSynthetic,
786
+ symbol: (isSynthetic ? `${synthChain}/` : "") + (address ? `${ticker}-${address?.toLowerCase() ?? ""}` : symbol),
787
+ ticker
788
+ };
789
+ };
790
+ var staticTokensMap = new Map;
791
+
792
+ class AssetValue extends BigIntArithmetics {
793
+ address;
794
+ chain;
795
+ isGasAsset = false;
796
+ isSynthetic = false;
797
+ symbol;
798
+ tax;
799
+ ticker;
800
+ type;
801
+ constructor({
802
+ value,
803
+ decimal,
804
+ tax,
805
+ chain,
806
+ symbol,
807
+ identifier
808
+ }) {
809
+ super(typeof value === "object" ? value : { decimal, value });
810
+ const assetInfo = getAssetInfo(identifier || `${chain}.${symbol}`);
811
+ this.type = getAssetType(assetInfo);
812
+ this.tax = tax;
813
+ this.chain = assetInfo.chain;
814
+ this.ticker = assetInfo.ticker;
815
+ this.symbol = assetInfo.symbol;
816
+ this.address = assetInfo.address;
817
+ this.isSynthetic = assetInfo.isSynthetic;
818
+ this.isGasAsset = assetInfo.isGasAsset;
819
+ }
820
+ toString() {
821
+ return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;
822
+ }
823
+ toUrl() {
824
+ return this.isSynthetic ? `${this.chain}.${this.symbol.replace("/", ".")}` : this.toString();
825
+ }
826
+ eq({ chain, symbol }) {
827
+ return this.chain === chain && this.symbol === symbol;
828
+ }
829
+ chainId() {
830
+ return ChainToChainId[this.chain];
831
+ }
832
+ static fromUrl(urlAsset, value = 0) {
833
+ const [chain, ticker, symbol] = urlAsset.split(".");
834
+ if (!(chain && ticker))
835
+ throw new Error("Invalid asset url");
836
+ const assetString = chain === Chain4.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset;
837
+ return createAssetValue(assetString, value);
838
+ }
839
+ static fromString(assetString, value = 0) {
840
+ return createAssetValue(assetString, value);
841
+ }
842
+ static fromIdentifier(assetString, value = 0) {
843
+ return createAssetValue(assetString, value);
844
+ }
845
+ static fromStringSync(assetString, value = 0) {
846
+ const { chain, isSynthetic } = getAssetInfo(assetString);
847
+ const tokenInfo = staticTokensMap.get(assetString.toUpperCase());
848
+ if (isSynthetic)
849
+ return createSyntheticAssetValue(assetString, value);
850
+ const { tax, decimal, identifier } = tokenInfo || {
851
+ decimal: BaseDecimal4[chain],
852
+ identifier: assetString
853
+ };
854
+ return new AssetValue({
855
+ tax,
856
+ value: safeValue(value, decimal),
857
+ identifier: isSynthetic ? assetString : identifier,
858
+ decimal: isSynthetic ? 8 : decimal
859
+ });
860
+ }
861
+ static async fromStringWithBase(assetString, value = 0, baseDecimal = BaseDecimal4.THOR) {
862
+ const shiftedAmount = BigIntArithmetics.shiftDecimals({
863
+ value: SwapKitNumber.fromBigInt(BigInt(value)),
864
+ from: 0,
865
+ to: baseDecimal
866
+ }).getBaseValue("string");
867
+ const assetValue = await AssetValue.fromString(assetString, value);
868
+ return assetValue.set(shiftedAmount);
869
+ }
870
+ static fromStringWithBaseSync(assetString, value = 0, baseDecimal = BaseDecimal4.THOR) {
871
+ const { chain, isSynthetic } = getAssetInfo(assetString);
872
+ const tokenInfo = staticTokensMap.get(assetString.toUpperCase());
873
+ if (isSynthetic)
874
+ return createSyntheticAssetValue(assetString, value);
875
+ const { tax, decimal, identifier } = tokenInfo || {
876
+ decimal: BaseDecimal4[chain],
877
+ identifier: assetString
878
+ };
879
+ return new AssetValue({
880
+ tax,
881
+ value: safeValue(BigInt(value), baseDecimal),
882
+ identifier,
883
+ decimal
884
+ });
885
+ }
886
+ static fromIdentifierSync(assetString, value = 0) {
887
+ const { chain, isSynthetic } = getAssetInfo(assetString);
888
+ const tokenInfo = staticTokensMap.get(assetString);
889
+ if (isSynthetic)
890
+ return createSyntheticAssetValue(assetString, value);
891
+ const { tax, decimal, identifier } = tokenInfo || {
892
+ decimal: BaseDecimal4[chain],
893
+ identifier: assetString
894
+ };
895
+ return new AssetValue({ tax, decimal, identifier, value: safeValue(value, decimal) });
896
+ }
897
+ static fromChainOrSignature(assetString, value = 0) {
898
+ const { decimal, identifier } = getCommonAssetInfo(assetString);
899
+ return new AssetValue({ value: safeValue(value, decimal), decimal, identifier });
900
+ }
901
+ static loadStaticAssets() {
902
+ return new Promise((resolve, reject) => {
903
+ try {
904
+ import("@swapkit/tokens").then((tokenPackages) => {
905
+ for (const tokenList of Object.values(tokenPackages)) {
906
+ for (const { identifier, chain, ...rest } of tokenList.tokens) {
907
+ staticTokensMap.set(identifier.toUpperCase(), {
908
+ identifier,
909
+ decimal: "decimals" in rest ? rest.decimals : BaseDecimal4[chain]
910
+ });
911
+ }
912
+ }
913
+ resolve({ ok: true });
914
+ });
915
+ } catch (error) {
916
+ console.error(error);
917
+ reject({
918
+ ok: false,
919
+ error,
920
+ message: "Couldn't load static assets. Ensure you have installed @swapkit/tokens package"
921
+ });
922
+ }
923
+ });
924
+ }
925
+ }
926
+ export {
927
+ wrapWithThrow,
928
+ isGasAsset,
929
+ getTHORNameCost,
930
+ getSymmetricWithdraw,
931
+ getSymmetricPoolShare,
932
+ getMinAmountByChain,
933
+ getMemoFor,
934
+ getMAYANameCost,
935
+ getLiquiditySlippage,
936
+ getEstimatedPoolShare,
937
+ getDecimal,
938
+ getCommonAssetInfo,
939
+ getAsymmetricRuneWithdrawAmount,
940
+ getAsymmetricRuneShare,
941
+ getAsymmetricAssetWithdrawAmount,
942
+ getAsymmetricAssetShare,
943
+ getAssetType,
944
+ gasFeeMultiplier,
945
+ formatBigIntToSafeValue,
946
+ findAssetBy,
947
+ filterAssets,
948
+ derivationPathToString,
949
+ assetFromString,
950
+ SwapKitNumber,
951
+ SwapKitError,
952
+ BigIntArithmetics,
953
+ AssetValue
954
+ };
955
+
956
+ //# debugId=73252CC82EFDBB7564756e2164756e21