@swapkit/helpers 1.0.0-rc.1 → 1.0.0-rc.100

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 (40) hide show
  1. package/dist/index.js +2452 -0
  2. package/dist/index.js.map +30 -0
  3. package/package.json +26 -36
  4. package/src/helpers/__tests__/asset.test.ts +149 -105
  5. package/src/helpers/__tests__/memo.test.ts +52 -40
  6. package/src/helpers/__tests__/others.test.ts +42 -37
  7. package/src/helpers/__tests__/validators.test.ts +24 -0
  8. package/src/helpers/asset.ts +139 -91
  9. package/src/helpers/derivationPath.ts +53 -0
  10. package/src/helpers/liquidity.ts +50 -43
  11. package/src/helpers/memo.ts +31 -28
  12. package/src/helpers/others.ts +35 -57
  13. package/src/helpers/validators.ts +15 -6
  14. package/src/helpers/web3wallets.ts +177 -0
  15. package/src/index.ts +14 -8
  16. package/src/modules/__tests__/assetValue.test.ts +420 -117
  17. package/src/modules/__tests__/bigIntArithmetics.test.ts +30 -0
  18. package/src/modules/__tests__/swapKitNumber.test.ts +351 -149
  19. package/src/modules/assetValue.ts +243 -171
  20. package/src/modules/bigIntArithmetics.ts +313 -153
  21. package/src/modules/requestClient.ts +39 -0
  22. package/src/modules/swapKitError.ts +33 -5
  23. package/src/modules/swapKitNumber.ts +6 -3
  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 +220 -0
  28. package/src/types/commonTypes.ts +119 -0
  29. package/src/types/derivationPath.ts +56 -0
  30. package/src/types/errors/apiV1.ts +0 -0
  31. package/src/types/index.ts +10 -0
  32. package/src/types/network.ts +43 -0
  33. package/src/types/sdk.ts +44 -0
  34. package/src/types/tokens.ts +30 -0
  35. package/src/types/wallet.ts +47 -0
  36. package/LICENSE +0 -201
  37. package/dist/index.cjs +0 -1
  38. package/dist/index.d.ts +0 -333
  39. package/dist/index.es.js +0 -661
  40. package/src/helpers/number.ts +0 -40
@@ -1,14 +1,64 @@
1
- import { DEFAULT_DECIMAL, formatBigIntToSafeValue } from '../helpers/number.ts';
1
+ import { BaseDecimal } from "../types/chains.ts";
2
+ import type { SwapKitNumber } from "./swapKitNumber.ts";
2
3
 
3
- type AllowedValueType = bigint | number | string;
4
- type ArithmeticMethod = 'add' | 'sub' | 'mul' | 'div';
4
+ type NumberPrimitivesType = {
5
+ bigint: bigint;
6
+ number: number;
7
+ string: string;
8
+ };
9
+ export type NumberPrimitives = bigint | number | string;
10
+ type InitialisationValueType = NumberPrimitives | BigIntArithmetics | SwapKitNumber;
5
11
 
12
+ type SKBigIntParams = InitialisationValueType | { decimal?: number; value: number | string };
13
+ type AllowedNumberTypes = "bigint" | "number" | "string";
14
+
15
+ const DEFAULT_DECIMAL = 8;
6
16
  const toMultiplier = (decimal: number) => 10n ** BigInt(decimal);
7
- const decimalFromMultiplier = (multiplier: bigint) => Math.log10(parseFloat(multiplier.toString()));
17
+ const decimalFromMultiplier = (multiplier: bigint) =>
18
+ Math.log10(Number.parseFloat(multiplier.toString()));
19
+
20
+ export function formatBigIntToSafeValue({
21
+ value,
22
+ bigIntDecimal = DEFAULT_DECIMAL,
23
+ decimal = DEFAULT_DECIMAL,
24
+ }: {
25
+ value: bigint;
26
+ bigIntDecimal?: number;
27
+ decimal?: number;
28
+ }) {
29
+ if (decimal === 0) return value.toString();
30
+ const isNegative = value < 0n;
31
+ let valueString = value.toString().substring(isNegative ? 1 : 0);
32
+
33
+ const padLength = decimal - (valueString.length - 1);
34
+
35
+ if (padLength > 0) {
36
+ valueString = "0".repeat(padLength) + valueString;
37
+ }
38
+
39
+ const decimalIndex = valueString.length - decimal;
40
+ let decimalString = valueString.slice(-decimal);
41
+
42
+ // Check if we need to round up
43
+ if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
44
+ // Increment the last decimal place and slice off the rest
45
+ decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(
46
+ Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1
47
+ ).toString()}`;
48
+ } else {
49
+ // Just slice off the extra digits
50
+ decimalString = decimalString.substring(0, bigIntDecimal);
51
+ }
52
+
53
+ return `${isNegative ? "-" : ""}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(
54
+ /\.?0*$/,
55
+ "",
56
+ );
57
+ }
8
58
 
