@pioneer-platform/helpers 4.1.1 → 4.3.0

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,58 @@
1
+ import type { CoinGeckoList, MayaList, PancakeswapETHList, PancakeswapList, PangolinList, PioneerList, StargateARBList, SushiswapList, ThorchainList, TraderjoeList, UniswapList, WoofiList } from '@coinmasters/tokens';
2
+ import { Chain } from '@coinmasters/types';
3
+ import type { CommonAssetString } from '../helpers/asset';
4
+ import { getAssetType } from '../helpers/asset';
5
+ import type { NumberPrimitives } from './bigIntArithmetics';
6
+ import { BigIntArithmetics } from './bigIntArithmetics';
7
+ import type { SwapKitValueType } from './swapKitNumber';
8
+ type TokenTax = {
9
+ buy: number;
10
+ sell: number;
11
+ };
12
+ export declare function safeValue(value: NumberPrimitives, decimal: number): bigint;
13
+ type AssetValueParams = {
14
+ decimal: number;
15
+ value: SwapKitValueType;
16
+ tax?: TokenTax;
17
+ } & ({
18
+ chain: Chain;
19
+ symbol: string;
20
+ } | {
21
+ identifier: string;
22
+ });
23
+ type TCTokenNames = (typeof ThorchainList)['tokens'][number]['identifier'];
24
+ type TokenNames = TCTokenNames | (typeof CoinGeckoList)['tokens'][number]['identifier'] | (typeof MayaList)['tokens'][number]['identifier'] | (typeof PancakeswapETHList)['tokens'][number]['identifier'] | (typeof PancakeswapList)['tokens'][number]['identifier'] | (typeof PangolinList)['tokens'][number]['identifier'] | (typeof StargateARBList)['tokens'][number]['identifier'] | (typeof SushiswapList)['tokens'][number]['identifier'] | (typeof TraderjoeList)['tokens'][number]['identifier'] | (typeof WoofiList)['tokens'][number]['identifier'] | (typeof UniswapList)['tokens'][number]['identifier'] | (typeof PioneerList)['tokens'][number]['identifier'];
25
+ export declare class AssetValue extends BigIntArithmetics {
26
+ address?: string;
27
+ caip?: string;
28
+ pubkey?: string;
29
+ identifier?: string;
30
+ chain: Chain;
31
+ isGasAsset: boolean;
32
+ isSynthetic: boolean;
33
+ symbol: string;
34
+ tax?: TokenTax;
35
+ ticker: string;
36
+ type: ReturnType<typeof getAssetType>;
37
+ constructor(params: AssetValueParams);
38
+ toString(short?: boolean): string | undefined;
39
+ toUrl(): string | undefined;
40
+ eq({ chain, symbol }: {
41
+ chain: Chain;
42
+ symbol: string;
43
+ }): boolean | undefined;
44
+ static fromString(assetString: string, value?: NumberPrimitives): Promise<AssetValue | undefined>;
45
+ static fromStringSync(assetString: string, value?: NumberPrimitives): AssetValue | undefined;
46
+ static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: NumberPrimitives): Promise<AssetValue | undefined>;
47
+ static fromIdentifierSync(identifier: TokenNames, value?: NumberPrimitives): AssetValue | undefined;
48
+ static fromChainOrSignature(assetString: CommonAssetString, value?: NumberPrimitives): AssetValue | undefined;
49
+ static loadStaticAssets(): Promise<{
50
+ ok: true;
51
+ } | {
52
+ ok: false;
53
+ message: string;
54
+ error: any;
55
+ } | undefined>;
56
+ }
57
+ export declare const getMinAmountByChain: (chain: Chain) => any;
58
+ export {};
@@ -0,0 +1,355 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __rest = (this && this.__rest) || function (s, e) {
45
+ var t = {};
46
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
47
+ t[p] = s[p];
48
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
49
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
50
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
51
+ t[p[i]] = s[p[i]];
52
+ }
53
+ return t;
54
+ };
55
+ Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.getMinAmountByChain = exports.AssetValue = void 0;
57
+ exports.safeValue = safeValue;
58
+ const types_1 = require("@coinmasters/types");
59
+ const asset_1 = require("../helpers/asset");
60
+ const validators_1 = require("../helpers/validators");
61
+ const bigIntArithmetics_1 = require("./bigIntArithmetics");
62
+ const TAG = " | assetValue | ";
63
+ function safeValue(value, decimal) {
64
+ let tag = TAG + " | safeValue | ";
65
+ try {
66
+ if (typeof value === 'bigint') {
67
+ return value;
68
+ }
69
+ else if (typeof value === 'number') {
70
+ return BigInt(Math.round(value * Math.pow(10, decimal)));
71
+ }
72
+ else if (typeof value === 'string') {
73
+ return BigInt(Math.round(parseFloat(value) * Math.pow(10, decimal)));
74
+ }
75
+ return BigInt(0);
76
+ }
77
+ catch (error) {
78
+ console.error(tag + 'Error in safeValue:', error);
79
+ return BigInt(0);
80
+ }
81
+ }
82
+ let staticTokensMap;
83
+ const getStaticToken = (identifier) => {
84
+ let tag = TAG + " | getStaticToken | ";
85
+ try {
86
+ if (!staticTokensMap) {
87
+ throw new Error('Static assets not loaded, call await AssetValue.loadStaticAssets() first');
88
+ }
89
+ const tokenInfo = staticTokensMap.get(identifier.toUpperCase());
90
+ return tokenInfo || { decimal: types_1.BaseDecimal.THOR, identifier: '' };
91
+ }
92
+ catch (error) {
93
+ console.error(tag + 'Error in getStaticToken:', error);
94
+ }
95
+ };
96
+ const createAssetValue = (assetString_1, ...args_1) => __awaiter(void 0, [assetString_1, ...args_1], void 0, function* (assetString, value = 0) {
97
+ let tag = TAG + " | createAssetValue | ";
98
+ try {
99
+ (0, validators_1.validateIdentifier)(assetString);
100
+ //console.log(tag + 'assetString', assetString);
101
+ //@ts-ignore
102
+ const decimal = yield (0, asset_1.getDecimal)(getAssetInfo(assetString));
103
+ //console.log(tag + 'decimal', decimal);
104
+ const parsedValue = safeValue(value, decimal);
105
+ //console.log(tag + 'parsedValue', parsedValue);
106
+ // @ts-ignore
107
+ return new AssetValue({ decimal, value: parsedValue, identifier: assetString });
108
+ }
109
+ catch (error) {
110
+ console.error(tag + 'Error in createAssetValue:', error);
111
+ }
112
+ });
113
+ class AssetValue extends bigIntArithmetics_1.BigIntArithmetics {
114
+ //@ts-ignore
115
+ constructor(params) {
116
+ let tag = TAG + " | constructor | ";
117
+ try {
118
+ const identifier = 'identifier' in params ? params.identifier : `${params.chain}.${params.symbol}`;
119
+ let value;
120
+ if (params.value instanceof bigIntArithmetics_1.BigIntArithmetics) {
121
+ value = params.value;
122
+ }
123
+ else {
124
+ value = { decimal: params.decimal, value: safeValue(params.value, params.decimal) };
125
+ }
126
+ // @ts-ignore
127
+ super(value);
128
+ this.isGasAsset = false;
129
+ this.isSynthetic = false;
130
+ const assetInfo = getAssetInfo(identifier);
131
+ this.type = (0, asset_1.getAssetType)(assetInfo);
132
+ this.identifier = identifier;
133
+ this.chain = assetInfo.chain;
134
+ this.ticker = assetInfo.ticker;
135
+ this.symbol = assetInfo.symbol;
136
+ this.address = assetInfo.address;
137
+ this.isSynthetic = assetInfo.isSynthetic;
138
+ // @ts-ignore
139
+ this.isGasAsset = assetInfo.isGasAsset;
140
+ this.tax = params.tax;
141
+ }
142
+ catch (error) {
143
+ console.error(tag + 'Error in constructor:', error);
144
+ }
145
+ }
146
+ toString(short = false) {
147
+ let tag = TAG + " | toString | ";
148
+ try {
149
+ const shortFormat = this.isSynthetic ? this.symbol : this.ticker;
150
+ return short
151
+ ? shortFormat
152
+ : `${this.chain}.${this.symbol}`;
153
+ }
154
+ catch (error) {
155
+ console.error(tag + 'Error in toString:', error);
156
+ }
157
+ }
158
+ toUrl() {
159
+ let tag = TAG + " | toUrl | ";
160
+ try {
161
+ return this.isSynthetic ? `${this.chain}.${this.symbol.replace('/', '.')}` : this.toString();
162
+ }
163
+ catch (error) {
164
+ console.error(tag + 'Error in toUrl:', error);
165
+ }
166
+ }
167
+ eq({ chain, symbol }) {
168
+ let tag = TAG + " | eq | ";
169
+ try {
170
+ return this.chain === chain && this.symbol === symbol;
171
+ }
172
+ catch (error) {
173
+ console.error(tag + 'Error in eq:', error);
174
+ }
175
+ }
176
+ static fromString(assetString_1) {
177
+ return __awaiter(this, arguments, void 0, function* (assetString, value = 0) {
178
+ let tag = TAG + " | fromString | ";
179
+ try {
180
+ return createAssetValue(assetString, value);
181
+ }
182
+ catch (error) {
183
+ console.error(tag + 'Error in fromString:', error);
184
+ }
185
+ });
186
+ }
187
+ static fromStringSync(assetString, value = 0) {
188
+ let tag = TAG + " | fromStringSync | ";
189
+ try {
190
+ //@ts-ignore
191
+ const { isSynthetic, symbol, chain, isGasAsset, ticker, address } = getAssetInfo(assetString);
192
+ const { tax, decimal, identifier: tokenIdentifier, } = getStaticToken(assetString);
193
+ const parsedValue = safeValue(value, decimal);
194
+ let asset;
195
+ if (tokenIdentifier) {
196
+ asset = new AssetValue({
197
+ tax,
198
+ decimal,
199
+ identifier: tokenIdentifier,
200
+ // @ts-ignore
201
+ value: parsedValue,
202
+ });
203
+ }
204
+ else if (isSynthetic) {
205
+ asset = new AssetValue({
206
+ tax,
207
+ decimal: 8, // Synthetic assets use a fixed decimal value
208
+ identifier: assetString,
209
+ // @ts-ignore
210
+ value: parsedValue,
211
+ });
212
+ }
213
+ else {
214
+ asset = undefined;
215
+ }
216
+ return asset;
217
+ }
218
+ catch (error) {
219
+ console.error(tag + 'Error in fromStringSync:', error);
220
+ }
221
+ }
222
+ static fromIdentifier(assetString_1) {
223
+ return __awaiter(this, arguments, void 0, function* (assetString, value = 0) {
224
+ let tag = TAG + " | fromIdentifier | ";
225
+ try {
226
+ return createAssetValue(assetString, value);
227
+ }
228
+ catch (error) {
229
+ console.error(tag + 'Error in fromIdentifier:', error);
230
+ }
231
+ });
232
+ }
233
+ static fromIdentifierSync(identifier, value = 0) {
234
+ let tag = TAG + " | fromIdentifierSync | ";
235
+ try {
236
+ //@ts-ignore
237
+ const { decimal, identifier: tokenIdentifier } = getStaticToken(identifier);
238
+ const parsedValue = safeValue(value, decimal);
239
+ // @ts-ignore
240
+ return new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue });
241
+ }
242
+ catch (error) {
243
+ console.error(tag + 'Error in fromIdentifierSync:', error);
244
+ }
245
+ }
246
+ static fromChainOrSignature(assetString, value = 0) {
247
+ let tag = TAG + " | fromChainOrSignature | ";
248
+ try {
249
+ const { decimal, identifier } = (0, asset_1.getCommonAssetInfo)(assetString);
250
+ if (!decimal || !identifier)
251
+ throw Error('unknown coin! ' + assetString);
252
+ const parsedValue = safeValue(value, decimal);
253
+ //console.log(tag + "parsedValue: ", parsedValue);
254
+ //console.log(tag + "decimal: ", decimal);
255
+ //console.log(tag + "identifier: ", identifier);
256
+ // @ts-ignore
257
+ return new AssetValue({ value: parsedValue, decimal, identifier });
258
+ }
259
+ catch (error) {
260
+ console.error(tag + 'Error in fromChainOrSignature:', error);
261
+ }
262
+ }
263
+ static loadStaticAssets() {
264
+ return __awaiter(this, void 0, void 0, function* () {
265
+ let tag = TAG + " | loadStaticAssets | ";
266
+ try {
267
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
268
+ try {
269
+ const _a = yield Promise.resolve().then(() => __importStar(require('@coinmasters/tokens'))), { ThorchainList: _ThorchainList, NativeList } = _a, tokensPackage = __rest(_a, ["ThorchainList", "NativeList"]);
270
+ const tokensMap = [NativeList, ...Object.values(tokensPackage)].reduce((acc, { tokens }) => {
271
+ if (!tokens) {
272
+ console.warn(tag + "No tokens found in the current package, skipping.");
273
+ return acc;
274
+ }
275
+ // @ts-ignore
276
+ tokens.forEach((_a) => {
277
+ var { identifier, chain } = _a, rest = __rest(_a, ["identifier", "chain"]);
278
+ const decimal = 'decimals' in rest ? rest.decimals : types_1.BaseDecimal[chain];
279
+ acc.set(identifier, { identifier, decimal });
280
+ });
281
+ return acc;
282
+ }, new Map());
283
+ staticTokensMap = tokensMap;
284
+ resolve({ ok: true });
285
+ }
286
+ catch (error) {
287
+ console.error(tag + "Error loading static assets:", error);
288
+ reject({
289
+ ok: false,
290
+ error,
291
+ message: "Couldn't load static assets. Ensure you have installed @coinmasters/tokens package",
292
+ });
293
+ }
294
+ }));
295
+ }
296
+ catch (error) {
297
+ console.error(tag + 'Error in loadStaticAssets:', error);
298
+ }
299
+ });
300
+ }
301
+ }
302
+ exports.AssetValue = AssetValue;
303
+ const getMinAmountByChain = (chain) => {
304
+ let tag = TAG + " | getMinAmountByChain | ";
305
+ try {
306
+ const asset = AssetValue.fromChainOrSignature(chain);
307
+ switch (chain) {
308
+ case types_1.Chain.Bitcoin:
309
+ case types_1.Chain.Litecoin:
310
+ case types_1.Chain.Dash:
311
+ case types_1.Chain.Zcash:
312
+ case types_1.Chain.BitcoinCash:
313
+ return asset.set(0.00010001);
314
+ case types_1.Chain.Dogecoin:
315
+ return asset.set(1.00000001);
316
+ case types_1.Chain.Base:
317
+ case types_1.Chain.Arbitrum:
318
+ case types_1.Chain.Avalanche:
319
+ case types_1.Chain.Ethereum:
320
+ return asset.set(0.00000001);
321
+ case types_1.Chain.THORChain:
322
+ case types_1.Chain.Mayachain:
323
+ return asset.set(0.0000000001);
324
+ default:
325
+ return asset.set(0.00000001);
326
+ }
327
+ }
328
+ catch (error) {
329
+ console.error(tag + 'Error in getMinAmountByChain:', error);
330
+ }
331
+ };
332
+ exports.getMinAmountByChain = getMinAmountByChain;
333
+ const getAssetInfo = (identifier) => {
334
+ var _a;
335
+ let tag = TAG + " | getAssetInfo | ";
336
+ try {
337
+ const isSynthetic = identifier.slice(0, 14).includes('/');
338
+ const [synthChain, synthSymbol] = identifier.split('.').pop().split('/');
339
+ const adjustedIdentifier = identifier.includes('.') && !isSynthetic ? identifier : `${types_1.Chain.THORChain}.${synthSymbol}`;
340
+ const [chain, symbol] = adjustedIdentifier.split('.');
341
+ const [ticker, address] = (isSynthetic ? synthSymbol : symbol).split('-');
342
+ return {
343
+ address: address === null || address === void 0 ? void 0 : address.toLowerCase(),
344
+ chain,
345
+ isGasAsset: (0, asset_1.isGasAsset)({ chain, symbol }),
346
+ isSynthetic,
347
+ symbol: (isSynthetic ? `${synthChain}/` : '') +
348
+ (address ? `${ticker}-${(_a = address === null || address === void 0 ? void 0 : address.toLowerCase()) !== null && _a !== void 0 ? _a : ''}` : symbol),
349
+ ticker,
350
+ };
351
+ }
352
+ catch (error) {
353
+ console.error(tag + 'Error in getAssetInfo:', error);
354
+ }
355
+ };
@@ -0,0 +1,54 @@
1
+ import type { SwapKitNumber } from './swapKitNumber';
2
+ type NumberPrimitivesType = {
3
+ bigint: bigint;
4
+ number: number;
5
+ string: string;
6
+ };
7
+ export type NumberPrimitives = bigint | number | string;
8
+ type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber;
9
+ type SKBigIntParams = InitialisationValueType | {
10
+ decimal?: number;
11
+ value: number | string;
12
+ };
13
+ type AllowedNumberTypes = 'bigint' | 'number' | 'string';
14
+ export declare const toMultiplier: (decimal: number) => bigint;
15
+ export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: {
16
+ value: bigint;
17
+ bigIntDecimal?: bigint;
18
+ decimal?: number;
19
+ }): string;
20
+ export declare class BigIntArithmetics {
21
+ private decimalMultiplier;
22
+ private bigIntValue;
23
+ private decimal?;
24
+ static fromBigInt(value: bigint, decimal?: number): BigIntArithmetics;
25
+ constructor(params: SKBigIntParams);
26
+ set(value: SKBigIntParams): this;
27
+ add(...args: InitialisationValueType[]): this;
28
+ sub(...args: InitialisationValueType[]): this;
29
+ mul(...args: InitialisationValueType[]): this;
30
+ div(...args: InitialisationValueType[]): this;
31
+ gt(value: InitialisationValueType): boolean;
32
+ gte(value: InitialisationValueType): boolean;
33
+ lt(value: InitialisationValueType): boolean;
34
+ lte(value: InitialisationValueType): boolean;
35
+ eqValue(value: InitialisationValueType): boolean;
36
+ getValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T];
37
+ getBaseValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T];
38
+ getBigIntValue(value: InitialisationValueType, decimal?: number): bigint;
39
+ toSignificant(significantDigits?: number): string;
40
+ toFixed(fixedDigits?: number): string;
41
+ toAbbreviation(digits?: number): string;
42
+ toCurrency(currency?: string, { currencyPosition, decimal, decimalSeparator, thousandSeparator, }?: {
43
+ currencyPosition?: string | undefined;
44
+ decimal?: number | undefined;
45
+ decimalSeparator?: string | undefined;
46
+ thousandSeparator?: string | undefined;
47
+ }): string;
48
+ private arithmetics;
49
+ private comparison;
50
+ private setValue;
51
+ private retrievePrecisionDecimal;
52
+ private toBigInt;
53
+ }
54
+ export {};