@swapkit/helpers 1.0.0-rc.11 → 1.0.0-rc.111

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 (42) hide show
  1. package/dist/index.js +2900 -0
  2. package/dist/index.js.map +31 -0
  3. package/package.json +26 -37
  4. package/src/helpers/__tests__/asset.test.ts +186 -103
  5. package/src/helpers/__tests__/memo.test.ts +53 -41
  6. package/src/helpers/__tests__/others.test.ts +44 -37
  7. package/src/helpers/__tests__/validators.test.ts +24 -0
  8. package/src/helpers/asset.ts +184 -95
  9. package/src/helpers/derivationPath.ts +53 -0
  10. package/src/helpers/liquidity.ts +50 -43
  11. package/src/helpers/memo.ts +34 -31
  12. package/src/helpers/others.ts +46 -12
  13. package/src/helpers/validators.ts +15 -6
  14. package/src/helpers/web3wallets.ts +200 -0
  15. package/src/index.ts +14 -9
  16. package/src/modules/__tests__/assetValue.test.ts +486 -129
  17. package/src/modules/__tests__/bigIntArithmetics.test.ts +30 -0
  18. package/src/modules/__tests__/swapKitNumber.test.ts +306 -183
  19. package/src/modules/assetValue.ts +220 -162
  20. package/src/modules/bigIntArithmetics.ts +214 -165
  21. package/src/modules/requestClient.ts +38 -0
  22. package/src/modules/swapKitError.ts +41 -5
  23. package/src/modules/swapKitNumber.ts +1 -1
  24. package/src/types/abis/erc20.ts +99 -0
  25. package/src/types/abis/mayaEvmVaults.ts +331 -0
  26. package/src/types/abis/tcEthVault.ts +496 -0
  27. package/src/types/chains.ts +226 -0
  28. package/src/types/commonTypes.ts +123 -0
  29. package/src/types/derivationPath.ts +58 -0
  30. package/src/types/errors/apiV1.ts +0 -0
  31. package/src/types/index.ts +12 -0
  32. package/src/types/network.ts +45 -0
  33. package/src/types/quotes.ts +391 -0
  34. package/src/types/radix.ts +14 -0
  35. package/src/types/sdk.ts +126 -0
  36. package/src/types/tokens.ts +30 -0
  37. package/src/types/wallet.ts +72 -0
  38. package/LICENSE +0 -201
  39. package/dist/index.cjs +0 -1
  40. package/dist/index.d.ts +0 -356
  41. package/dist/index.es.js +0 -1071
  42. package/src/helpers/request.ts +0 -16
@@ -1,6 +1,5 @@
1
- import { BaseDecimal } from '@swapkit/types';
2
-
3
- import type { SwapKitNumber } from './swapKitNumber.ts';
1
+ import { BaseDecimal } from "../types/chains.ts";
2
+ import type { SwapKitNumber } from "./swapKitNumber.ts";
4
3
 