9
59
  export class BigIntArithmetics {
10
60
  decimalMultiplier: bigint = 10n ** 8n;
11
- bigIntValue: bigint = 0n;
61
+ bigIntValue = 0n;
12
62
  decimal?: number;
13
63
 
14
64
  static fromBigInt(value: bigint, decimal?: number) {
@@ -23,86 +73,189 @@ export class BigIntArithmetics {
23
73
  from,
24
74
  to,
25
75
  }: {
26
- value: BigIntArithmetics | string | number;
76
+ value: InstanceType<typeof SwapKitNumber>;
27
77
  from: number;
28
78
  to: number;
29
79
  }) {
30
80
  return BigIntArithmetics.fromBigInt(
31
- (new BigIntArithmetics(value).bigIntValue * toMultiplier(to)) / toMultiplier(from),
81
+ (value.getBaseValue("bigint") * toMultiplier(to)) / toMultiplier(from),
32
82
  to,
33
83
  );
34
84
  }
35
85
 
36
- constructor(
37
- valueOrParams:
38
- | BigIntArithmetics
39
- | string
40
- | number
41
- | { decimal?: number; value: number | string },
42
- ) {
43
- const complexInit = typeof valueOrParams === 'object';
44
- const value = complexInit ? valueOrParams.value : valueOrParams;
45
- this.decimal = complexInit ? valueOrParams.decimal : undefined;
86
+ constructor(params: SKBigIntParams) {
87
+ const value = getStringValue(params);
88
+ const isComplex = typeof params === "object";
89
+ this.decimal = isComplex ? params.decimal : undefined;
46
90
 
47
91
  // use the multiplier to keep track of decimal point - defaults to 8 if lower than 8
48
- this.decimalMultiplier = toMultiplier(
49
- Math.max(this.#getFloatDecimals(this.#toSafeValue(value)), this.decimal || 0),
50
- );
92
+ this.decimalMultiplier =
93
+ isComplex && "decimalMultiplier" in params
94
+ ? params.decimalMultiplier
95
+ : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0));
51
96
  this.#setValue(value);
52
97
  }
53
98
 
54
- get unsafeNumber() {
55
- return parseFloat((this.bigIntValue / this.decimalMultiplier).toString());
99
+ set(value: SKBigIntParams): this {
100
+ // @ts-expect-error False positive
101
+ return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
56
102
  }
57
- get baseValue() {
58
- return this.#getBaseValue('string') as string;
103
+ add(...args: InitialisationValueType[]) {
104
+ return this.#arithmetics("add", ...args);
59
105
  }
60
- get baseValueNumber() {
61
- return this.#getBaseValue('number') as number;
106
+ sub(...args: InitialisationValueType[]) {
107
+ return this.#arithmetics("sub", ...args);
62
108
  }
63
- get baseValueBigInt() {
64
- return this.#getBaseValue('number') as bigint;
109
+ mul(...args: InitialisationValueType[]) {
110
+ return this.#arithmetics("mul", ...args);
65
111
  }
66
- get value() {
67
- return this.formatBigIntToSafeValue(
68
- this.bigIntValue,
69
- this.decimal || decimalFromMultiplier(this.decimalMultiplier),
70
- );
112
+ div(...args: InitialisationValueType[]) {
113
+ return this.#arithmetics("div", ...args);
71
114
  }
72
-
73
- add(...args: (BigIntArithmetics | string | number)[]) {
74
- return this.#arithmetics('add', ...args);
115
+ gt(value: InitialisationValueType) {
116
+ return this.#comparison("gt", value);
75
117
  }
76
- sub(...args: (BigIntArithmetics | string | number)[]) {
77
- return this.#arithmetics('sub', ...args);
118
+ gte(value: InitialisationValueType) {
119
+ return this.#comparison("gte", value);
78
120
  }
79
- mul(...args: (BigIntArithmetics | string | number)[]) {
80
- return this.#arithmetics('mul', ...args);
121
+ lt(value: InitialisationValueType) {
122
+ return this.#comparison("lt", value);
81
123
  }
82
- div(...args: (BigIntArithmetics | string | number)[]) {
83
- return this.#arithmetics('div', ...args);
124
+ lte(value: InitialisationValueType) {
125
+ return this.#comparison("lte", value);
84
126
  }
85
- gt(value: BigIntArithmetics | string | number) {
86
- return this.bigIntValue > this.getBigIntValue(value);
127
+ eqValue(value: InitialisationValueType) {
128
+ return this.#comparison("eqValue", value);
87
129
  }
88
- gte(value: BigIntArithmetics | string | number) {
89
- return this.bigIntValue >= this.getBigIntValue(value);
130
+
131
+ // @ts-expect-error False positive
132
+ getValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T] {
133
+ const value = this.formatBigIntToSafeValue(
134
+ this.bigIntValue,
135
+ this.decimal || decimalFromMultiplier(this.decimalMultiplier),
136
+ );
137
+
138
+ switch (type) {
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];
146
+ }
147
+ }
148
+
149
+ // @ts-expect-error
150
+ getBaseValue<T extends AllowedNumberTypes>(type: T): NumberPrimitivesType[T] {
151
+ const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);
152
+ const baseValue = this.bigIntValue / divisor;
153
+
154
+ switch (type) {
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];
161
+ }
162
+ }
163
+
164
+ getBigIntValue(value: InitialisationValueType, decimal?: number) {
165
+ if (!decimal && typeof value === "object") return value.bigIntValue;
166
+
167
+ const stringValue = getStringValue(value);
168
+ const safeValue = toSafeValue(stringValue);
169
+
170
+ if (safeValue === "0" || safeValue === "undefined") return 0n;
171
+ return this.#toBigInt(safeValue, decimal);
90
172
  }
91
- lt(value: BigIntArithmetics | string | number) {
92
- return this.bigIntValue < this.getBigIntValue(value);
173
+
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;
179
+
180
+ if (valueLength <= significantDigits) {
181
+ return this.getValue("string");
182
+ }
183
+
184
+ if (integer.length >= significantDigits) {
185
+ return integer.slice(0, significantDigits).padEnd(integer.length, "0");
186
+ }
187
+
188
+ if (Number.parseInt(integer)) {
189
+ return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(
190
+ significantDigits - integer.length,
191
+ "0",
192
+ );
193
+ }
194
+
195
+ const trimmedDecimal = Number.parseInt(decimal);
196
+ const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits);
197
+
198
+ return `0.${slicedDecimal.padStart(
199
+ decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length,
200
+ "0",
201
+ )}`;
93
202
  }
94
- lte(value: BigIntArithmetics | string | number) {
95
- return this.bigIntValue <= this.getBigIntValue(value);
203
+
204
+ toFixed(fixedDigits = 6) {
205
+ const [int, dec] = this.getValue("string").split(".");
206
+ const integer = int || "";
207
+ const decimal = dec || "";
208
+
209
+ if (Number.parseInt(integer)) {
210
+ return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, "0");
211
+ }
212
+
213
+ const trimmedDecimal = Number.parseInt(decimal);
214
+ const slicedDecimal = `${trimmedDecimal}`.slice(0, fixedDigits);
215
+
216
+ return `0.${slicedDecimal.padStart(
217
+ decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length,
218
+ "0",
219
+ )}`;
96
220
  }
97
- eqValue(value: BigIntArithmetics | string | number) {
98
- return this.bigIntValue === this.getBigIntValue(value);
221
+
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}`;
99
234
  }
100
235
 
101
- getBigIntValue(value: BigIntArithmetics | string | number, decimal?: number) {
102
- if (!decimal && typeof value === 'object') return value.bigIntValue;
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);
103
248
 
104
- value = typeof value === 'object' ? value.value : value;
105
- return this.#toBigInt(this.#toSafeValue(value), decimal);
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
+ }`;
106
259
  }
107
260
 
108
261
  formatBigIntToSafeValue(value: bigint, decimal?: number) {
@@ -113,147 +266,154 @@ export class BigIntArithmetics {
113
266
  );
114
267
  const isNegative = value < 0n;
115
268
 
116
- let valueString = value.toString().substring(isNegative ? 1 : 0);
117
-
269
+ const valueString = value.toString().substring(isNegative ? 1 : 0);
118
270
  const padLength = decimalToUseForConversion - (valueString.length - 1);
119
271
 
120
- if (padLength > 0) {
121
- valueString = '0'.repeat(padLength) + valueString;
122
- }
272
+ const parsedValueString = padLength > 0 ? "0".repeat(padLength) + valueString : valueString;
123
273
 
124
- const decimalIndex = valueString.length - decimalToUseForConversion;
125
- let decimalString = valueString.slice(-decimalToUseForConversion);
274
+ const decimalIndex = parsedValueString.length - decimalToUseForConversion;
275
+ let decimalString = parsedValueString.slice(-decimalToUseForConversion);
126
276
 
127
277
  // Check if we need to round up
128
- if (parseInt(decimalString[bigIntDecimal]) >= 5) {
278
+ if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
129
279
  // Increment the last decimal place and slice off the rest
130
280
  decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(
131
- parseInt(decimalString[bigIntDecimal - 1]) + 1
281
+ Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1
132
282
  ).toString()}`;
133
283
  } else {
134
284
  // Just slice off the extra digits
135
285
  decimalString = decimalString.substring(0, bigIntDecimal);
136
286
  }
137
287
 
138
- return `${isNegative ? '-' : ''}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(
139
- /\.?0*$/,
140
- '',
141
- );
288
+ return `${isNegative ? "-" : ""}${parsedValueString.slice(
289
+ 0,
290
+ decimalIndex,
291
+ )}.${decimalString}`.replace(/\.?0*$/, "");
142
292
  }
143
293
 
144
- toSignificant(significantDigits?: number) {
145
- const value = this.value.split('.');
146
- const integer = value[0];
147
- const decimal = value[1];
148
-
149
- if (decimal) {
150
- return `${integer}.${decimal.slice(0, significantDigits || this.decimal)}`.replace(
151
- /\.?0*$/,
152
- '',
153
- );
154
- }
155
-
156
- return integer;
157
- }
158
-
159
- #arithmetics(method: ArithmeticMethod, ...args: (BigIntArithmetics | string | number)[]): this {
294
+ #arithmetics(method: "add" | "sub" | "mul" | "div", ...args: InitialisationValueType[]): this {
160
295
  const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
161
- const precisionDecimalMultiplier = toMultiplier(precisionDecimal);
296
+ const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier));
297
+ const precisionDecimalMultiplier = toMultiplier(decimal);
162
298
 
163
299
  const result = args.reduce(
164
- (acc, arg) => {
165
- const value = this.getBigIntValue(arg, precisionDecimal);
166
-
167
- if ('div' === method && value === 0n) throw new RangeError('Division by zero');
168
-
169
- /**
170
- * Normal arithmetic - add & sub => 200000000n +- 200000000n
171
- */
172
- if ('add' === method) return acc + value;
173
- if ('sub' === method) return acc - value;
174
-
175
- /**
176
- * Multiplication & division would end up with wrong result if we don't adjust the value
177
- * 200000000n * 200000000n => 40000000000000000n
178
- * 200000000n / 200000000n => 1n
179
- * So we do the following:
180
- * 200000000n * 200000000n = 40000000000000000n / 100000000n (decimals) => 400000000n
181
- * (200000000n * 100000000n (decimals)) / 200000000n => 100000000n
182
- */
183
- if ('mul' === method) return (acc * value) / precisionDecimalMultiplier;
184
- // 'div' === method
185
- return (acc * precisionDecimalMultiplier) / value;
300
+ (acc: bigint, arg) => {
301
+ const value = this.getBigIntValue(arg, decimal);
302
+
303
+ switch (method) {
304
+ case "add":
305
+ return acc + value;
306
+ case "sub":
307
+ return acc - value;
308
+ /**
309
+ * Multiplication & division would end up with wrong result if we don't adjust the value
310
+ * 200000000n * 200000000n => 40000000000000000n
311
+ * 200000000n / 200000000n => 1n
312
+ * So we do the following:
313
+ * 200000000n * 200000000n = 40000000000000000n / 100000000n (decimals) => 400000000n
314
+ * (200000000n * 100000000n (decimals)) / 200000000n => 100000000n
315
+ */
316
+ case "mul":
317
+ return (acc * value) / precisionDecimalMultiplier;
318
+ case "div": {
319
+ if (value === 0n) throw new RangeError("Division by zero");
320
+ return (acc * precisionDecimalMultiplier) / value;
321
+ }
322
+ default:
323
+ return acc;
324
+ }
186
325
  },
187
326
  //normalize is to precision multiplier base
188
327
  (this.bigIntValue * precisionDecimalMultiplier) / this.decimalMultiplier,
189
328
  );
190
329
 
191
330
  const value = formatBigIntToSafeValue({
192
- bigIntDecimal: precisionDecimal,
193
- decimal: Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier)),
331
+ bigIntDecimal: decimal,
332
+ decimal,
194
333
  value: result,
195
334
  });
196
335
 
197
- // @ts-expect-error - we know that the constructor is the same as the current class
198
- return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
336
+ // @ts-expect-error False positive
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
+ }
199
362
  }
200
363
 
201
- #setValue(value: AllowedValueType, bigIntValue?: bigint) {
202
- const safeValue = this.#toSafeValue(value) || '0';
203
- this.bigIntValue = bigIntValue || this.#toBigInt(safeValue);
364
+ #setValue(value: InitialisationValueType) {
365
+ const safeValue = toSafeValue(value) || "0";
366
+ this.bigIntValue = this.#toBigInt(safeValue);
204
367
  }
