@pioneer-platform/helpers 0.0.0 → 0.0.2

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.
Files changed (48) hide show
  1. package/lib/helpers/asset.d.ts +36 -0
  2. package/lib/helpers/asset.js +270 -0
  3. package/lib/helpers/liquidity.d.ts +58 -0
  4. package/lib/helpers/liquidity.js +112 -0
  5. package/lib/helpers/memo.d.ts +46 -0
  6. package/lib/helpers/memo.js +46 -0
  7. package/lib/helpers/others.d.ts +3 -0
  8. package/lib/helpers/others.js +24 -0
  9. package/lib/helpers/request.d.ts +5 -0
  10. package/lib/helpers/request.js +74 -0
  11. package/lib/helpers/validators.d.ts +1 -0
  12. package/lib/helpers/validators.js +17 -0
  13. package/lib/index.d.ts +15 -0
  14. package/lib/index.js +31 -0
  15. package/lib/modules/__tests__/assetValue.test.d.ts +1 -0
  16. package/lib/modules/__tests__/assetValue.test.js +399 -0
  17. package/lib/modules/__tests__/swapKitNumber.test.d.ts +1 -0
  18. package/lib/modules/__tests__/swapKitNumber.test.js +425 -0
  19. package/lib/modules/assetValue.d.ts +55 -0
  20. package/lib/modules/assetValue.js +389 -0
  21. package/lib/modules/bigIntArithmetics.d.ts +58 -0
  22. package/lib/modules/bigIntArithmetics.js +344 -0
  23. package/lib/modules/swapKitError.d.ts +64 -0
  24. package/lib/modules/swapKitError.js +90 -0
  25. package/lib/modules/swapKitNumber.d.ts +6 -0
  26. package/lib/modules/swapKitNumber.js +36 -0
  27. package/package.json +22 -35
  28. package/src/helpers/asset.ts +232 -0
  29. package/src/helpers/liquidity.ts +174 -0
  30. package/src/helpers/memo.ts +90 -0
  31. package/src/helpers/others.ts +20 -0
  32. package/src/helpers/request.ts +33 -0
  33. package/src/helpers/validators.ts +17 -0
  34. package/src/index.ts +16 -6
  35. package/src/modules/assetValue.ts +358 -0
  36. package/src/modules/bigIntArithmetics.ts +416 -0
  37. package/src/{exceptions/SwapKitError.ts → modules/swapKitError.ts} +15 -4
  38. package/src/modules/swapKitNumber.ts +16 -0
  39. package/tsconfig.json +13 -0
  40. package/LICENSE +0 -21
  41. package/src/__tests__/asset.test.ts +0 -33
  42. package/src/__tests__/derivationPath.test.ts +0 -16
  43. package/src/amount.ts +0 -29
  44. package/src/asset.ts +0 -13
  45. package/src/derivationPath.ts +0 -5
  46. package/src/exceptions/index.ts +0 -1
  47. package/src/fees.ts +0 -13
  48. package/src/request.ts +0 -34