5
4
  type NumberPrimitivesType = {
6
5
  bigint: bigint;
@@ -11,10 +10,12 @@ export type NumberPrimitives = bigint | number | string;
11
10
  type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber;
12
11
 
13
12
  type SKBigIntParams = InitialisationValueType | { decimal?: number; value: number | string };
13
+ type AllowedNumberTypes = "bigint" | "number" | "string";
14
14
 
15
15
  const DEFAULT_DECIMAL = 8;
16
16
  const toMultiplier = (decimal: number) => 10n ** BigInt(decimal);
17
- const decimalFromMultiplier = (multiplier: bigint) => Math.log10(parseFloat(multiplier.toString()));
17
+ const decimalFromMultiplier = (multiplier: bigint) =>
18
+ Math.log10(Number.parseFloat(multiplier.toString()));
18
19
 
19
20
  export function formatBigIntToSafeValue({
20
21
  value,
@@ -25,38 +26,39 @@ export function formatBigIntToSafeValue({
25
26
  bigIntDecimal?: number;
26
27
  decimal?: number;
27
28
  }) {
29
+ if (decimal === 0) return value.toString();
28
30
  const isNegative = value < 0n;
29
31
  let valueString = value.toString().substring(isNegative ? 1 : 0);
30
32
 
31
33
  const padLength = decimal - (valueString.length - 1);
32
34
 
33
35
  if (padLength > 0) {
34
- valueString = '0'.repeat(padLength) + valueString;
36
+ valueString = "0".repeat(padLength) + valueString;
35
37
  }
36
38
 
37
39
  const decimalIndex = valueString.length - decimal;
38
40
  let decimalString = valueString.slice(-decimal);
39
41
 
40
42
  // Check if we need to round up
41
- if (parseInt(decimalString[bigIntDecimal]) >= 5) {
43
+ if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
42
44
  // Increment the last decimal place and slice off the rest
43
45
  decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(
44
- parseInt(decimalString[bigIntDecimal - 1]) + 1
46
+ Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1
45
47
  ).toString()}`;
46
48
  } else {
47
49
  // Just slice off the extra digits
48
50
  decimalString = decimalString.substring(0, bigIntDecimal);
49
51
  }
50
52
 
51
- return `${isNegative ? '-' : ''}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(
53
+ return `${isNegative ? "-" : ""}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(
52
54
  /\.?0*$/,
53
- '',
55
+ "",
54
56
  );
55
57
  }
56
58
 
57
59
  export class BigIntArithmetics {
58
60
  decimalMultiplier: bigint = 10n ** 8n;
59
- bigIntValue: bigint = 0n;
61
+ bigIntValue = 0n;
60
62
  decimal?: number;
61
63
 
62
64
  static fromBigInt(value: bigint, decimal?: number) {
@@ -71,217 +73,237 @@ export class BigIntArithmetics {
71
73
  from,
72
74
  to,
73
75
  }: {
74
- value: InitialisationValueType;
76
+ value: InstanceType<typeof SwapKitNumber>;
75
77
  from: number;
76
78
  to: number;
77
79
  }) {
78
- return this.fromBigInt(
79
- (new BigIntArithmetics(value).bigIntValue * toMultiplier(to)) / toMultiplier(from),
80
+ return BigIntArithmetics.fromBigInt(
81
+ (value.getBaseValue("bigint") * toMultiplier(to)) / toMultiplier(from),
80
82
  to,
81
83
  );
82
84
  }
83
85
 
84
86
  constructor(params: SKBigIntParams) {
85
87
  const value = getStringValue(params);
86
- this.decimal = typeof params === 'object' ? params.decimal : undefined;
88
+ const isComplex = typeof params === "object";
89
+ this.decimal = isComplex ? params.decimal : undefined;
87
90
 
88
91
  // use the multiplier to keep track of decimal point - defaults to 8 if lower than 8
89
- this.decimalMultiplier = toMultiplier(
90
- Math.max(this.#getFloatDecimals(this.#toSafeValue(value)), this.decimal || 0),
91
- );
92
+ this.decimalMultiplier =
93
+ isComplex && "decimalMultiplier" in params
94
+ ? params.decimalMultiplier
95
+ : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0));
92
96
  this.#setValue(value);
93
97
  }
94
98
 
95
- /**
96
- * @deprecated Use `getBaseValue('string')` instead
97
- */
98
- get baseValue() {
99
- return this.getBaseValue('string') as string;
100
- }
101
- /**
102
- * @deprecated Use `getBaseValue('number')` instead
103
- */
104
- get baseValueNumber() {
105
- return this.getBaseValue('number') as number;
106
- }
107
- /**
108
- * @deprecated Use `getBaseValue('bigint')` instead
109
- */
110
- get baseValueBigInt() {
111
- return this.getBaseValue('bigint') as bigint;
112
- }
113
-
114
- set(value: SKBigIntParams) {
99
+ set(value: SKBigIntParams): this {
115
100
  // @ts-expect-error False positive
116
101
  return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
117
102
  }
118
103
  add(...args: InitialisationValueType[]) {
119
- return this.#arithmetics('add', ...args);
104
+ return this.#arithmetics("add", ...args);
120
105
  }
121
106
  sub(...args: InitialisationValueType[]) {
122
- return this.#arithmetics('sub', ...args);
107
+ return this.#arithmetics("sub", ...args);
123
108
  }
124
109
  mul(...args: InitialisationValueType[]) {
125
- return this.#arithmetics('mul', ...args);
110
+ return this.#arithmetics("mul", ...args);
126
111
  }
127
112
  div(...args: InitialisationValueType[]) {
128
- return this.#arithmetics('div', ...args);
113
+ return this.#arithmetics("div", ...args);
129
114
  }
130
115
  gt(value: InitialisationValueType) {
131
- return this.bigIntValue > this.getBigIntValue(value);
116
+ return this.#comparison("gt", value);
132
117
  }
133
118
  gte(value: InitialisationValueType) {
134
- return this.bigIntValue >= this.getBigIntValue(value);
119
+ return this.#comparison("gte", value);
135
120
  }
136
121
  lt(value: InitialisationValueType) {
137
- return this.bigIntValue < this.getBigIntValue(value);
122
+ return this.#comparison("lt", value);
138
123
  }
139
124
  lte(value: InitialisationValueType) {
140
- return this.bigIntValue <= this.getBigIntValue(value);
125
+ return this.#comparison("lte", value);
141
126
  }
142
127
  eqValue(value: InitialisationValueType) {
143
- return this.bigIntValue === this.getBigIntValue(value);
128
+ return this.#comparison("eqValue", value);
144
129
  }
145
130
 
146
- getValue<T extends 'number' | 'string'>(type: T): NumberPrimitivesType[T] {
131
+ // @ts-expect-error False positive
132
+ getValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T] {
147
133
  const value = this.formatBigIntToSafeValue(
148
134
  this.bigIntValue,
149
135
  this.decimal || decimalFromMultiplier(this.decimalMultiplier),
150
136
  );
151
137
 
152
138
  switch (type) {
153
- case 'number':
154
- // @ts-expect-error False positive
155
- return Number(value);
156
- case 'string':
157
- // @ts-expect-error False positive
158
- return value;
159
- default:
160
- // @ts-expect-error False positive
161
- return (this.bigIntValue * BigInt(this.decimal || 8n)) / this.decimalMultiplier;
139
+ case "number":
140
+ return Number(value) as NumberPrimitivesType[T];
141
+ case "string":
142
+ return value as NumberPrimitivesType[T];
143
+ case "bigint":
144
+ return ((this.bigIntValue * 10n ** BigInt(this.decimal || 8n)) /
145
+ this.decimalMultiplier) as NumberPrimitivesType[T];
162
146
  }
163
147
  }
164
148
 
165
- getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T] {
149
+ // @ts-expect-error
150
+ getBaseValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T] {
166
151
  const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);
167
152
  const baseValue = this.bigIntValue / divisor;
168
153
 
169
154
  switch (type) {
170
- case 'number':
171
- // @ts-expect-error False positive
172
- return Number(baseValue);
173
- case 'string':
174
- // @ts-expect-error False positive
175
- return baseValue.toString();
176
- default:
177
- // @ts-expect-error False positive
178
- return baseValue;
155
+ case "number":
156
+ return Number(baseValue) as NumberPrimitivesType[T];
157
+ case "string":
158
+ return baseValue.toString() as NumberPrimitivesType[T];
159
+ case "bigint":
160
+ return baseValue as NumberPrimitivesType[T];
179
161
  }
180
162
  }
181
163
 
182
164
  getBigIntValue(value: InitialisationValueType, decimal?: number) {
183
- if (!decimal && typeof value === 'object') return value.bigIntValue;
165
+ if (!decimal && typeof value === "object") return value.bigIntValue;
184
166
 
185
167
  const stringValue = getStringValue(value);
186
- const safeValue = this.#toSafeValue(stringValue);
168
+ const safeValue = toSafeValue(stringValue);
187
169
 
188
- if (safeValue === '0' || safeValue === 'undefined') return 0n;
170
+ if (safeValue === "0" || safeValue === "undefined") return 0n;
189
171
  return this.#toBigInt(safeValue, decimal);
190
172
  }
191
173
 
192
- formatBigIntToSafeValue(value: bigint, decimal?: number) {
193
- const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;
194
- const decimalToUseForConversion = Math.max(
195
- bigIntDecimal,
196
- decimalFromMultiplier(this.decimalMultiplier),
197
- );
198
- const isNegative = value < 0n;
199
-
200
- const valueString = value.toString().substring(isNegative ? 1 : 0);
201
- const padLength = decimalToUseForConversion - (valueString.length - 1);
202
-
203
- const parsedValueString = padLength > 0 ? '0'.repeat(padLength) + valueString : valueString;
204
-
205
- const decimalIndex = parsedValueString.length - decimalToUseForConversion;
206
- let decimalString = parsedValueString.slice(-decimalToUseForConversion);
207
-
208
- // Check if we need to round up
209
- if (parseInt(decimalString[bigIntDecimal]) >= 5) {
210
- // Increment the last decimal place and slice off the rest
211
- decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(
212
- parseInt(decimalString[bigIntDecimal - 1]) + 1
213
- ).toString()}`;
214
- } else {
215
- // Just slice off the extra digits
216
- decimalString = decimalString.substring(0, bigIntDecimal);
217
- }
218
-
219
- return `${isNegative ? '-' : ''}${parsedValueString.slice(
220
- 0,
221
- decimalIndex,
222
- )}.${decimalString}`.replace(/\.?0*$/, '');
223
- }
224
-
225
- toSignificant(significantDigits: number = 6) {
226
- const [int, dec] = this.getValue('string').split('.');
227
- const integer = int || '';
228
- const decimal = dec || '';
229
- const valueLength = parseInt(integer) ? integer.length + decimal.length : decimal.length;
174
+ toSignificant(significantDigits = 6) {
175
+ const [int, dec] = this.getValue("string").split(".");
176
+ const integer = int || "";
177
+ const decimal = dec || "";
178
+ const valueLength = Number.parseInt(integer) ? integer.length + decimal.length : decimal.length;
230
179
 
231
180
  if (valueLength <= significantDigits) {
232
- return this.getValue('string');
181
+ return this.getValue("string");
233
182
  }
234
183
 
235
184
  if (integer.length >= significantDigits) {
236
- return integer.slice(0, significantDigits).padEnd(integer.length, '0');
185
+ return integer.slice(0, significantDigits).padEnd(integer.length, "0");
237
186
  }
238
187
 
239
- if (parseInt(integer)) {
188
+ if (Number.parseInt(integer)) {
240
189
  return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(
241
- valueLength - significantDigits,
242
- '0',
190
+ significantDigits - integer.length,
191
+ "0",
243
192
  );
244
193
  }
245
194
 
246
- const trimmedDecimal = parseInt(decimal);
195
+ const trimmedDecimal = Number.parseInt(decimal);
247
196
  const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits);
248
197
 
249
198
  return `0.${slicedDecimal.padStart(
250
199
  decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length,
251
- '0',
200
+ "0",
252
201
  )}`;
253
202
  }
254
203
 
255
- toFixed(fixedDigits: number = 6) {
256
- const [int, dec] = this.getValue('string').split('.');
257
- const integer = int || '';
258
- const decimal = dec || '';
204
+ toFixed(fixedDigits = 6) {
205
+ const [int, dec] = this.getValue("string").split(".");
206
+ const integer = int || "";
207
+ const decimal = dec || "";
259
208
 
260
- if (parseInt(integer)) {
261
- return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, '0');
209
+ if (Number.parseInt(integer)) {
210
+ return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, "0");
262
211
  }
263
212
 
264
- const trimmedDecimal = parseInt(decimal);
213
+ const trimmedDecimal = Number.parseInt(decimal);
265
214
  const slicedDecimal = `${trimmedDecimal}`.slice(0, fixedDigits);
266
215
 
267
216
  return `0.${slicedDecimal.padStart(
268
217
  decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length,
269
- '0',
218
+ "0",
270
219
  )}`;
271
220
  }
272
221
 
273
- #arithmetics(method: 'add' | 'sub' | 'mul' | 'div', ...args: InitialisationValueType[]): this {
222
+ toAbbreviation(digits = 2) {
223
+ const value = this.getValue("number");
224
+ const abbreviations = ["", "K", "M", "B", "T", "Q", "Qi", "S"];
225
+ const tier = Math.floor(Math.log10(Math.abs(value)) / 3);
226
+ const suffix = abbreviations[tier];
227
+
228
+ if (!suffix) return this.getValue("string");
229
+
230
+ const scale = 10 ** (tier * 3);
231
+ const scaled = value / scale;
232
+
233
+ return `${scaled.toFixed(digits)}${suffix}`;
234
+ }
235
+
236
+ toCurrency(
237
+ currency = "$",
238
+ {
239
+ currencyPosition = "start",
240
+ decimal = 2,
241
+ decimalSeparator = ".",
242
+ thousandSeparator = ",",
243
+ } = {},
244
+ ) {
245
+ const value = this.getValue("number");
246
+ const [int = "", dec = ""] = value.toFixed(6).split(".");
247
+ const integer = int.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
248
+
249
+ const parsedValue =
250
+ int || dec
251
+ ? int === "0"
252
+ ? `${Number.parseFloat(`0.${dec}`)}`.replace(".", decimalSeparator)
253
+ : `${integer}${Number.parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ""}`
254
+ : "0.00";
255
+
256
+ return `${currencyPosition === "start" ? currency : ""}${parsedValue}${
257
+ currencyPosition === "end" ? currency : ""
258
+ }`;
259
+ }
260
+
261
+ formatBigIntToSafeValue(value: bigint, decimal?: number) {
262
+ const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;
263
+ const decimalToUseForConversion = Math.max(
264
+ bigIntDecimal,
265
+ decimalFromMultiplier(this.decimalMultiplier),
266
+ );
267
+ const isNegative = value < 0n;
268
+
269
+ const valueString = value.toString().substring(isNegative ? 1 : 0);
270
+ const padLength = decimalToUseForConversion - (valueString.length - 1);
271
+
272
+ const parsedValueString = padLength > 0 ? "0".repeat(padLength) + valueString : valueString;
273
+
274
+ const decimalIndex = parsedValueString.length - decimalToUseForConversion;
275
+ let decimalString = parsedValueString.slice(-decimalToUseForConversion);
276
+
277
+ // Check if we need to round up
278
+ if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
279
+ // Increment the last decimal place and slice off the rest
280
+ decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(
281
+ Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1
282
+ ).toString()}`;
283
+ } else {
284
+ // Just slice off the extra digits
285
+ decimalString = decimalString.substring(0, bigIntDecimal);
286
+ }
287
+
288
+ return `${isNegative ? "-" : ""}${parsedValueString.slice(
289
+ 0,
290
+ decimalIndex,
291
+ )}.${decimalString}`.replace(/\.?0*$/, "");
292
+ }
293
+
294
+ #arithmetics(method: "add" | "sub" | "mul" | "div", ...args: InitialisationValueType[]): this {
274
295
  const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
275
- const precisionDecimalMultiplier = toMultiplier(precisionDecimal);
296
+ const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier));
297
+ const precisionDecimalMultiplier = toMultiplier(decimal);
276
298
 
277
299
  const result = args.reduce(
278
300
  (acc: bigint, arg) => {
279
- const value = this.getBigIntValue(arg, precisionDecimal);
301
+ const value = this.getBigIntValue(arg, decimal);
280
302
 
281
303
  switch (method) {
282
- case 'add':
304
+ case "add":
283
305
  return acc + value;
284
- case 'sub':
306
+ case "sub":
285
307
  return acc - value;
286
308
  /**
287
309
  * Multiplication & division would end up with wrong result if we don't adjust the value
@@ -291,10 +313,10 @@ export class BigIntArithmetics {
291
313
  * 200000000n * 200000000n = 40000000000000000n / 100000000n (decimals) => 400000000n
292
314
  * (200000000n * 100000000n (decimals)) / 200000000n => 100000000n
293
315
  */
294
- case 'mul':
316
+ case "mul":
295
317
  return (acc * value) / precisionDecimalMultiplier;
296
- case 'div': {
297
- if (value === 0n) throw new RangeError('Division by zero');
318
+ case "div": {
319
+ if (value === 0n) throw new RangeError("Division by zero");
298
320
  return (acc * precisionDecimalMultiplier) / value;
299
321
  }
300
322
  default:
@@ -306,65 +328,92 @@ export class BigIntArithmetics {
306
328
  );
307
329
 
308
330
  const value = formatBigIntToSafeValue({
309
- bigIntDecimal: precisionDecimal,
310
- decimal: Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier)),
331
+ bigIntDecimal: decimal,
332
+ decimal,
311
333
  value: result,
312
334
  });
313
335
 
314
336
  // @ts-expect-error False positive
315
- return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
337
+ return new this.constructor({
338
+ decimalMultiplier: toMultiplier(decimal),
339
+ decimal: this.decimal,
340
+ value,
341
+ identifier: this.toString(),
342
+ });
343
+ }
344
+
345
+ #comparison(method: "gt" | "gte" | "lt" | "lte" | "eqValue", ...args: InitialisationValueType[]) {
346
+ const decimal = this.#retrievePrecisionDecimal(this, ...args);
347
+ const value = this.getBigIntValue(args[0] || "0", decimal);
348
+ const compareToValue = this.getBigIntValue(this, decimal);
349
+
350
+ switch (method) {
351
+ case "gt":
352
+ return compareToValue > value;
353
+ case "gte":
354
+ return compareToValue >= value;
355
+ case "lt":
356
+ return compareToValue < value;
357
+ case "lte":
358
+ return compareToValue <= value;
359
+ case "eqValue":
360
+ return compareToValue === value;
361
+ }
316
362
  }
317
363
 
318
364
  #setValue(value: InitialisationValueType) {
319
- const safeValue = this.#toSafeValue(value) || '0';
365
+ const safeValue = toSafeValue(value) || "0";
320
366
  this.bigIntValue = this.#toBigInt(safeValue);
321
367
  }
322
368
 
323
369
  #retrievePrecisionDecimal(...args: InitialisationValueType[]) {
324
370
  const decimals = args
325
- .map((arg) =>
326
- typeof arg === 'object'
371
+ .map((arg) => {
372
+ const isObject = typeof arg === "object";
373
+ const value = isObject
327
374
  ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier)
328
- : this.#getFloatDecimals(this.#toSafeValue(arg)),
329
- )
375
+ : getFloatDecimals(toSafeValue(arg));
376
+
377
+ return value;
378
+ })
330
379
  .filter(Boolean) as number[];
380
+
331
381
  return Math.max(...decimals, DEFAULT_DECIMAL);
332
382
  }
333
383
 
334
384
  #toBigInt(value: string, decimal?: number) {
335
385
  const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
336
386
  const padDecimal = decimalFromMultiplier(multiplier);
337
- const [integerPart = '', decimalPart = ''] = value.split('.');
387
+ const [integerPart = "", decimalPart = ""] = value.split(".");
338
388
 
339
- return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, '0')}`);
389
+ return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, "0")}`);
340
390
  }
391
+ }
341
392
 
342
- #toSafeValue(value: InitialisationValueType) {
343
- const parsedValue =
344
- typeof value === 'number'
345
- ? Number(value).toLocaleString('fullwide', {
346
- useGrouping: false,
347
- maximumFractionDigits: 20,
348
- })
349
- : getStringValue(value);
350
-
351
- const splitValue = `${parsedValue}`.replaceAll(',', '.').split('.');
352
-
353
- return splitValue.length > 1
354
- ? `${splitValue.slice(0, -1).join('')}.${splitValue.at(-1)}`
355
- : splitValue[0];
356
- }
393
+ const numberFormatter = Intl.NumberFormat("fullwide", {
394
+ useGrouping: false,
395
+ maximumFractionDigits: 20,
396
+ });
357
397
 
358
- #getFloatDecimals(value: string) {
359
- const decimals = value.split('.')[1]?.length || 0;
360
- return Math.max(decimals, DEFAULT_DECIMAL);
361
- }
398
+ function toSafeValue(value: InitialisationValueType) {
399
+ const parsedValue =
400
+ typeof value === "number" ? numberFormatter.format(value) : getStringValue(value);
401
+ const splitValue = `${parsedValue}`.replaceAll(",", ".").split(".");
402
+
403
+ return splitValue.length > 1
404
+ ? `${splitValue.slice(0, -1).join("")}.${splitValue.at(-1)}`
405
+ : splitValue[0] || "0";
406
+ }
407
+
408
+ function getFloatDecimals(value: string) {
409
+ const decimals = value.split(".")[1]?.length || 0;
410
+ return Math.max(decimals, DEFAULT_DECIMAL);
362
411
  }
363
412
 
364
- function getStringValue(value: SKBigIntParams) {
365
- return typeof value === 'object'
366
- ? 'getValue' in value
367
- ? value.getValue('string')
368
- : value.value
369
- : value;
413
+ function getStringValue(param: SKBigIntParams) {
414
+ return typeof param === "object"
415
+ ? "getValue" in param
416
+ ? param.getValue("string")
417
+ : param.value
418
+ : param;
370
419
  }
@@ -0,0 +1,38 @@
1
+ import type { KyInstance, Options } from "ky";
2
+ import ky from "ky";
3
+
4
+ let kyClient: typeof ky;
5
+
6
+ export const defaultRequestHeaders =
7
+ typeof window !== "undefined"
8
+ ? ({} as Record<string, string>)
9
+ : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" };
10
+
11
+ export function setRequestClientConfig({ apiKey, ...config }: Options & { apiKey?: string }) {
12
+ kyClient = ky.create({
13
+ ...config,
14
+ headers: { ...defaultRequestHeaders, ...config.headers, "x-api-key": apiKey },
15
+ });
16
+ }
17
+
18
+ function getKyClient() {
19
+ if (kyClient) return kyClient;
20
+ kyClient = ky.create({ headers: defaultRequestHeaders });
21
+ return kyClient;
22
+ }
23
+
24
+ const getTypedBaseRequestClient = (ky: KyInstance) => ({
25
+ get: <T>(url: string | URL | Request, options?: Options) => ky.get(url, options).json<T>(),
26
+ post: <T>(url: string | URL | Request, options?: Options) => ky.post(url, options).json<T>(),
27
+ });
28
+
29
+ export const RequestClient = {
30
+ ...getTypedBaseRequestClient(getKyClient()),
31
+ extend: (options: Options) => {
32
+ const extendedClient = getKyClient().extend(options);
33
+ return {
34
+ ...getTypedBaseRequestClient(extendedClient),
35
+ extend: RequestClient.extend,
36
+ };
37
+ },
38
+ };