205
368
 
206
- #retrievePrecisionDecimal(...args: (BigIntArithmetics | AllowedValueType)[]) {
369
+ #retrievePrecisionDecimal(...args: InitialisationValueType[]) {
207
370
  const decimals = args
208
- .map((arg) =>
209
- typeof arg === 'object'
371
+ .map((arg) => {
372
+ const isObject = typeof arg === "object";
373
+ const value = isObject
210
374
  ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier)
211
- : this.#getFloatDecimals(this.#toSafeValue(arg)),
212
- )
375
+ : getFloatDecimals(toSafeValue(arg));
376
+
377
+ return value;
378
+ })
213
379
  .filter(Boolean) as number[];
380
+
214
381
  return Math.max(...decimals, DEFAULT_DECIMAL);
215
382
  }
216
383
 
217
384
  #toBigInt(value: string, decimal?: number) {
218
385
  const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
219
386
  const padDecimal = decimalFromMultiplier(multiplier);
220
- const [integerPart, decimalPart = ''] = value.split('.');
387
+ const [integerPart = "", decimalPart = ""] = value.split(".");
221
388
 
222
- return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, '0')}`);
389
+ return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, "0")}`);
223
390
  }
391
+ }
224
392
 
225
- #toSafeValue(value: AllowedValueType) {
226
- const parsedValue =
227
- typeof value === 'number'
228
- ? Number(value).toLocaleString('fullwide', {
229
- useGrouping: false,
230
- maximumFractionDigits: 20,
231
- })
232
- : value;
233
-
234
- const splitValue = `${parsedValue}`.replaceAll(',', '.').split('.');
235
-
236
- return splitValue.length > 1
237
- ? `${splitValue.slice(0, -1).join('')}.${splitValue.at(-1)}`
238
- : splitValue[0];
239
- }
393
+ const numberFormatter = Intl.NumberFormat("fullwide", {
394
+ useGrouping: false,
395
+ maximumFractionDigits: 20,
396
+ });
240
397
 