@@ -0,0 +1,358 @@
1
+ import type {
2
+ CoinGeckoList,
3
+ MayaList,
4
+ PancakeswapETHList,
5
+ PancakeswapList,
6
+ PangolinList,
7
+ PioneerList,
8
+ StargateARBList,
9
+ SushiswapList,
10
+ ThorchainList,
11
+ TraderjoeList,
12
+ UniswapList,
13
+ WoofiList,
14
+ //@ts-ignore
15
+ } from '@coinmasters/tokens';
16
+ import { BaseDecimal, Chain } from '@coinmasters/types';
17
+
18
+ import type { CommonAssetString } from '../helpers/asset';
19
+ import { getAssetType, getCommonAssetInfo, getDecimal, isGasAsset } from '../helpers/asset';
20
+ import { validateIdentifier } from '../helpers/validators';
21
+
22
+ import type { NumberPrimitives } from './bigIntArithmetics';
23
+ import { BigIntArithmetics, formatBigIntToSafeValue } from './bigIntArithmetics';
24
+ import type { SwapKitValueType } from './swapKitNumber';
25
+
26
+ type TokenTax = { buy: number; sell: number };
27
+
28
+ function safeValue(value: NumberPrimitives, decimal: number) {
29
+ try {
30
+ if (typeof value === 'bigint') {
31
+ return formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal });
32
+ }
33
+ return value;
34
+ } catch (error) {
35
+ console.error('Error in safeValue:', error);
36
+ return 0;
37
+ }
38
+ }
39
+
40
+ // const safeValue = (value: NumberPrimitives, decimal: number) =>
41
+ // typeof value === 'bigint'
42
+ // ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
43
+ // : value;
44
+
45
+ type AssetValueParams = { decimal: number; value: SwapKitValueType; tax?: TokenTax } & (
46
+ | { chain: Chain; symbol: string }
47
+ | { identifier: string }
48
+ );
49
+
50
+ type TCTokenNames = (typeof ThorchainList)['tokens'][number]['identifier'];
51
+
52
+ type TokenNames =
53
+ | TCTokenNames
54
+ | (typeof CoinGeckoList)['tokens'][number]['identifier']
55
+ | (typeof MayaList)['tokens'][number]['identifier']
56
+ | (typeof PancakeswapETHList)['tokens'][number]['identifier']
57
+ | (typeof PancakeswapList)['tokens'][number]['identifier']
58
+ | (typeof PangolinList)['tokens'][number]['identifier']
59
+ | (typeof StargateARBList)['tokens'][number]['identifier']
60
+ | (typeof SushiswapList)['tokens'][number]['identifier']
61
+ | (typeof TraderjoeList)['tokens'][number]['identifier']
62
+ | (typeof WoofiList)['tokens'][number]['identifier']
63
+ | (typeof UniswapList)['tokens'][number]['identifier']
64
+ | (typeof PioneerList)['tokens'][number]['identifier'];
65
+
66
+ let staticTokensMap:
67
+ | Map<TokenNames, { tax?: TokenTax; decimal: number; identifier: string }>
68
+ | undefined;
69
+
70
+ const getStaticToken = (identifier: TokenNames) => {
71
+ if (!staticTokensMap) {
72
+ throw new Error('Static assets not loaded, call await AssetValue.loadStaticAssets() first');
73
+ }
74
+ //console.log('getStaticToken: staticTokensMap: ', staticTokensMap);
75
+ //console.log('getStaticToken: identifier: ', identifier.toUpperCase());
76
+ const tokenInfo = staticTokensMap.get(identifier.toUpperCase() as TokenNames);
77
+
78
+ return tokenInfo || { decimal: BaseDecimal.THOR, identifier: '' };
79
+ };
80
+
81
+ const createAssetValue = async (assetString: string, value: NumberPrimitives = 0) => {
82
+ validateIdentifier(assetString);
83
+
84
+ const decimal = await getDecimal(getAssetInfo(assetString));
85
+ const parsedValue = safeValue(value, decimal);
86
+
87
+ return new AssetValue({ decimal, value: parsedValue, identifier: assetString });
88
+ };
89
+
90
+ export class AssetValue extends BigIntArithmetics {
91
+ address?: string;
92
+ caip?: string;
93
+ chain: Chain;
94
+ isGasAsset = false;
95
+ isSynthetic = false;
96
+ symbol: string;
97
+ tax?: TokenTax;
98
+ ticker: string;
99
+ type: ReturnType<typeof getAssetType>;
100
+
101
+ // @ts-ignore
102
+ constructor(params: AssetValueParams) {
103
+ const identifier =
104
+ 'identifier' in params ? params.identifier : `${params.chain}.${params.symbol}`;
105
+ console.log('identifier: ', identifier);
106
+
107
+ let value;
108
+ if (params.value instanceof BigIntArithmetics) {
109
+ value = params.value;
110
+ } else {
111
+ value = { decimal: params.decimal, value: params.value };
112
+ }
113
+ console.log('value: ', value);
114
+ super(value);
115
+
116
+ // super(
117
+ // params.value instanceof BigIntArithmetics
118
+ // ? params.value
119
+ // : { decimal: params.decimal, value: params.value },
120
+ // );
121
+
122
+ const assetInfo = getAssetInfo(identifier);
123
+ console.log('assetInfo: ', assetInfo);
124
+ this.type = getAssetType(assetInfo);
125
+ this.chain = assetInfo.chain;
126
+ this.ticker = assetInfo.ticker;
127
+ this.symbol = assetInfo.symbol;
128
+ this.address = assetInfo.address;
129
+ this.isSynthetic = assetInfo.isSynthetic;
130
+ // @ts-ignore
131
+ this.isGasAsset = assetInfo.isGasAsset;
132
+
133
+ this.tax = params.tax;
134
+ }
135
+
136
+ toString(short = false) {
137
+ const shortFormat = this.isSynthetic ? this.symbol : this.ticker;
138
+
139
+ return short
140
+ ? // ETH/THOR-0xa5f2211b9b8170f694421f2046281775e8468044 | USDT
141
+ shortFormat
142
+ : // THOR.ETH/ETH | ETH.USDT-0x1234567890
143
+ `${this.chain}.${this.symbol}`;
144
+ }
145
+
146
+ toUrl() {
147
+ return this.isSynthetic ? `${this.chain}.${this.symbol.replace('/', '.')}` : this.toString();
148
+ }
149
+
150
+ eq({ chain, symbol }: { chain: Chain; symbol: string }) {
151
+ return this.chain === chain && this.symbol === symbol;
152
+ }
153
+
154
+ static async fromString(assetString: string, value: NumberPrimitives = 0) {
155
+ return createAssetValue(assetString, value);
156
+ }
157
+
158
+ // static fromStringSync(assetString: string, value: NumberPrimitives = 0) {
159
+ // const { isSynthetic, symbol, chain, isGasAsset, ticker, address } = getAssetInfo(assetString);
160
+ // console.log('getAssetInfo: ', { isSynthetic, symbol, chain, isGasAsset, ticker, address });
161
+ // const { tax, decimal, identifier: tokenIdentifier } = getStaticToken(assetString as unknown as TokenNames);
162
+ // console.log('getStaticToken: ', { tax, decimal, tokenIdentifier });
163
+ //
164
+ // // Convert value to a BigInt if necessary
165
+ // let safeValue = (val: NumberPrimitives, decimal: number): BigInt => {
166
+ // if (typeof val === 'bigint') {
167
+ // return val;
168
+ // } else if (typeof val === 'number') {
169
+ // return BigInt(val * Math.pow(10, decimal));
170
+ // } else {
171
+ // return BigInt(0);
172
+ // }
173
+ // };
174
+ //
175
+ // const parsedValue = safeValue(value, decimal);
176
+ // console.log('parsedValue: ', parsedValue);
177
+ //
178
+ // let asset: AssetValue | undefined;
179
+ //
180
+ // if (tokenIdentifier) {
181
+ // console.log('tokenIdentifier is truthy'); // Indicates tokenIdentifier has a value considered true in a boolean context
182
+ // asset = new AssetValue({
183
+ // tax,
184
+ // decimal,
185
+ // identifier: tokenIdentifier,
186
+ // value: parsedValue,
187
+ // });
188
+ // } else if (isSynthetic) {
189
+ // console.log('isSynthetic is true'); // Indicates the asset is synthetic
190
+ // asset = new AssetValue({
191
+ // tax,
192
+ // decimal: 8, // Synthetic assets use a fixed decimal value
193
+ // identifier: assetString,
194
+ // value: parsedValue,
195
+ // });
196
+ // } else {
197
+ // asset = undefined;
198
+ // }
199
+ //
200
+ // return asset;
201
+ // }
202
+
203
+ static fromStringSync(assetString: string, value: NumberPrimitives = 0) {
204
+ const { isSynthetic, symbol, chain, isGasAsset, ticker, address } = getAssetInfo(assetString);
205
+ console.log('getAssetInfo: ', { isSynthetic, symbol, chain, isGasAsset, ticker, address });
206
+ const {
207
+ tax,
208
+ decimal,
209
+ identifier: tokenIdentifier,
210
+ } = getStaticToken(assetString as unknown as TokenNames);
211
+ console.log('getStaticToken: ', { tax, decimal, tokenIdentifier });
212
+ console.log('value: ', value);
213
+ console.log('decimal: ', decimal);
214
+ const parsedValue = safeValue(value, decimal);
215
+ console.log('parsedValue: ', parsedValue);
216
+ let asset: AssetValue | undefined;
217
+
218
+ if (tokenIdentifier) {
219
+ console.log('tokenIdentifier is truthy'); // Indicates tokenIdentifier has a value considered true in a boolean context
220
+ asset = new AssetValue({
221
+ tax,
222
+ decimal,
223
+ identifier: tokenIdentifier,
224
+ value: parsedValue,
225
+ });
226
+ } else if (isSynthetic) {
227
+ console.log('isSynthetic is true'); // Indicates the asset is synthetic
228
+ asset = new AssetValue({
229
+ tax,
230
+ decimal: 8, // Synthetic assets use a fixed decimal value
231
+ identifier: assetString,
232
+ value: parsedValue,
233
+ });
234
+ } else {
235
+ //console.log('No valid condition met'); // Neither condition is true, asset is left undefined
236
+ asset = undefined;
237
+ }
238
+
239
+ return asset;
240
+ }
241
+
242
+ static async fromIdentifier(
243
+ assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`,
244
+ value: NumberPrimitives = 0,
245
+ ) {
246
+ return createAssetValue(assetString, value);
247
+ }
248
+
249
+ static fromIdentifierSync(identifier: TokenNames, value: NumberPrimitives = 0) {
250
+ const { decimal, identifier: tokenIdentifier } = getStaticToken(identifier);
251
+ const parsedValue = safeValue(value, decimal);
252
+
253
+ return new AssetValue({ decimal, identifier: tokenIdentifier, value: parsedValue });
254
+ }
255
+
256
+ static fromChainOrSignature(assetString: CommonAssetString, value: NumberPrimitives = 0) {
257
+ const { decimal, identifier } = getCommonAssetInfo(assetString);
258
+ if (!decimal || !identifier) throw Error('unknown coin! ' + assetString);
259
+ const parsedValue = safeValue(value, decimal);
260
+
261
+ return new AssetValue({ value: parsedValue, decimal, identifier });
262
+ }
263
+
264
+ static async loadStaticAssets() {
265
+ return new Promise<{ ok: true } | { ok: false; message: string; error: any }>(
266
+ async (resolve, reject) => {
267
+ try {
268
+ // @ts-ignore
269
+ const {
270
+ // Omit ThorchainList from import to avoid decimals conflict (TC uses 8 for all)
271
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
272
+ ThorchainList: _ThorchainList,
273
+ NativeList,
274
+ ...tokensPackage
275
+ //@ts-ignore
276
+ } = await import('@coinmasters/tokens');
277
+ const tokensMap = [NativeList, ...Object.values(tokensPackage)].reduce(
278
+ (acc, { tokens }) => {
279
+ // @ts-ignore
280
+ tokens.forEach(({ identifier, chain, ...rest }) => {
281
+ //@ts-ignore
282
+ const decimal = 'decimals' in rest ? rest.decimals : BaseDecimal[chain as Chain];
283
+
284
+ acc.set(identifier as TokenNames, { identifier, decimal });
285
+ });
286
+
287
+ return acc;
288
+ },
289
+ new Map<TokenNames, { decimal: number; identifier: string }>(),
290
+ );
291
+
292
+ staticTokensMap = tokensMap;
293
+
294
+ resolve({ ok: true });
295
+ } catch (error) {
296
+ console.error(error);
297
+ reject({
298
+ ok: false,
299
+ error,
300
+ message:
301
+ "Couldn't load static assets. Ensure you have installed @coinmasters/tokens package",
302
+ });
303
+ }
304
+ },
305
+ );
306
+ }
307
+ }
308
+
309
+ export const getMinAmountByChain = (chain: Chain) => {
310
+ const asset = AssetValue.fromChainOrSignature(chain);
311
+
312
+ switch (chain) {
313
+ case Chain.Bitcoin:
314
+ case Chain.Litecoin:
315
+ case Chain.Dash:
316
+ case Chain.Zcash:
317
+ case Chain.BitcoinCash:
318
+ return asset.set(0.00010001);
319
+
320
+ case Chain.Dogecoin:
321
+ return asset.set(1.00000001);
322
+
323
+ case Chain.Base:
324
+ case Chain.Arbitrum:
325
+ case Chain.Avalanche:
326
+ case Chain.Ethereum:
327
+ return asset.set(0.00000001);
328
+
329
+ case Chain.THORChain:
330
+ //@ts-ignore
331
+ case Chain.Mayachain:
332
+ return asset.set(0.0000000001);
333
+
334
+ default:
335
+ return asset.set(0.00000001);
336
+ }
337
+ };
338
+
339
+ const getAssetInfo = (identifier: string) => {
340
+ const isSynthetic = identifier.slice(0, 14).includes('/');
341
+ const [synthChain, synthSymbol] = identifier.split('.').pop()!.split('/');
342
+ const adjustedIdentifier =
343
+ identifier.includes('.') && !isSynthetic ? identifier : `${Chain.THORChain}.${synthSymbol}`;
344
+
345
+ const [chain, symbol] = adjustedIdentifier.split('.') as [Chain, string];
346
+ const [ticker, address] = (isSynthetic ? synthSymbol : symbol).split('-') as [string, string?];
347
+
348
+ return {
349
+ address: address?.toLowerCase(),
350
+ chain,
351
+ isGasAsset: isGasAsset({ chain, symbol }),
352
+ isSynthetic,
353
+ symbol:
354
+ (isSynthetic ? `${synthChain}/` : '') +
355
+ (address ? `${ticker}-${address?.toLowerCase() ?? ''}` : symbol),
356
+ ticker,
357
+ };
358
+ };