241
- #getFloatDecimals(value: string) {
242
- const decimals = value.split('.')[1]?.length || 0;
243
- return Math.max(decimals, DEFAULT_DECIMAL);
244
- }
398
+ function toSafeValue(value: InitialisationValueType) {
399
+ const parsedValue =
400
+ typeof value === "number" ? numberFormatter.format(value) : getStringValue(value);
401
+ const splitValue = `${parsedValue}`.replaceAll(",", ".").split(".");
245
402
 
246
- #getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T) {
247
- const divisor = this.decimalMultiplier / toMultiplier(this.decimal || 0);
248
- const baseValue = this.bigIntValue / divisor;
403
+ return splitValue.length > 1
404
+ ? `${splitValue.slice(0, -1).join("")}.${splitValue.at(-1)}`
405
+ : splitValue[0] || "0";
406
+ }
249
407
 
250
- switch (type) {
251
- case 'number':
252
- return Number(baseValue);
253
- case 'string':
254
- return baseValue.toString();
255
- default:
256
- return baseValue;
257
- }
258
- }
408
+ function getFloatDecimals(value: string) {
409
+ const decimals = value.split(".")[1]?.length || 0;
410
+ return Math.max(decimals, DEFAULT_DECIMAL);
411
+ }
412
+
413
+ function getStringValue(param: SKBigIntParams) {
414
+ return typeof param === "object"
415
+ ? "getValue" in param
416
+ ? param.getValue("string")
417
+ : param.value
418
+ : param;
259
419
  }
@@ -0,0 +1,39 @@
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 = (kyClient: KyInstance) => ({
25
+ get: <T>(url: string | URL | Request, options?: Options) => kyClient.get(url, options).json<T>(),
26
+ post: <T>(url: string | URL | Request, options?: Options) =>
27
+ kyClient.post(url, options).json<T>(),
28
+ });
29
+
30
+ export const RequestClient = {
31
+ ...getTypedBaseRequestClient(getKyClient()),
32
+ extend: (options: Options) => {
33
+ const extendedClient = getKyClient().extend(options);
34
+ return {
35
+ ...getTypedBaseRequestClient(extendedClient),
36
+ extend: RequestClient.extend,
37
+ };
38
+ },
39
+ };
@@ -7,7 +7,11 @@ const errorMessages = {
7
7
  core_extend_error: 10003,
8
8
  core_inbound_data_not_found: 10004,
9
9
  core_approve_asset_address_or_from_not_found: 10005,
10
+ core_plugin_not_found: 10006,
11
+ core_plugin_swap_not_found: 10007,
12
+ core_approve_asset_target_invalid: 10008,
10
13
  core_chain_halted: 10099,
14
+
11
15
  /**
12
16
  * Core - Wallet Connection
13
17
  */
@@ -19,6 +23,7 @@ const errorMessages = {
19
23
  core_wallet_trezor_not_installed: 10106,
20
24
  core_wallet_keplr_not_installed: 10107,
21
25
  core_wallet_okx_not_installed: 10108,
26
+ core_wallet_keepkey_not_installed: 10109,
22
27
  /**
23
28
  * Core - Swap
24
29
  */
@@ -45,12 +50,28 @@ const errorMessages = {
45
50
  core_transaction_deposit_to_pool_error: 10310,
46
51
  core_transaction_deposit_insufficient_funds_error: 10311,
47
52
  core_transaction_deposit_gas_error: 10312,
48
- core_transaction_deposit_server_error: 10313,
53
+ core_transaction_invalid_sender_address: 10313,
54
+ core_transaction_deposit_server_error: 10314,
55
+ core_transaction_user_rejected: 10315,
49
56
 
50
57
  /**
51
58
  * Wallets
52
59
  */
53
60
  wallet_ledger_connection_error: 20001,
61
+ wallet_ledger_connection_claimed: 20002,
62
+ wallet_ledger_get_address_error: 20003,
63
+ wallet_ledger_device_not_found: 20004,
64
+ wallet_ledger_device_locked: 20005,
65
+
66
+ /**
67
+ * Chainflip
68
+ */
69
+ chainflip_channel_error: 30001,
70
+ chainflip_broker_recipient_error: 30002,
71
+
72
+ /**
73
+ * THORChain
74
+ */
54
75
 
55
76
  /**
56
77
  * Helpers
@@ -58,13 +79,20 @@ const errorMessages = {
58
79
  helpers_number_different_decimals: 99101,
59
80
  } as const;
60
81
 
61
- export type Keys = keyof typeof errorMessages;
82
+ export type ErrorKeys = keyof typeof errorMessages;
62
83
 
63
84
  export class SwapKitError extends Error {
64
- constructor(errorKey: Keys, sourceError?: any) {
65
- console.error(sourceError);
85
+ constructor(errorKey: ErrorKeys, sourceError?: NotWorth) {
86
+ if (sourceError) {
87
+ console.error(sourceError, {
88
+ stack: sourceError?.stack,
89
+ message: sourceError?.message,
90
+ });
91
+ }
66
92
 
67
- super(errorKey, { cause: { code: errorMessages[errorKey], message: errorKey } });
93
+ super(errorKey, {
94
+ cause: { code: errorMessages[errorKey], message: errorKey },
95
+ });
68
96
  Object.setPrototypeOf(this, SwapKitError.prototype);
69
97
  }
70
98
  }