@kaspacom/swap-sdk 1.1.2 → 1.1.3

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 DELETED
@@ -1,2029 +0,0 @@
1
- // src/types/index.ts
2
- var LoaderStatuses = /* @__PURE__ */ ((LoaderStatuses2) => {
3
- LoaderStatuses2[LoaderStatuses2["CALCULATING_QUOTE"] = 1] = "CALCULATING_QUOTE";
4
- LoaderStatuses2[LoaderStatuses2["APPROVING"] = 2] = "APPROVING";
5
- LoaderStatuses2[LoaderStatuses2["SWAPPING"] = 3] = "SWAPPING";
6
- return LoaderStatuses2;
7
- })(LoaderStatuses || {});
8
-
9
- // src/services/wallet.service.ts
10
- import { BrowserProvider, JsonRpcProvider } from "ethers";
11
- var WalletService = class {
12
- // injected provider (window.ethereum or similar)
13
- constructor(config, injectedProvider) {
14
- this.signer = null;
15
- this.address = null;
16
- this.config = config;
17
- this.networkProvider = new JsonRpcProvider(config.rpcUrl, {
18
- name: config.name,
19
- chainId: config.chainId
20
- }, config.additionalJsonRpcApiProviderOptionsOptions);
21
- if (injectedProvider) {
22
- this.connect(this.injectedProvider);
23
- }
24
- }
25
- async connect(injectedProvider) {
26
- if (injectedProvider) {
27
- this.injectedProvider = injectedProvider;
28
- this.walletProvider = new BrowserProvider(this.injectedProvider);
29
- }
30
- if (!this.injectedProvider || !this.walletProvider) {
31
- throw new Error("Please connect wallet.");
32
- }
33
- try {
34
- const accounts = await this.injectedProvider.request({
35
- method: "eth_requestAccounts"
36
- });
37
- if (accounts.length === 0) {
38
- throw new Error("No accounts found");
39
- }
40
- this.address = accounts[0];
41
- const chainId = await this.injectedProvider.request({
42
- method: "eth_chainId"
43
- });
44
- const currentChainId = parseInt(chainId, 16);
45
- if (currentChainId !== this.config.chainId) {
46
- try {
47
- await this.injectedProvider.request({
48
- method: "wallet_switchEthereumChain",
49
- params: [{ chainId: `0x${this.config.chainId.toString(16)}` }]
50
- });
51
- } catch (switchError) {
52
- if (switchError.code === 4902) {
53
- await this.injectedProvider.request({
54
- method: "wallet_addEthereumChain",
55
- params: [{
56
- chainId: `0x${this.config.chainId.toString(16)}`,
57
- chainName: this.config.name,
58
- nativeCurrency: {
59
- name: "ETH",
60
- symbol: "ETH",
61
- decimals: 18
62
- },
63
- rpcUrls: [this.config.rpcUrl],
64
- blockExplorerUrls: this.config.blockExplorerUrl ? [this.config.blockExplorerUrl] : []
65
- }]
66
- });
67
- await this.injectedProvider.request({
68
- method: "wallet_switchEthereumChain",
69
- params: [{ chainId: `0x${this.config.chainId.toString(16)}` }]
70
- });
71
- } else {
72
- throw new Error(`Please switch to ${this.config.name} network`);
73
- }
74
- }
75
- }
76
- this.signer = await this.walletProvider.getSigner();
77
- return this.address;
78
- } catch (error) {
79
- if (error.code === 4001) {
80
- throw new Error("User rejected wallet connection");
81
- }
82
- throw new Error(`Failed to connect wallet: ${error.message}`);
83
- }
84
- }
85
- disconnect() {
86
- this.address = null;
87
- this.signer = null;
88
- }
89
- isConnected() {
90
- return !!this.address && !!this.signer;
91
- }
92
- getAddress() {
93
- return this.address;
94
- }
95
- getProvider() {
96
- return this.walletProvider || this.networkProvider;
97
- }
98
- getSigner() {
99
- return this.signer;
100
- }
101
- // Helper method to get current chain ID
102
- async getCurrentChainId() {
103
- if (!this.injectedProvider) {
104
- throw new Error("No Ethereum wallet detected");
105
- }
106
- const chainId = await this.injectedProvider.request({
107
- method: "eth_chainId"
108
- });
109
- return parseInt(chainId, 16);
110
- }
111
- // Connect wallet and emit event with address
112
- async connectWallet() {
113
- if (this.injectedProvider) {
114
- try {
115
- const accounts = await this.injectedProvider.request({
116
- method: "eth_requestAccounts"
117
- });
118
- if (accounts.length > 0 && typeof accounts[0] === "string") {
119
- const address = accounts[0];
120
- this.address = address;
121
- return address;
122
- } else {
123
- throw new Error("No accounts found");
124
- }
125
- } catch (error) {
126
- console.error("Failed to connect wallet:", error);
127
- throw error;
128
- }
129
- } else {
130
- throw new Error("No Ethereum wallet detected. Please connect a wallet provider.");
131
- }
132
- }
133
- // Disconnect wallet and emit event
134
- disconnectWallet() {
135
- this.address = null;
136
- this.signer = null;
137
- }
138
- };
139
-
140
- // src/services/swap.service.ts
141
- import { Contract, parseUnits, formatUnits, ZeroAddress, ethers, hexlify } from "ethers";
142
- import { CurrencyAmount as CurrencyAmount2, Percent, Token as Token2, TradeType } from "@uniswap/sdk-core";
143
- import { Trade, Route } from "@uniswap/v2-sdk";
144
-
145
- // src/types/CustomFeePair.ts
146
- import { CurrencyAmount } from "@uniswap/sdk-core";
147
- import { Pair as UniPair } from "@uniswap/v2-sdk";
148
-
149
- // node_modules/jsbi/dist/jsbi.mjs
150
- var JSBI = class _JSBI extends Array {
151
- constructor(i, _) {
152
- if (super(i), this.sign = _, i > _JSBI.__kMaxLength) throw new RangeError("Maximum BigInt size exceeded");
153
- }
154
- static BigInt(i) {
155
- var _ = Math.floor, t = Number.isFinite;
156
- if ("number" == typeof i) {
157
- if (0 === i) return _JSBI.__zero();
158
- if (_JSBI.__isOneDigitInt(i)) return 0 > i ? _JSBI.__oneDigit(-i, true) : _JSBI.__oneDigit(i, false);
159
- if (!t(i) || _(i) !== i) throw new RangeError("The number " + i + " cannot be converted to BigInt because it is not an integer");
160
- return _JSBI.__fromDouble(i);
161
- }
162
- if ("string" == typeof i) {
163
- const _2 = _JSBI.__fromString(i);
164
- if (null === _2) throw new SyntaxError("Cannot convert " + i + " to a BigInt");
165
- return _2;
166
- }
167
- if ("boolean" == typeof i) return true === i ? _JSBI.__oneDigit(1, false) : _JSBI.__zero();
168
- if ("object" == typeof i) {
169
- if (i.constructor === _JSBI) return i;
170
- const _2 = _JSBI.__toPrimitive(i);
171
- return _JSBI.BigInt(_2);
172
- }
173
- throw new TypeError("Cannot convert " + i + " to a BigInt");
174
- }
175
- toDebugString() {
176
- const i = ["BigInt["];
177
- for (const _ of this) i.push((_ ? (_ >>> 0).toString(16) : _) + ", ");
178
- return i.push("]"), i.join("");
179
- }
180
- toString(i = 10) {
181
- if (2 > i || 36 < i) throw new RangeError("toString() radix argument must be between 2 and 36");
182
- return 0 === this.length ? "0" : 0 == (i & i - 1) ? _JSBI.__toStringBasePowerOfTwo(this, i) : _JSBI.__toStringGeneric(this, i, false);
183
- }
184
- static toNumber(i) {
185
- const _ = i.length;
186
- if (0 === _) return 0;
187
- if (1 === _) {
188
- const _2 = i.__unsignedDigit(0);
189
- return i.sign ? -_2 : _2;
190
- }
191
- const t = i.__digit(_ - 1), e = _JSBI.__clz30(t), n = 30 * _ - e;
192
- if (1024 < n) return i.sign ? -Infinity : 1 / 0;
193
- let g = n - 1, o = t, s = _ - 1;
194
- const l = e + 3;
195
- let r = 32 === l ? 0 : o << l;
196
- r >>>= 12;
197
- const a = l - 12;
198
- let u = 12 <= l ? 0 : o << 20 + l, d = 20 + l;
199
- for (0 < a && 0 < s && (s--, o = i.__digit(s), r |= o >>> 30 - a, u = o << a + 2, d = a + 2); 0 < d && 0 < s; ) s--, o = i.__digit(s), u |= 30 <= d ? o << d - 30 : o >>> 30 - d, d -= 30;
200
- const h = _JSBI.__decideRounding(i, d, s, o);
201
- if ((1 === h || 0 === h && 1 == (1 & u)) && (u = u + 1 >>> 0, 0 === u && (r++, 0 != r >>> 20 && (r = 0, g++, 1023 < g)))) return i.sign ? -Infinity : 1 / 0;
202
- const m = i.sign ? -2147483648 : 0;
203
- return g = g + 1023 << 20, _JSBI.__kBitConversionInts[1] = m | g | r, _JSBI.__kBitConversionInts[0] = u, _JSBI.__kBitConversionDouble[0];
204
- }
205
- static unaryMinus(i) {
206
- if (0 === i.length) return i;
207
- const _ = i.__copy();
208
- return _.sign = !i.sign, _;
209
- }
210
- static bitwiseNot(i) {
211
- return i.sign ? _JSBI.__absoluteSubOne(i).__trim() : _JSBI.__absoluteAddOne(i, true);
212
- }
213
- static exponentiate(i, _) {
214
- if (_.sign) throw new RangeError("Exponent must be positive");
215
- if (0 === _.length) return _JSBI.__oneDigit(1, false);
216
- if (0 === i.length) return i;
217
- if (1 === i.length && 1 === i.__digit(0)) return i.sign && 0 == (1 & _.__digit(0)) ? _JSBI.unaryMinus(i) : i;
218
- if (1 < _.length) throw new RangeError("BigInt too big");
219
- let t = _.__unsignedDigit(0);
220
- if (1 === t) return i;
221
- if (t >= _JSBI.__kMaxLengthBits) throw new RangeError("BigInt too big");
222
- if (1 === i.length && 2 === i.__digit(0)) {
223
- const _2 = 1 + (0 | t / 30), e2 = i.sign && 0 != (1 & t), n2 = new _JSBI(_2, e2);
224
- n2.__initializeDigits();
225
- const g = 1 << t % 30;
226
- return n2.__setDigit(_2 - 1, g), n2;
227
- }
228
- let e = null, n = i;
229
- for (0 != (1 & t) && (e = i), t >>= 1; 0 !== t; t >>= 1) n = _JSBI.multiply(n, n), 0 != (1 & t) && (null === e ? e = n : e = _JSBI.multiply(e, n));
230
- return e;
231
- }
232
- static multiply(_, t) {
233
- if (0 === _.length) return _;
234
- if (0 === t.length) return t;
235
- let i = _.length + t.length;
236
- 30 <= _.__clzmsd() + t.__clzmsd() && i--;
237
- const e = new _JSBI(i, _.sign !== t.sign);
238
- e.__initializeDigits();
239
- for (let n = 0; n < _.length; n++) _JSBI.__multiplyAccumulate(t, _.__digit(n), e, n);
240
- return e.__trim();
241
- }
242
- static divide(i, _) {
243
- if (0 === _.length) throw new RangeError("Division by zero");
244
- if (0 > _JSBI.__absoluteCompare(i, _)) return _JSBI.__zero();
245
- const t = i.sign !== _.sign, e = _.__unsignedDigit(0);
246
- let n;
247
- if (1 === _.length && 32767 >= e) {
248
- if (1 === e) return t === i.sign ? i : _JSBI.unaryMinus(i);
249
- n = _JSBI.__absoluteDivSmall(i, e, null);
250
- } else n = _JSBI.__absoluteDivLarge(i, _, true, false);
251
- return n.sign = t, n.__trim();
252
- }
253
- static remainder(i, _) {
254
- if (0 === _.length) throw new RangeError("Division by zero");
255
- if (0 > _JSBI.__absoluteCompare(i, _)) return i;
256
- const t = _.__unsignedDigit(0);
257
- if (1 === _.length && 32767 >= t) {
258
- if (1 === t) return _JSBI.__zero();
259
- const _2 = _JSBI.__absoluteModSmall(i, t);
260
- return 0 === _2 ? _JSBI.__zero() : _JSBI.__oneDigit(_2, i.sign);
261
- }
262
- const e = _JSBI.__absoluteDivLarge(i, _, false, true);
263
- return e.sign = i.sign, e.__trim();
264
- }
265
- static add(i, _) {
266
- const t = i.sign;
267
- return t === _.sign ? _JSBI.__absoluteAdd(i, _, t) : 0 <= _JSBI.__absoluteCompare(i, _) ? _JSBI.__absoluteSub(i, _, t) : _JSBI.__absoluteSub(_, i, !t);
268
- }
269
- static subtract(i, _) {
270
- const t = i.sign;
271
- return t === _.sign ? 0 <= _JSBI.__absoluteCompare(i, _) ? _JSBI.__absoluteSub(i, _, t) : _JSBI.__absoluteSub(_, i, !t) : _JSBI.__absoluteAdd(i, _, t);
272
- }
273
- static leftShift(i, _) {
274
- return 0 === _.length || 0 === i.length ? i : _.sign ? _JSBI.__rightShiftByAbsolute(i, _) : _JSBI.__leftShiftByAbsolute(i, _);
275
- }
276
- static signedRightShift(i, _) {
277
- return 0 === _.length || 0 === i.length ? i : _.sign ? _JSBI.__leftShiftByAbsolute(i, _) : _JSBI.__rightShiftByAbsolute(i, _);
278
- }
279
- static unsignedRightShift() {
280
- throw new TypeError("BigInts have no unsigned right shift; use >> instead");
281
- }
282
- static lessThan(i, _) {
283
- return 0 > _JSBI.__compareToBigInt(i, _);
284
- }
285
- static lessThanOrEqual(i, _) {
286
- return 0 >= _JSBI.__compareToBigInt(i, _);
287
- }
288
- static greaterThan(i, _) {
289
- return 0 < _JSBI.__compareToBigInt(i, _);
290
- }
291
- static greaterThanOrEqual(i, _) {
292
- return 0 <= _JSBI.__compareToBigInt(i, _);
293
- }
294
- static equal(_, t) {
295
- if (_.sign !== t.sign) return false;
296
- if (_.length !== t.length) return false;
297
- for (let e = 0; e < _.length; e++) if (_.__digit(e) !== t.__digit(e)) return false;
298
- return true;
299
- }
300
- static notEqual(i, _) {
301
- return !_JSBI.equal(i, _);
302
- }
303
- static bitwiseAnd(i, _) {
304
- var t = Math.max;
305
- if (!i.sign && !_.sign) return _JSBI.__absoluteAnd(i, _).__trim();
306
- if (i.sign && _.sign) {
307
- const e = t(i.length, _.length) + 1;
308
- let n = _JSBI.__absoluteSubOne(i, e);
309
- const g = _JSBI.__absoluteSubOne(_);
310
- return n = _JSBI.__absoluteOr(n, g, n), _JSBI.__absoluteAddOne(n, true, n).__trim();
311
- }
312
- return i.sign && ([i, _] = [_, i]), _JSBI.__absoluteAndNot(i, _JSBI.__absoluteSubOne(_)).__trim();
313
- }
314
- static bitwiseXor(i, _) {
315
- var t = Math.max;
316
- if (!i.sign && !_.sign) return _JSBI.__absoluteXor(i, _).__trim();
317
- if (i.sign && _.sign) {
318
- const e2 = t(i.length, _.length), n2 = _JSBI.__absoluteSubOne(i, e2), g = _JSBI.__absoluteSubOne(_);
319
- return _JSBI.__absoluteXor(n2, g, n2).__trim();
320
- }
321
- const e = t(i.length, _.length) + 1;
322
- i.sign && ([i, _] = [_, i]);
323
- let n = _JSBI.__absoluteSubOne(_, e);
324
- return n = _JSBI.__absoluteXor(n, i, n), _JSBI.__absoluteAddOne(n, true, n).__trim();
325
- }
326
- static bitwiseOr(i, _) {
327
- var t = Math.max;
328
- const e = t(i.length, _.length);
329
- if (!i.sign && !_.sign) return _JSBI.__absoluteOr(i, _).__trim();
330
- if (i.sign && _.sign) {
331
- let t2 = _JSBI.__absoluteSubOne(i, e);
332
- const n2 = _JSBI.__absoluteSubOne(_);
333
- return t2 = _JSBI.__absoluteAnd(t2, n2, t2), _JSBI.__absoluteAddOne(t2, true, t2).__trim();
334
- }
335
- i.sign && ([i, _] = [_, i]);
336
- let n = _JSBI.__absoluteSubOne(_, e);
337
- return n = _JSBI.__absoluteAndNot(n, i, n), _JSBI.__absoluteAddOne(n, true, n).__trim();
338
- }
339
- static asIntN(_, t) {
340
- var i = Math.floor;
341
- if (0 === t.length) return t;
342
- if (_ = i(_), 0 > _) throw new RangeError("Invalid value: not (convertible to) a safe integer");
343
- if (0 === _) return _JSBI.__zero();
344
- if (_ >= _JSBI.__kMaxLengthBits) return t;
345
- const e = 0 | (_ + 29) / 30;
346
- if (t.length < e) return t;
347
- const g = t.__unsignedDigit(e - 1), o = 1 << (_ - 1) % 30;
348
- if (t.length === e && g < o) return t;
349
- if (!((g & o) === o)) return _JSBI.__truncateToNBits(_, t);
350
- if (!t.sign) return _JSBI.__truncateAndSubFromPowerOfTwo(_, t, true);
351
- if (0 == (g & o - 1)) {
352
- for (let n = e - 2; 0 <= n; n--) if (0 !== t.__digit(n)) return _JSBI.__truncateAndSubFromPowerOfTwo(_, t, false);
353
- return t.length === e && g === o ? t : _JSBI.__truncateToNBits(_, t);
354
- }
355
- return _JSBI.__truncateAndSubFromPowerOfTwo(_, t, false);
356
- }
357
- static asUintN(i, _) {
358
- var t = Math.floor;
359
- if (0 === _.length) return _;
360
- if (i = t(i), 0 > i) throw new RangeError("Invalid value: not (convertible to) a safe integer");
361
- if (0 === i) return _JSBI.__zero();
362
- if (_.sign) {
363
- if (i > _JSBI.__kMaxLengthBits) throw new RangeError("BigInt too big");
364
- return _JSBI.__truncateAndSubFromPowerOfTwo(i, _, false);
365
- }
366
- if (i >= _JSBI.__kMaxLengthBits) return _;
367
- const e = 0 | (i + 29) / 30;
368
- if (_.length < e) return _;
369
- const g = i % 30;
370
- if (_.length == e) {
371
- if (0 === g) return _;
372
- const i2 = _.__digit(e - 1);
373
- if (0 == i2 >>> g) return _;
374
- }
375
- return _JSBI.__truncateToNBits(i, _);
376
- }
377
- static ADD(i, _) {
378
- if (i = _JSBI.__toPrimitive(i), _ = _JSBI.__toPrimitive(_), "string" == typeof i) return "string" != typeof _ && (_ = _.toString()), i + _;
379
- if ("string" == typeof _) return i.toString() + _;
380
- if (i = _JSBI.__toNumeric(i), _ = _JSBI.__toNumeric(_), _JSBI.__isBigInt(i) && _JSBI.__isBigInt(_)) return _JSBI.add(i, _);
381
- if ("number" == typeof i && "number" == typeof _) return i + _;
382
- throw new TypeError("Cannot mix BigInt and other types, use explicit conversions");
383
- }
384
- static LT(i, _) {
385
- return _JSBI.__compare(i, _, 0);
386
- }
387
- static LE(i, _) {
388
- return _JSBI.__compare(i, _, 1);
389
- }
390
- static GT(i, _) {
391
- return _JSBI.__compare(i, _, 2);
392
- }
393
- static GE(i, _) {
394
- return _JSBI.__compare(i, _, 3);
395
- }
396
- static EQ(i, _) {
397
- for (; ; ) {
398
- if (_JSBI.__isBigInt(i)) return _JSBI.__isBigInt(_) ? _JSBI.equal(i, _) : _JSBI.EQ(_, i);
399
- if ("number" == typeof i) {
400
- if (_JSBI.__isBigInt(_)) return _JSBI.__equalToNumber(_, i);
401
- if ("object" != typeof _) return i == _;
402
- _ = _JSBI.__toPrimitive(_);
403
- } else if ("string" == typeof i) {
404
- if (_JSBI.__isBigInt(_)) return i = _JSBI.__fromString(i), null !== i && _JSBI.equal(i, _);
405
- if ("object" != typeof _) return i == _;
406
- _ = _JSBI.__toPrimitive(_);
407
- } else if ("boolean" == typeof i) {
408
- if (_JSBI.__isBigInt(_)) return _JSBI.__equalToNumber(_, +i);
409
- if ("object" != typeof _) return i == _;
410
- _ = _JSBI.__toPrimitive(_);
411
- } else if ("symbol" == typeof i) {
412
- if (_JSBI.__isBigInt(_)) return false;
413
- if ("object" != typeof _) return i == _;
414
- _ = _JSBI.__toPrimitive(_);
415
- } else if ("object" == typeof i) {
416
- if ("object" == typeof _ && _.constructor !== _JSBI) return i == _;
417
- i = _JSBI.__toPrimitive(i);
418
- } else return i == _;
419
- }
420
- }
421
- static NE(i, _) {
422
- return !_JSBI.EQ(i, _);
423
- }
424
- static __zero() {
425
- return new _JSBI(0, false);
426
- }
427
- static __oneDigit(i, _) {
428
- const t = new _JSBI(1, _);
429
- return t.__setDigit(0, i), t;
430
- }
431
- __copy() {
432
- const _ = new _JSBI(this.length, this.sign);
433
- for (let t = 0; t < this.length; t++) _[t] = this[t];
434
- return _;
435
- }
436
- __trim() {
437
- let i = this.length, _ = this[i - 1];
438
- for (; 0 === _; ) i--, _ = this[i - 1], this.pop();
439
- return 0 === i && (this.sign = false), this;
440
- }
441
- __initializeDigits() {
442
- for (let _ = 0; _ < this.length; _++) this[_] = 0;
443
- }
444
- static __decideRounding(i, _, t, e) {
445
- if (0 < _) return -1;
446
- let n;
447
- if (0 > _) n = -_ - 1;
448
- else {
449
- if (0 === t) return -1;
450
- t--, e = i.__digit(t), n = 29;
451
- }
452
- let g = 1 << n;
453
- if (0 == (e & g)) return -1;
454
- if (g -= 1, 0 != (e & g)) return 1;
455
- for (; 0 < t; ) if (t--, 0 !== i.__digit(t)) return 1;
456
- return 0;
457
- }
458
- static __fromDouble(i) {
459
- _JSBI.__kBitConversionDouble[0] = i;
460
- const _ = 2047 & _JSBI.__kBitConversionInts[1] >>> 20, t = _ - 1023, e = (0 | t / 30) + 1, n = new _JSBI(e, 0 > i);
461
- let g = 1048575 & _JSBI.__kBitConversionInts[1] | 1048576, o = _JSBI.__kBitConversionInts[0];
462
- const s = 20, l = t % 30;
463
- let r, a = 0;
464
- if (l < 20) {
465
- const i2 = s - l;
466
- a = i2 + 32, r = g >>> i2, g = g << 32 - i2 | o >>> i2, o <<= 32 - i2;
467
- } else if (l === 20) a = 32, r = g, g = o, o = 0;
468
- else {
469
- const i2 = l - s;
470
- a = 32 - i2, r = g << i2 | o >>> 32 - i2, g = o << i2, o = 0;
471
- }
472
- n.__setDigit(e - 1, r);
473
- for (let _2 = e - 2; 0 <= _2; _2--) 0 < a ? (a -= 30, r = g >>> 2, g = g << 30 | o >>> 2, o <<= 30) : r = 0, n.__setDigit(_2, r);
474
- return n.__trim();
475
- }
476
- static __isWhitespace(i) {
477
- return !!(13 >= i && 9 <= i) || (159 >= i ? 32 == i : 131071 >= i ? 160 == i || 5760 == i : 196607 >= i ? (i &= 131071, 10 >= i || 40 == i || 41 == i || 47 == i || 95 == i || 4096 == i) : 65279 == i);
478
- }
479
- static __fromString(i, _ = 0) {
480
- let t = 0;
481
- const e = i.length;
482
- let n = 0;
483
- if (n === e) return _JSBI.__zero();
484
- let g = i.charCodeAt(n);
485
- for (; _JSBI.__isWhitespace(g); ) {
486
- if (++n === e) return _JSBI.__zero();
487
- g = i.charCodeAt(n);
488
- }
489
- if (43 === g) {
490
- if (++n === e) return null;
491
- g = i.charCodeAt(n), t = 1;
492
- } else if (45 === g) {
493
- if (++n === e) return null;
494
- g = i.charCodeAt(n), t = -1;
495
- }
496
- if (0 === _) {
497
- if (_ = 10, 48 === g) {
498
- if (++n === e) return _JSBI.__zero();
499
- if (g = i.charCodeAt(n), 88 === g || 120 === g) {
500
- if (_ = 16, ++n === e) return null;
501
- g = i.charCodeAt(n);
502
- } else if (79 === g || 111 === g) {
503
- if (_ = 8, ++n === e) return null;
504
- g = i.charCodeAt(n);
505
- } else if (66 === g || 98 === g) {
506
- if (_ = 2, ++n === e) return null;
507
- g = i.charCodeAt(n);
508
- }
509
- }
510
- } else if (16 === _ && 48 === g) {
511
- if (++n === e) return _JSBI.__zero();
512
- if (g = i.charCodeAt(n), 88 === g || 120 === g) {
513
- if (++n === e) return null;
514
- g = i.charCodeAt(n);
515
- }
516
- }
517
- if (0 != t && 10 !== _) return null;
518
- for (; 48 === g; ) {
519
- if (++n === e) return _JSBI.__zero();
520
- g = i.charCodeAt(n);
521
- }
522
- const o = e - n;
523
- let s = _JSBI.__kMaxBitsPerChar[_], l = _JSBI.__kBitsPerCharTableMultiplier - 1;
524
- if (o > 1073741824 / s) return null;
525
- const r = s * o + l >>> _JSBI.__kBitsPerCharTableShift, a = new _JSBI(0 | (r + 29) / 30, false), u = 10 > _ ? _ : 10, h = 10 < _ ? _ - 10 : 0;
526
- if (0 == (_ & _ - 1)) {
527
- s >>= _JSBI.__kBitsPerCharTableShift;
528
- const _2 = [], t2 = [];
529
- let o2 = false;
530
- do {
531
- let l2 = 0, r2 = 0;
532
- for (; ; ) {
533
- let _3;
534
- if (g - 48 >>> 0 < u) _3 = g - 48;
535
- else if ((32 | g) - 97 >>> 0 < h) _3 = (32 | g) - 87;
536
- else {
537
- o2 = true;
538
- break;
539
- }
540
- if (r2 += s, l2 = l2 << s | _3, ++n === e) {
541
- o2 = true;
542
- break;
543
- }
544
- if (g = i.charCodeAt(n), 30 < r2 + s) break;
545
- }
546
- _2.push(l2), t2.push(r2);
547
- } while (!o2);
548
- _JSBI.__fillFromParts(a, _2, t2);
549
- } else {
550
- a.__initializeDigits();
551
- let t2 = false, o2 = 0;
552
- do {
553
- let r2 = 0, b = 1;
554
- for (; ; ) {
555
- let s2;
556
- if (g - 48 >>> 0 < u) s2 = g - 48;
557
- else if ((32 | g) - 97 >>> 0 < h) s2 = (32 | g) - 87;
558
- else {
559
- t2 = true;
560
- break;
561
- }
562
- const l2 = b * _;
563
- if (1073741823 < l2) break;
564
- if (b = l2, r2 = r2 * _ + s2, o2++, ++n === e) {
565
- t2 = true;
566
- break;
567
- }
568
- g = i.charCodeAt(n);
569
- }
570
- l = 30 * _JSBI.__kBitsPerCharTableMultiplier - 1;
571
- const D = 0 | (s * o2 + l >>> _JSBI.__kBitsPerCharTableShift) / 30;
572
- a.__inplaceMultiplyAdd(b, r2, D);
573
- } while (!t2);
574
- }
575
- if (n !== e) {
576
- if (!_JSBI.__isWhitespace(g)) return null;
577
- for (n++; n < e; n++) if (g = i.charCodeAt(n), !_JSBI.__isWhitespace(g)) return null;
578
- }
579
- return a.sign = -1 == t, a.__trim();
580
- }
581
- static __fillFromParts(_, t, e) {
582
- let n = 0, g = 0, o = 0;
583
- for (let s = t.length - 1; 0 <= s; s--) {
584
- const i = t[s], l = e[s];
585
- g |= i << o, o += l, 30 === o ? (_.__setDigit(n++, g), o = 0, g = 0) : 30 < o && (_.__setDigit(n++, 1073741823 & g), o -= 30, g = i >>> l - o);
586
- }
587
- if (0 !== g) {
588
- if (n >= _.length) throw new Error("implementation bug");
589
- _.__setDigit(n++, g);
590
- }
591
- for (; n < _.length; n++) _.__setDigit(n, 0);
592
- }
593
- static __toStringBasePowerOfTwo(_, i) {
594
- const t = _.length;
595
- let e = i - 1;
596
- e = (85 & e >>> 1) + (85 & e), e = (51 & e >>> 2) + (51 & e), e = (15 & e >>> 4) + (15 & e);
597
- const n = e, g = i - 1, o = _.__digit(t - 1), s = _JSBI.__clz30(o);
598
- let l = 0 | (30 * t - s + n - 1) / n;
599
- if (_.sign && l++, 268435456 < l) throw new Error("string too long");
600
- const r = Array(l);
601
- let a = l - 1, u = 0, d = 0;
602
- for (let e2 = 0; e2 < t - 1; e2++) {
603
- const i2 = _.__digit(e2), t2 = (u | i2 << d) & g;
604
- r[a--] = _JSBI.__kConversionChars[t2];
605
- const o2 = n - d;
606
- for (u = i2 >>> o2, d = 30 - o2; d >= n; ) r[a--] = _JSBI.__kConversionChars[u & g], u >>>= n, d -= n;
607
- }
608
- const h = (u | o << d) & g;
609
- for (r[a--] = _JSBI.__kConversionChars[h], u = o >>> n - d; 0 !== u; ) r[a--] = _JSBI.__kConversionChars[u & g], u >>>= n;
610
- if (_.sign && (r[a--] = "-"), -1 != a) throw new Error("implementation bug");
611
- return r.join("");
612
- }
613
- static __toStringGeneric(_, i, t) {
614
- const e = _.length;
615
- if (0 === e) return "";
616
- if (1 === e) {
617
- let e2 = _.__unsignedDigit(0).toString(i);
618
- return false === t && _.sign && (e2 = "-" + e2), e2;
619
- }
620
- const n = 30 * e - _JSBI.__clz30(_.__digit(e - 1)), g = _JSBI.__kMaxBitsPerChar[i], o = g - 1;
621
- let s = n * _JSBI.__kBitsPerCharTableMultiplier;
622
- s += o - 1, s = 0 | s / o;
623
- const l = s + 1 >> 1, r = _JSBI.exponentiate(_JSBI.__oneDigit(i, false), _JSBI.__oneDigit(l, false));
624
- let a, u;
625
- const d = r.__unsignedDigit(0);
626
- if (1 === r.length && 32767 >= d) {
627
- a = new _JSBI(_.length, false), a.__initializeDigits();
628
- let t2 = 0;
629
- for (let e2 = 2 * _.length - 1; 0 <= e2; e2--) {
630
- const i2 = t2 << 15 | _.__halfDigit(e2);
631
- a.__setHalfDigit(e2, 0 | i2 / d), t2 = 0 | i2 % d;
632
- }
633
- u = t2.toString(i);
634
- } else {
635
- const t2 = _JSBI.__absoluteDivLarge(_, r, true, true);
636
- a = t2.quotient;
637
- const e2 = t2.remainder.__trim();
638
- u = _JSBI.__toStringGeneric(e2, i, true);
639
- }
640
- a.__trim();
641
- let h = _JSBI.__toStringGeneric(a, i, true);
642
- for (; u.length < l; ) u = "0" + u;
643
- return false === t && _.sign && (h = "-" + h), h + u;
644
- }
645
- static __unequalSign(i) {
646
- return i ? -1 : 1;
647
- }
648
- static __absoluteGreater(i) {
649
- return i ? -1 : 1;
650
- }
651
- static __absoluteLess(i) {
652
- return i ? 1 : -1;
653
- }
654
- static __compareToBigInt(i, _) {
655
- const t = i.sign;
656
- if (t !== _.sign) return _JSBI.__unequalSign(t);
657
- const e = _JSBI.__absoluteCompare(i, _);
658
- return 0 < e ? _JSBI.__absoluteGreater(t) : 0 > e ? _JSBI.__absoluteLess(t) : 0;
659
- }
660
- static __compareToNumber(i, _) {
661
- if (_JSBI.__isOneDigitInt(_)) {
662
- const t = i.sign, e = 0 > _;
663
- if (t !== e) return _JSBI.__unequalSign(t);
664
- if (0 === i.length) {
665
- if (e) throw new Error("implementation bug");
666
- return 0 === _ ? 0 : -1;
667
- }
668
- if (1 < i.length) return _JSBI.__absoluteGreater(t);
669
- const n = Math.abs(_), g = i.__unsignedDigit(0);
670
- return g > n ? _JSBI.__absoluteGreater(t) : g < n ? _JSBI.__absoluteLess(t) : 0;
671
- }
672
- return _JSBI.__compareToDouble(i, _);
673
- }
674
- static __compareToDouble(i, _) {
675
- if (_ !== _) return _;
676
- if (_ === 1 / 0) return -1;
677
- if (_ === -Infinity) return 1;
678
- const t = i.sign;
679
- if (t !== 0 > _) return _JSBI.__unequalSign(t);
680
- if (0 === _) throw new Error("implementation bug: should be handled elsewhere");
681
- if (0 === i.length) return -1;
682
- _JSBI.__kBitConversionDouble[0] = _;
683
- const e = 2047 & _JSBI.__kBitConversionInts[1] >>> 20;
684
- if (2047 == e) throw new Error("implementation bug: handled elsewhere");
685
- const n = e - 1023;
686
- if (0 > n) return _JSBI.__absoluteGreater(t);
687
- const g = i.length;
688
- let o = i.__digit(g - 1);
689
- const s = _JSBI.__clz30(o), l = 30 * g - s, r = n + 1;
690
- if (l < r) return _JSBI.__absoluteLess(t);
691
- if (l > r) return _JSBI.__absoluteGreater(t);
692
- let a = 1048576 | 1048575 & _JSBI.__kBitConversionInts[1], u = _JSBI.__kBitConversionInts[0];
693
- const d = 20, h = 29 - s;
694
- if (h !== (0 | (l - 1) % 30)) throw new Error("implementation bug");
695
- let m, b = 0;
696
- if (20 > h) {
697
- const i2 = d - h;
698
- b = i2 + 32, m = a >>> i2, a = a << 32 - i2 | u >>> i2, u <<= 32 - i2;
699
- } else if (20 === h) b = 32, m = a, a = u, u = 0;
700
- else {
701
- const i2 = h - d;
702
- b = 32 - i2, m = a << i2 | u >>> 32 - i2, a = u << i2, u = 0;
703
- }
704
- if (o >>>= 0, m >>>= 0, o > m) return _JSBI.__absoluteGreater(t);
705
- if (o < m) return _JSBI.__absoluteLess(t);
706
- for (let e2 = g - 2; 0 <= e2; e2--) {
707
- 0 < b ? (b -= 30, m = a >>> 2, a = a << 30 | u >>> 2, u <<= 30) : m = 0;
708
- const _2 = i.__unsignedDigit(e2);
709
- if (_2 > m) return _JSBI.__absoluteGreater(t);
710
- if (_2 < m) return _JSBI.__absoluteLess(t);
711
- }
712
- if (0 !== a || 0 !== u) {
713
- if (0 === b) throw new Error("implementation bug");
714
- return _JSBI.__absoluteLess(t);
715
- }
716
- return 0;
717
- }
718
- static __equalToNumber(i, _) {
719
- var t = Math.abs;
720
- return _JSBI.__isOneDigitInt(_) ? 0 === _ ? 0 === i.length : 1 === i.length && i.sign === 0 > _ && i.__unsignedDigit(0) === t(_) : 0 === _JSBI.__compareToDouble(i, _);
721
- }
722
- static __comparisonResultToBool(i, _) {
723
- return 0 === _ ? 0 > i : 1 === _ ? 0 >= i : 2 === _ ? 0 < i : 3 === _ ? 0 <= i : void 0;
724
- }
725
- static __compare(i, _, t) {
726
- if (i = _JSBI.__toPrimitive(i), _ = _JSBI.__toPrimitive(_), "string" == typeof i && "string" == typeof _) switch (t) {
727
- case 0:
728
- return i < _;
729
- case 1:
730
- return i <= _;
731
- case 2:
732
- return i > _;
733
- case 3:
734
- return i >= _;
735
- }
736
- if (_JSBI.__isBigInt(i) && "string" == typeof _) return _ = _JSBI.__fromString(_), null !== _ && _JSBI.__comparisonResultToBool(_JSBI.__compareToBigInt(i, _), t);
737
- if ("string" == typeof i && _JSBI.__isBigInt(_)) return i = _JSBI.__fromString(i), null !== i && _JSBI.__comparisonResultToBool(_JSBI.__compareToBigInt(i, _), t);
738
- if (i = _JSBI.__toNumeric(i), _ = _JSBI.__toNumeric(_), _JSBI.__isBigInt(i)) {
739
- if (_JSBI.__isBigInt(_)) return _JSBI.__comparisonResultToBool(_JSBI.__compareToBigInt(i, _), t);
740
- if ("number" != typeof _) throw new Error("implementation bug");
741
- return _JSBI.__comparisonResultToBool(_JSBI.__compareToNumber(i, _), t);
742
- }
743
- if ("number" != typeof i) throw new Error("implementation bug");
744
- if (_JSBI.__isBigInt(_)) return _JSBI.__comparisonResultToBool(_JSBI.__compareToNumber(_, i), 2 ^ t);
745
- if ("number" != typeof _) throw new Error("implementation bug");
746
- return 0 === t ? i < _ : 1 === t ? i <= _ : 2 === t ? i > _ : 3 === t ? i >= _ : void 0;
747
- }
748
- __clzmsd() {
749
- return _JSBI.__clz30(this.__digit(this.length - 1));
750
- }
751
- static __absoluteAdd(_, t, e) {
752
- if (_.length < t.length) return _JSBI.__absoluteAdd(t, _, e);
753
- if (0 === _.length) return _;
754
- if (0 === t.length) return _.sign === e ? _ : _JSBI.unaryMinus(_);
755
- let n = _.length;
756
- (0 === _.__clzmsd() || t.length === _.length && 0 === t.__clzmsd()) && n++;
757
- const g = new _JSBI(n, e);
758
- let o = 0, s = 0;
759
- for (; s < t.length; s++) {
760
- const i = _.__digit(s) + t.__digit(s) + o;
761
- o = i >>> 30, g.__setDigit(s, 1073741823 & i);
762
- }
763
- for (; s < _.length; s++) {
764
- const i = _.__digit(s) + o;
765
- o = i >>> 30, g.__setDigit(s, 1073741823 & i);
766
- }
767
- return s < g.length && g.__setDigit(s, o), g.__trim();
768
- }
769
- static __absoluteSub(_, t, e) {
770
- if (0 === _.length) return _;
771
- if (0 === t.length) return _.sign === e ? _ : _JSBI.unaryMinus(_);
772
- const n = new _JSBI(_.length, e);
773
- let g = 0, o = 0;
774
- for (; o < t.length; o++) {
775
- const i = _.__digit(o) - t.__digit(o) - g;
776
- g = 1 & i >>> 30, n.__setDigit(o, 1073741823 & i);
777
- }
778
- for (; o < _.length; o++) {
779
- const i = _.__digit(o) - g;
780
- g = 1 & i >>> 30, n.__setDigit(o, 1073741823 & i);
781
- }
782
- return n.__trim();
783
- }
784
- static __absoluteAddOne(_, i, t = null) {
785
- const e = _.length;
786
- null === t ? t = new _JSBI(e, i) : t.sign = i;
787
- let n = 1;
788
- for (let g = 0; g < e; g++) {
789
- const i2 = _.__digit(g) + n;
790
- n = i2 >>> 30, t.__setDigit(g, 1073741823 & i2);
791
- }
792
- return 0 != n && t.__setDigitGrow(e, 1), t;
793
- }
794
- static __absoluteSubOne(_, t) {
795
- const e = _.length;
796
- t = t || e;
797
- const n = new _JSBI(t, false);
798
- let g = 1;
799
- for (let o = 0; o < e; o++) {
800
- const i = _.__digit(o) - g;
801
- g = 1 & i >>> 30, n.__setDigit(o, 1073741823 & i);
802
- }
803
- if (0 != g) throw new Error("implementation bug");
804
- for (let g2 = e; g2 < t; g2++) n.__setDigit(g2, 0);
805
- return n;
806
- }
807
- static __absoluteAnd(_, t, e = null) {
808
- let n = _.length, g = t.length, o = g;
809
- if (n < g) {
810
- o = n;
811
- const i = _, e2 = n;
812
- _ = t, n = g, t = i, g = e2;
813
- }
814
- let s = o;
815
- null === e ? e = new _JSBI(s, false) : s = e.length;
816
- let l = 0;
817
- for (; l < o; l++) e.__setDigit(l, _.__digit(l) & t.__digit(l));
818
- for (; l < s; l++) e.__setDigit(l, 0);
819
- return e;
820
- }
821
- static __absoluteAndNot(_, t, e = null) {
822
- const n = _.length, g = t.length;
823
- let o = g;
824
- n < g && (o = n);
825
- let s = n;
826
- null === e ? e = new _JSBI(s, false) : s = e.length;
827
- let l = 0;
828
- for (; l < o; l++) e.__setDigit(l, _.__digit(l) & ~t.__digit(l));
829
- for (; l < n; l++) e.__setDigit(l, _.__digit(l));
830
- for (; l < s; l++) e.__setDigit(l, 0);
831
- return e;
832
- }
833
- static __absoluteOr(_, t, e = null) {
834
- let n = _.length, g = t.length, o = g;
835
- if (n < g) {
836
- o = n;
837
- const i = _, e2 = n;
838
- _ = t, n = g, t = i, g = e2;
839
- }
840
- let s = n;
841
- null === e ? e = new _JSBI(s, false) : s = e.length;
842
- let l = 0;
843
- for (; l < o; l++) e.__setDigit(l, _.__digit(l) | t.__digit(l));
844
- for (; l < n; l++) e.__setDigit(l, _.__digit(l));
845
- for (; l < s; l++) e.__setDigit(l, 0);
846
- return e;
847
- }
848
- static __absoluteXor(_, t, e = null) {
849
- let n = _.length, g = t.length, o = g;
850
- if (n < g) {
851
- o = n;
852
- const i = _, e2 = n;
853
- _ = t, n = g, t = i, g = e2;
854
- }
855
- let s = n;
856
- null === e ? e = new _JSBI(s, false) : s = e.length;
857
- let l = 0;
858
- for (; l < o; l++) e.__setDigit(l, _.__digit(l) ^ t.__digit(l));
859
- for (; l < n; l++) e.__setDigit(l, _.__digit(l));
860
- for (; l < s; l++) e.__setDigit(l, 0);
861
- return e;
862
- }
863
- static __absoluteCompare(_, t) {
864
- const e = _.length - t.length;
865
- if (0 != e) return e;
866
- let n = _.length - 1;
867
- for (; 0 <= n && _.__digit(n) === t.__digit(n); ) n--;
868
- return 0 > n ? 0 : _.__unsignedDigit(n) > t.__unsignedDigit(n) ? 1 : -1;
869
- }
870
- static __multiplyAccumulate(_, t, e, n) {
871
- if (0 === t) return;
872
- const g = 32767 & t, o = t >>> 15;
873
- let s = 0, l = 0;
874
- for (let r, a = 0; a < _.length; a++, n++) {
875
- r = e.__digit(n);
876
- const i = _.__digit(a), t2 = 32767 & i, u = i >>> 15, d = _JSBI.__imul(t2, g), h = _JSBI.__imul(t2, o), m = _JSBI.__imul(u, g), b = _JSBI.__imul(u, o);
877
- r += l + d + s, s = r >>> 30, r &= 1073741823, r += ((32767 & h) << 15) + ((32767 & m) << 15), s += r >>> 30, l = b + (h >>> 15) + (m >>> 15), e.__setDigit(n, 1073741823 & r);
878
- }
879
- for (; 0 != s || 0 !== l; n++) {
880
- let i = e.__digit(n);
881
- i += s + l, l = 0, s = i >>> 30, e.__setDigit(n, 1073741823 & i);
882
- }
883
- }
884
- static __internalMultiplyAdd(_, t, e, g, o) {
885
- let s = e, l = 0;
886
- for (let n = 0; n < g; n++) {
887
- const i = _.__digit(n), e2 = _JSBI.__imul(32767 & i, t), g2 = _JSBI.__imul(i >>> 15, t), a = e2 + ((32767 & g2) << 15) + l + s;
888
- s = a >>> 30, l = g2 >>> 15, o.__setDigit(n, 1073741823 & a);
889
- }
890
- if (o.length > g) for (o.__setDigit(g++, s + l); g < o.length; ) o.__setDigit(g++, 0);
891
- else if (0 !== s + l) throw new Error("implementation bug");
892
- }
893
- __inplaceMultiplyAdd(i, _, t) {
894
- t > this.length && (t = this.length);
895
- const e = 32767 & i, n = i >>> 15;
896
- let g = 0, o = _;
897
- for (let s = 0; s < t; s++) {
898
- const i2 = this.__digit(s), _2 = 32767 & i2, t2 = i2 >>> 15, l = _JSBI.__imul(_2, e), r = _JSBI.__imul(_2, n), a = _JSBI.__imul(t2, e), u = _JSBI.__imul(t2, n);
899
- let d = o + l + g;
900
- g = d >>> 30, d &= 1073741823, d += ((32767 & r) << 15) + ((32767 & a) << 15), g += d >>> 30, o = u + (r >>> 15) + (a >>> 15), this.__setDigit(s, 1073741823 & d);
901
- }
902
- if (0 != g || 0 !== o) throw new Error("implementation bug");
903
- }
904
- static __absoluteDivSmall(_, t, e = null) {
905
- null === e && (e = new _JSBI(_.length, false));
906
- let n = 0;
907
- for (let g, o = 2 * _.length - 1; 0 <= o; o -= 2) {
908
- g = (n << 15 | _.__halfDigit(o)) >>> 0;
909
- const i = 0 | g / t;
910
- n = 0 | g % t, g = (n << 15 | _.__halfDigit(o - 1)) >>> 0;
911
- const s = 0 | g / t;
912
- n = 0 | g % t, e.__setDigit(o >>> 1, i << 15 | s);
913
- }
914
- return e;
915
- }
916
- static __absoluteModSmall(_, t) {
917
- let e = 0;
918
- for (let n = 2 * _.length - 1; 0 <= n; n--) {
919
- const i = (e << 15 | _.__halfDigit(n)) >>> 0;
920
- e = 0 | i % t;
921
- }
922
- return e;
923
- }
924
- static __absoluteDivLarge(i, _, t, e) {
925
- const g = _.__halfDigitLength(), n = _.length, o = i.__halfDigitLength() - g;
926
- let s = null;
927
- t && (s = new _JSBI(o + 2 >>> 1, false), s.__initializeDigits());
928
- const l = new _JSBI(g + 2 >>> 1, false);
929
- l.__initializeDigits();
930
- const r = _JSBI.__clz15(_.__halfDigit(g - 1));
931
- 0 < r && (_ = _JSBI.__specialLeftShift(_, r, 0));
932
- const a = _JSBI.__specialLeftShift(i, r, 1), u = _.__halfDigit(g - 1);
933
- let d = 0;
934
- for (let r2, h = o; 0 <= h; h--) {
935
- r2 = 32767;
936
- const i2 = a.__halfDigit(h + g);
937
- if (i2 !== u) {
938
- const t2 = (i2 << 15 | a.__halfDigit(h + g - 1)) >>> 0;
939
- r2 = 0 | t2 / u;
940
- let e3 = 0 | t2 % u;
941
- const n2 = _.__halfDigit(g - 2), o2 = a.__halfDigit(h + g - 2);
942
- for (; _JSBI.__imul(r2, n2) >>> 0 > (e3 << 16 | o2) >>> 0 && (r2--, e3 += u, !(32767 < e3)); ) ;
943
- }
944
- _JSBI.__internalMultiplyAdd(_, r2, 0, n, l);
945
- let e2 = a.__inplaceSub(l, h, g + 1);
946
- 0 !== e2 && (e2 = a.__inplaceAdd(_, h, g), a.__setHalfDigit(h + g, 32767 & a.__halfDigit(h + g) + e2), r2--), t && (1 & h ? d = r2 << 15 : s.__setDigit(h >>> 1, d | r2));
947
- }
948
- if (e) return a.__inplaceRightShift(r), t ? { quotient: s, remainder: a } : a;
949
- if (t) return s;
950
- throw new Error("unreachable");
951
- }
952
- static __clz15(i) {
953
- return _JSBI.__clz30(i) - 15;
954
- }
955
- __inplaceAdd(_, t, e) {
956
- let n = 0;
957
- for (let g = 0; g < e; g++) {
958
- const i = this.__halfDigit(t + g) + _.__halfDigit(g) + n;
959
- n = i >>> 15, this.__setHalfDigit(t + g, 32767 & i);
960
- }
961
- return n;
962
- }
963
- __inplaceSub(_, t, e) {
964
- let n = 0;
965
- if (1 & t) {
966
- t >>= 1;
967
- let g = this.__digit(t), o = 32767 & g, s = 0;
968
- for (; s < e - 1 >>> 1; s++) {
969
- const i2 = _.__digit(s), e2 = (g >>> 15) - (32767 & i2) - n;
970
- n = 1 & e2 >>> 15, this.__setDigit(t + s, (32767 & e2) << 15 | 32767 & o), g = this.__digit(t + s + 1), o = (32767 & g) - (i2 >>> 15) - n, n = 1 & o >>> 15;
971
- }
972
- const i = _.__digit(s), l = (g >>> 15) - (32767 & i) - n;
973
- n = 1 & l >>> 15, this.__setDigit(t + s, (32767 & l) << 15 | 32767 & o);
974
- if (t + s + 1 >= this.length) throw new RangeError("out of bounds");
975
- 0 == (1 & e) && (g = this.__digit(t + s + 1), o = (32767 & g) - (i >>> 15) - n, n = 1 & o >>> 15, this.__setDigit(t + _.length, 1073709056 & g | 32767 & o));
976
- } else {
977
- t >>= 1;
978
- let g = 0;
979
- for (; g < _.length - 1; g++) {
980
- const i2 = this.__digit(t + g), e2 = _.__digit(g), o2 = (32767 & i2) - (32767 & e2) - n;
981
- n = 1 & o2 >>> 15;
982
- const s2 = (i2 >>> 15) - (e2 >>> 15) - n;
983
- n = 1 & s2 >>> 15, this.__setDigit(t + g, (32767 & s2) << 15 | 32767 & o2);
984
- }
985
- const i = this.__digit(t + g), o = _.__digit(g), s = (32767 & i) - (32767 & o) - n;
986
- n = 1 & s >>> 15;
987
- let l = 0;
988
- 0 == (1 & e) && (l = (i >>> 15) - (o >>> 15) - n, n = 1 & l >>> 15), this.__setDigit(t + g, (32767 & l) << 15 | 32767 & s);
989
- }
990
- return n;
991
- }
992
- __inplaceRightShift(_) {
993
- if (0 === _) return;
994
- let t = this.__digit(0) >>> _;
995
- const e = this.length - 1;
996
- for (let n = 0; n < e; n++) {
997
- const i = this.__digit(n + 1);
998
- this.__setDigit(n, 1073741823 & i << 30 - _ | t), t = i >>> _;
999
- }
1000
- this.__setDigit(e, t);
1001
- }
1002
- static __specialLeftShift(_, t, e) {
1003
- const g = _.length, n = new _JSBI(g + e, false);
1004
- if (0 === t) {
1005
- for (let t2 = 0; t2 < g; t2++) n.__setDigit(t2, _.__digit(t2));
1006
- return 0 < e && n.__setDigit(g, 0), n;
1007
- }
1008
- let o = 0;
1009
- for (let s = 0; s < g; s++) {
1010
- const i = _.__digit(s);
1011
- n.__setDigit(s, 1073741823 & i << t | o), o = i >>> 30 - t;
1012
- }
1013
- return 0 < e && n.__setDigit(g, o), n;
1014
- }
1015
- static __leftShiftByAbsolute(_, i) {
1016
- const t = _JSBI.__toShiftAmount(i);
1017
- if (0 > t) throw new RangeError("BigInt too big");
1018
- const e = 0 | t / 30, n = t % 30, g = _.length, o = 0 !== n && 0 != _.__digit(g - 1) >>> 30 - n, s = g + e + (o ? 1 : 0), l = new _JSBI(s, _.sign);
1019
- if (0 === n) {
1020
- let t2 = 0;
1021
- for (; t2 < e; t2++) l.__setDigit(t2, 0);
1022
- for (; t2 < s; t2++) l.__setDigit(t2, _.__digit(t2 - e));
1023
- } else {
1024
- let t2 = 0;
1025
- for (let _2 = 0; _2 < e; _2++) l.__setDigit(_2, 0);
1026
- for (let o2 = 0; o2 < g; o2++) {
1027
- const i2 = _.__digit(o2);
1028
- l.__setDigit(o2 + e, 1073741823 & i2 << n | t2), t2 = i2 >>> 30 - n;
1029
- }
1030
- if (o) l.__setDigit(g + e, t2);
1031
- else if (0 !== t2) throw new Error("implementation bug");
1032
- }
1033
- return l.__trim();
1034
- }
1035
- static __rightShiftByAbsolute(_, i) {
1036
- const t = _.length, e = _.sign, n = _JSBI.__toShiftAmount(i);
1037
- if (0 > n) return _JSBI.__rightShiftByMaximum(e);
1038
- const g = 0 | n / 30, o = n % 30;
1039
- let s = t - g;
1040
- if (0 >= s) return _JSBI.__rightShiftByMaximum(e);
1041
- let l = false;
1042
- if (e) {
1043
- if (0 != (_.__digit(g) & (1 << o) - 1)) l = true;
1044
- else for (let t2 = 0; t2 < g; t2++) if (0 !== _.__digit(t2)) {
1045
- l = true;
1046
- break;
1047
- }
1048
- }
1049
- if (l && 0 === o) {
1050
- const i2 = _.__digit(t - 1);
1051
- 0 == ~i2 && s++;
1052
- }
1053
- let r = new _JSBI(s, e);
1054
- if (0 === o) {
1055
- r.__setDigit(s - 1, 0);
1056
- for (let e2 = g; e2 < t; e2++) r.__setDigit(e2 - g, _.__digit(e2));
1057
- } else {
1058
- let e2 = _.__digit(g) >>> o;
1059
- const n2 = t - g - 1;
1060
- for (let t2 = 0; t2 < n2; t2++) {
1061
- const i2 = _.__digit(t2 + g + 1);
1062
- r.__setDigit(t2, 1073741823 & i2 << 30 - o | e2), e2 = i2 >>> o;
1063
- }
1064
- r.__setDigit(n2, e2);
1065
- }
1066
- return l && (r = _JSBI.__absoluteAddOne(r, true, r)), r.__trim();
1067
- }
1068
- static __rightShiftByMaximum(i) {
1069
- return i ? _JSBI.__oneDigit(1, true) : _JSBI.__zero();
1070
- }
1071
- static __toShiftAmount(i) {
1072
- if (1 < i.length) return -1;
1073
- const _ = i.__unsignedDigit(0);
1074
- return _ > _JSBI.__kMaxLengthBits ? -1 : _;
1075
- }
1076
- static __toPrimitive(i, _ = "default") {
1077
- if ("object" != typeof i) return i;
1078
- if (i.constructor === _JSBI) return i;
1079
- if ("undefined" != typeof Symbol && "symbol" == typeof Symbol.toPrimitive) {
1080
- const t2 = i[Symbol.toPrimitive];
1081
- if (t2) {
1082
- const i2 = t2(_);
1083
- if ("object" != typeof i2) return i2;
1084
- throw new TypeError("Cannot convert object to primitive value");
1085
- }
1086
- }
1087
- const t = i.valueOf;
1088
- if (t) {
1089
- const _2 = t.call(i);
1090
- if ("object" != typeof _2) return _2;
1091
- }
1092
- const e = i.toString;
1093
- if (e) {
1094
- const _2 = e.call(i);
1095
- if ("object" != typeof _2) return _2;
1096
- }
1097
- throw new TypeError("Cannot convert object to primitive value");
1098
- }
1099
- static __toNumeric(i) {
1100
- return _JSBI.__isBigInt(i) ? i : +i;
1101
- }
1102
- static __isBigInt(i) {
1103
- return "object" == typeof i && null !== i && i.constructor === _JSBI;
1104
- }
1105
- static __truncateToNBits(i, _) {
1106
- const t = 0 | (i + 29) / 30, e = new _JSBI(t, _.sign), n = t - 1;
1107
- for (let t2 = 0; t2 < n; t2++) e.__setDigit(t2, _.__digit(t2));
1108
- let g = _.__digit(n);
1109
- if (0 != i % 30) {
1110
- const _2 = 32 - i % 30;
1111
- g = g << _2 >>> _2;
1112
- }
1113
- return e.__setDigit(n, g), e.__trim();
1114
- }
1115
- static __truncateAndSubFromPowerOfTwo(_, t, e) {
1116
- var n = Math.min;
1117
- const g = 0 | (_ + 29) / 30, o = new _JSBI(g, e);
1118
- let s = 0;
1119
- const l = g - 1;
1120
- let a = 0;
1121
- for (const i = n(l, t.length); s < i; s++) {
1122
- const i2 = 0 - t.__digit(s) - a;
1123
- a = 1 & i2 >>> 30, o.__setDigit(s, 1073741823 & i2);
1124
- }
1125
- for (; s < l; s++) o.__setDigit(s, 0 | 1073741823 & -a);
1126
- let u = l < t.length ? t.__digit(l) : 0;
1127
- const d = _ % 30;
1128
- let h;
1129
- if (0 == d) h = 0 - u - a, h &= 1073741823;
1130
- else {
1131
- const i = 32 - d;
1132
- u = u << i >>> i;
1133
- const _2 = 1 << 32 - i;
1134
- h = _2 - u - a, h &= _2 - 1;
1135
- }
1136
- return o.__setDigit(l, h), o.__trim();
1137
- }
1138
- __digit(_) {
1139
- return this[_];
1140
- }
1141
- __unsignedDigit(_) {
1142
- return this[_] >>> 0;
1143
- }
1144
- __setDigit(_, i) {
1145
- this[_] = 0 | i;
1146
- }
1147
- __setDigitGrow(_, i) {
1148
- this[_] = 0 | i;
1149
- }
1150
- __halfDigitLength() {
1151
- const i = this.length;
1152
- return 32767 >= this.__unsignedDigit(i - 1) ? 2 * i - 1 : 2 * i;
1153
- }
1154
- __halfDigit(_) {
1155
- return 32767 & this[_ >>> 1] >>> 15 * (1 & _);
1156
- }
1157
- __setHalfDigit(_, i) {
1158
- const t = _ >>> 1, e = this.__digit(t), n = 1 & _ ? 32767 & e | i << 15 : 1073709056 & e | 32767 & i;
1159
- this.__setDigit(t, n);
1160
- }
1161
- static __digitPow(i, _) {
1162
- let t = 1;
1163
- for (; 0 < _; ) 1 & _ && (t *= i), _ >>>= 1, i *= i;
1164
- return t;
1165
- }
1166
- static __isOneDigitInt(i) {
1167
- return (1073741823 & i) === i;
1168
- }
1169
- };
1170
- JSBI.__kMaxLength = 33554432, JSBI.__kMaxLengthBits = JSBI.__kMaxLength << 5, JSBI.__kMaxBitsPerChar = [0, 0, 32, 51, 64, 75, 83, 90, 96, 102, 107, 111, 115, 119, 122, 126, 128, 131, 134, 136, 139, 141, 143, 145, 147, 149, 151, 153, 154, 156, 158, 159, 160, 162, 163, 165, 166], JSBI.__kBitsPerCharTableShift = 5, JSBI.__kBitsPerCharTableMultiplier = 1 << JSBI.__kBitsPerCharTableShift, JSBI.__kConversionChars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"], JSBI.__kBitConversionBuffer = new ArrayBuffer(8), JSBI.__kBitConversionDouble = new Float64Array(JSBI.__kBitConversionBuffer), JSBI.__kBitConversionInts = new Int32Array(JSBI.__kBitConversionBuffer), JSBI.__clz30 = Math.clz32 ? function(i) {
1171
- return Math.clz32(i) - 2;
1172
- } : function(i) {
1173
- return 0 === i ? 30 : 0 | 29 - (0 | Math.log(i >>> 0) / Math.LN2);
1174
- }, JSBI.__imul = Math.imul || function(i, _) {
1175
- return 0 | i * _;
1176
- };
1177
- var jsbi_default = JSBI;
1178
-
1179
- // src/types/CustomFeePair.ts
1180
- var CustomFeePair = class extends UniPair {
1181
- // Override getOutputAmount for 1% fee
1182
- getOutputAmount(inputAmount) {
1183
- const inputReserve = this.reserveOf(inputAmount.currency);
1184
- const outputCurrency = this.token0.equals(inputAmount.currency) ? this.token1 : this.token0;
1185
- const outputReserve = this.reserveOf(outputCurrency);
1186
- const feeNumerator = jsbi_default.BigInt(99);
1187
- const feeDenominator = jsbi_default.BigInt(100);
1188
- const inputAmountWithFee = jsbi_default.divide(jsbi_default.multiply(inputAmount.quotient, feeNumerator), feeDenominator);
1189
- const numerator = jsbi_default.multiply(inputAmountWithFee, outputReserve.quotient);
1190
- const denominator = jsbi_default.add(inputReserve.quotient, inputAmountWithFee);
1191
- const outputAmount = jsbi_default.divide(numerator, denominator);
1192
- return [
1193
- CurrencyAmount.fromRawAmount(outputCurrency, outputAmount),
1194
- this
1195
- ];
1196
- }
1197
- // Override getInputAmount for 1% fee
1198
- getInputAmount(outputAmount) {
1199
- const outputReserve = this.reserveOf(outputAmount.currency);
1200
- const inputCurrency = this.token0.equals(outputAmount.currency) ? this.token1 : this.token0;
1201
- const inputReserve = this.reserveOf(inputCurrency);
1202
- const feeNumerator = jsbi_default.BigInt(100);
1203
- const feeDenominator = jsbi_default.BigInt(99);
1204
- const numerator = jsbi_default.multiply(jsbi_default.multiply(inputReserve.quotient, outputAmount.quotient), feeNumerator);
1205
- const denominator = jsbi_default.multiply(jsbi_default.subtract(outputReserve.quotient, outputAmount.quotient), feeDenominator);
1206
- const inputAmount = jsbi_default.add(jsbi_default.divide(numerator, denominator), jsbi_default.BigInt(1));
1207
- return [
1208
- CurrencyAmount.fromRawAmount(inputCurrency, inputAmount),
1209
- this
1210
- ];
1211
- }
1212
- };
1213
-
1214
- // src/services/swap.service.ts
1215
- var PARTNER_FEE_BPS_DIVISOR = 10000n;
1216
- var SwapService = class {
1217
- constructor(provider, config, swapOptions) {
1218
- this.config = config;
1219
- this.swapOptions = swapOptions;
1220
- this.signer = null;
1221
- this.pairs = [];
1222
- this.resolvePairsLoaded = null;
1223
- this.resolvePartnerFeeLoaded = null;
1224
- this.partnerFee = 0n;
1225
- this.provider = provider;
1226
- this.wethAddress = config.wrappedToken.address;
1227
- this.chainId = config.chainId;
1228
- const routerAbi = [
1229
- // Swaps (ERC20 <-> ERC20)
1230
- "function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)",
1231
- "function swapTokensForExactTokens(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)",
1232
- // Swaps (ETH <-> ERC20)
1233
- "function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)",
1234
- "function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)",
1235
- "function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)",
1236
- "function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)",
1237
- // Get Amounts
1238
- "function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts)",
1239
- "function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut)",
1240
- "function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn)",
1241
- "function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts)",
1242
- // Get WETH
1243
- "function WETH() external pure returns (address)"
1244
- ];
1245
- const factoryAbi = [
1246
- "function getPair(address tokenA, address tokenB) external view returns (address pair)",
1247
- "function allPairs(uint) external view returns (address pair)",
1248
- "function allPairsLength() external view returns (uint)"
1249
- ];
1250
- const proxyAbi = [
1251
- ...routerAbi,
1252
- "function partners(bytes32) external view returns (address feeRecipient, uint16 feeBps)"
1253
- ];
1254
- this.routerContract = new Contract(config.routerAddress, routerAbi, provider);
1255
- this.factoryContract = new Contract(config.factoryAddress, factoryAbi, provider);
1256
- if (config.proxyAddress) {
1257
- this.proxyContract = new Contract(config.proxyAddress, proxyAbi, provider);
1258
- }
1259
- this.pairsLoadedPromise = new Promise((resolve) => {
1260
- this.resolvePairsLoaded = resolve;
1261
- });
1262
- this.partnerFeeLoadedPromise = new Promise((resolve) => {
1263
- this.resolvePartnerFeeLoaded = resolve;
1264
- });
1265
- this.loadAllPairsFromGraph();
1266
- this.loadPartnerFee();
1267
- }
1268
- // parnter fee is BPS_DIVISOR = 10_000n;
1269
- async loadPartnerFee() {
1270
- if (!this.resolvePairsLoaded) {
1271
- return this.partnerFee;
1272
- }
1273
- if (this.swapOptions.partnerKey && this.proxyContract) {
1274
- const [, fee] = await this.proxyContract?.partners(this.swapOptions.partnerKey);
1275
- this.partnerFee = fee;
1276
- }
1277
- if (this.resolvePartnerFeeLoaded) {
1278
- this.resolvePartnerFeeLoaded();
1279
- this.resolvePartnerFeeLoaded = null;
1280
- }
1281
- return this.partnerFee;
1282
- }
1283
- setSigner(signer) {
1284
- this.signer = signer;
1285
- this.routerContract = this.routerContract.connect(signer);
1286
- if (this.proxyContract) {
1287
- this.proxyContract = this.proxyContract.connect(signer);
1288
- }
1289
- }
1290
- /**
1291
- * Rounds a number string to the specified number of decimal places
1292
- * to avoid parseUnits errors with too many decimals
1293
- */
1294
- roundToDecimals(value, decimals) {
1295
- const num = parseFloat(value);
1296
- if (isNaN(num)) {
1297
- return "0";
1298
- }
1299
- return num.toFixed(decimals);
1300
- }
1301
- /**
1302
- * Loads all pairs from The Graph and caches them as Uniswap SDK Pair instances.
1303
- * @param graphEndpoint The GraphQL endpoint URL
1304
- */
1305
- async loadAllPairsFromGraph() {
1306
- const query = `{
1307
- pairs(first: 1000) {
1308
- id
1309
- reserve0
1310
- reserve1
1311
- token0 { id symbol name decimals }
1312
- token1 { id symbol name decimals }
1313
- }
1314
- }`;
1315
- try {
1316
- const response = await fetch(this.config.graphEndpoint, {
1317
- method: "POST",
1318
- headers: { "Content-Type": "application/json" },
1319
- body: JSON.stringify({ query })
1320
- });
1321
- if (!response.ok) throw new Error(`Network error: ${response.status}`);
1322
- const { data } = await response.json();
1323
- if (!data || !data.pairs) return;
1324
- const pairs = [];
1325
- for (const pair of data.pairs) {
1326
- pairs.push(
1327
- this.createSDKPair(pair)
1328
- );
1329
- }
1330
- this.pairs = pairs;
1331
- const wethPair = data.pairs.find(
1332
- (pair) => pair.token0.id.toLowerCase() === this.wethAddress.toLowerCase() || pair.token1.id.toLowerCase() === this.wethAddress.toLowerCase()
1333
- );
1334
- if (wethPair) {
1335
- const tokenData = wethPair.token0.id.toLowerCase() === this.wethAddress.toLowerCase() ? wethPair.token0 : wethPair.token1;
1336
- this.wethToken = {
1337
- address: tokenData.id,
1338
- symbol: tokenData.symbol,
1339
- name: tokenData.name,
1340
- decimals: Number(tokenData.decimals)
1341
- };
1342
- } else {
1343
- throw new Error("No weth token found");
1344
- }
1345
- if (this.resolvePairsLoaded) {
1346
- this.resolvePairsLoaded();
1347
- this.resolvePairsLoaded = null;
1348
- }
1349
- } catch (error) {
1350
- console.error("Error loading pairs from graph:", error);
1351
- if (this.resolvePairsLoaded) {
1352
- this.resolvePairsLoaded();
1353
- this.resolvePairsLoaded = null;
1354
- }
1355
- }
1356
- }
1357
- async waitForPairsLoaded() {
1358
- return await this.pairsLoadedPromise;
1359
- }
1360
- async waitForPartnerFeeLoaded() {
1361
- return await this.partnerFeeLoadedPromise;
1362
- }
1363
- createSDKPair(pair) {
1364
- const { token0, token1, id, reserve0, reserve1 } = pair;
1365
- const sdkToken0 = new Token2(
1366
- this.chainId,
1367
- token0.id,
1368
- Number(token0.decimals),
1369
- token0.symbol,
1370
- token0.name
1371
- );
1372
- const sdkToken1 = new Token2(
1373
- this.chainId,
1374
- token1.id,
1375
- Number(token1.decimals),
1376
- token1.symbol,
1377
- token1.name
1378
- );
1379
- let reserve0BN;
1380
- let reserve1BN;
1381
- if (reserve0 && reserve1) {
1382
- reserve0BN = parseUnits(reserve0, Number(token0.decimals));
1383
- reserve1BN = parseUnits(reserve1, Number(token1.decimals));
1384
- } else {
1385
- throw new Error("No reserves data");
1386
- }
1387
- const amount0 = CurrencyAmount2.fromRawAmount(
1388
- sdkToken0,
1389
- reserve0BN.toString()
1390
- );
1391
- const amount1 = CurrencyAmount2.fromRawAmount(
1392
- sdkToken1,
1393
- reserve1BN.toString()
1394
- );
1395
- const sdkPair = new CustomFeePair(amount0, amount1);
1396
- return sdkPair;
1397
- }
1398
- /**
1399
- * Returns the cached pairs for use in routing.
1400
- */
1401
- getPairs() {
1402
- return this.pairs;
1403
- }
1404
- /**
1405
- * Finds the best trade path using Uniswap SDK for a given input amount.
1406
- * Returns the best path as an array of addresses, or null if no trade found.
1407
- */
1408
- async getBestTrade(fromToken, toToken, amountInWei, isOutputAmount) {
1409
- const sdkFromToken = new Token2(
1410
- this.chainId,
1411
- fromToken.address,
1412
- fromToken.decimals,
1413
- fromToken.symbol,
1414
- fromToken.name
1415
- );
1416
- const sdkToToken = new Token2(
1417
- this.chainId,
1418
- toToken.address,
1419
- toToken.decimals,
1420
- toToken.symbol,
1421
- toToken.name
1422
- );
1423
- const currencyAmount = CurrencyAmount2.fromRawAmount(
1424
- isOutputAmount ? sdkToToken : sdkFromToken,
1425
- amountInWei
1426
- );
1427
- await this.waitForPairsLoaded();
1428
- await this.waitForPartnerFeeLoaded();
1429
- const pairs = this.getPairs();
1430
- if (!pairs || pairs.length === 0) {
1431
- throw new Error("Pairs not loaded yet. Please wait for initialization.");
1432
- }
1433
- const tradeConfig = {
1434
- maxHops: 3,
1435
- maxNumResults: 1
1436
- };
1437
- const trades = isOutputAmount ? Trade.bestTradeExactOut(pairs, sdkFromToken, currencyAmount, tradeConfig) : Trade.bestTradeExactIn(
1438
- pairs,
1439
- currencyAmount,
1440
- sdkToToken,
1441
- tradeConfig
1442
- );
1443
- if (trades.length > 0) {
1444
- return trades[0];
1445
- } else {
1446
- return null;
1447
- }
1448
- }
1449
- trimTrailingZeros(value) {
1450
- if (!value.includes(".")) return value;
1451
- value = value.replace(/\.?0+$/, "");
1452
- return value;
1453
- }
1454
- /**
1455
- *
1456
- * @param sellToken
1457
- * @param buyToken
1458
- * @param targetAmount
1459
- * @param isOutputAmount true if user input output (How much tokens to receive) and not input (how much tokens to sell)
1460
- * @param slippage
1461
- * @returns
1462
- */
1463
- async calculateTrade(sellToken, buyToken, targetAmount, isOutputAmount, slippage) {
1464
- try {
1465
- const roundedAmountIn = this.roundToDecimals(targetAmount, isOutputAmount ? buyToken.decimals : sellToken.decimals);
1466
- let sellAmountWei = parseUnits(
1467
- roundedAmountIn,
1468
- isOutputAmount ? buyToken.decimals : sellToken.decimals
1469
- );
1470
- if (isOutputAmount && this.partnerFee && this.partnerFee > 0n) {
1471
- const numerator = sellAmountWei * PARTNER_FEE_BPS_DIVISOR;
1472
- const denominator = PARTNER_FEE_BPS_DIVISOR - this.partnerFee;
1473
- sellAmountWei = (numerator + denominator - 1n) / denominator;
1474
- }
1475
- const sellTokenForContracts = sellToken.address == ethers.ZeroAddress ? this.wethToken : sellToken;
1476
- const buyTokenForContracts = buyToken.address == ethers.ZeroAddress ? this.wethToken : buyToken;
1477
- const trade = await this.getBestTrade(
1478
- sellTokenForContracts,
1479
- buyTokenForContracts,
1480
- sellAmountWei.toString(),
1481
- isOutputAmount
1482
- );
1483
- if (!trade) {
1484
- throw new Error("No trade path found for the given tokens and amount.");
1485
- }
1486
- const amountIn = trade.inputAmount.quotient.toString();
1487
- const amountOut = trade.outputAmount.quotient.toString();
1488
- let amounts = {
1489
- amountIn: formatUnits(amountIn, sellToken.decimals),
1490
- amountOut: isOutputAmount ? this.trimTrailingZeros(roundedAmountIn) : formatUnits(amountOut, buyToken.decimals),
1491
- amountInRaw: amountIn,
1492
- amountOutRaw: amountOut
1493
- };
1494
- const slippagePercent = new Percent(Math.round(parseFloat(slippage) * 100), 1e4);
1495
- let maxAmountIn, minAmountOut;
1496
- if (isOutputAmount) {
1497
- maxAmountIn = trade.maximumAmountIn(slippagePercent).quotient.toString();
1498
- amounts.maxAmountInRaw = maxAmountIn;
1499
- amounts.maxAmountIn = formatUnits(maxAmountIn, sellToken.decimals);
1500
- } else {
1501
- minAmountOut = trade.minimumAmountOut(slippagePercent).quotient.toString();
1502
- amounts.minAmountOutRaw = minAmountOut;
1503
- amounts.minAmountOut = formatUnits(minAmountOut, buyToken.decimals);
1504
- }
1505
- if (this.partnerFee && this.partnerFee > 0n) {
1506
- if (!isOutputAmount) {
1507
- const amountOut2 = BigInt(trade.outputAmount.quotient.toString());
1508
- const amountOutMinusFee = amountOut2 * (PARTNER_FEE_BPS_DIVISOR - this.partnerFee) / PARTNER_FEE_BPS_DIVISOR;
1509
- amounts.amountOutRaw = amountOutMinusFee.toString();
1510
- amounts.amountOut = formatUnits(amountOutMinusFee, buyToken.decimals);
1511
- if (minAmountOut) {
1512
- const minOut = BigInt(minAmountOut.toString());
1513
- const minOutMinusFee = minOut * (PARTNER_FEE_BPS_DIVISOR - this.partnerFee) / PARTNER_FEE_BPS_DIVISOR;
1514
- amounts.minAmountOutRaw = minOutMinusFee.toString();
1515
- amounts.minAmountOut = formatUnits(minOutMinusFee, buyToken.decimals);
1516
- }
1517
- }
1518
- }
1519
- return {
1520
- trade,
1521
- computed: amounts
1522
- };
1523
- } catch (error) {
1524
- console.error("Error calculating expected output:", error);
1525
- throw error;
1526
- }
1527
- }
1528
- async checkApproval(tokenAddress, amount, spenderAddress) {
1529
- try {
1530
- const tokenContract = new Contract(
1531
- tokenAddress,
1532
- ["function allowance(address,address) view returns (uint256)"],
1533
- this.provider
1534
- );
1535
- const signerAddress = await this.signer?.getAddress();
1536
- if (!signerAddress) {
1537
- throw new Error("Please connect wallet first");
1538
- }
1539
- const allowance = await tokenContract.allowance(signerAddress, spenderAddress);
1540
- const amountWei = parseUnits(amount, 18);
1541
- return allowance >= amountWei;
1542
- } catch (error) {
1543
- console.error("Error checking approval:", error);
1544
- return false;
1545
- }
1546
- }
1547
- async isApprovalNeeded(fromToken, amountInWei) {
1548
- if (!this.signer) {
1549
- throw new Error("Please connect wallet first");
1550
- }
1551
- if (fromToken.address !== ethers.ZeroAddress) {
1552
- const tokenContract = new Contract(
1553
- fromToken.address,
1554
- ["function allowance(address,address) view returns (uint256)", "function approve(address,uint256) returns (bool)"],
1555
- this.signer
1556
- );
1557
- const signerAddress = await this.signer.getAddress();
1558
- const allowanceTo = this.config.proxyAddress || this.config.routerAddress;
1559
- const allowance = await tokenContract.allowance(signerAddress, allowanceTo);
1560
- if (allowance < amountInWei) {
1561
- return {
1562
- isApprovalNeeded: true,
1563
- tokenContract,
1564
- signerAddress,
1565
- allowanceTo
1566
- };
1567
- }
1568
- }
1569
- return {
1570
- isApprovalNeeded: false
1571
- };
1572
- }
1573
- async approveIfNeedApproval(fromToken, amountInWei) {
1574
- const isApprovalNeededInfo = await this.isApprovalNeeded(fromToken, amountInWei);
1575
- if (!isApprovalNeededInfo.isApprovalNeeded) {
1576
- return null;
1577
- }
1578
- return await isApprovalNeededInfo.tokenContract.approve(isApprovalNeededInfo.allowanceTo, ethers.MaxUint256);
1579
- }
1580
- async swapTokens(fromToken, toToken, amountInWei, amountOutWei, path, isOutputAmount, deadline) {
1581
- if (!this.signer) {
1582
- throw new Error("Please connect wallet first");
1583
- }
1584
- try {
1585
- const deadlineTimestamp = Math.floor(Date.now() / 1e3) + deadline * 60;
1586
- let tx;
1587
- const signerAddress = await this.signer.getAddress();
1588
- const iface = this.proxyContract ? this.proxyContract.interface : this.routerContract.interface;
1589
- let swapData;
1590
- const to = this.config.proxyAddress ? this.config.proxyAddress : signerAddress;
1591
- if (isOutputAmount) {
1592
- if (fromToken.address === ethers.ZeroAddress) {
1593
- swapData = iface.encodeFunctionData("swapETHForExactTokens", [
1594
- amountOutWei,
1595
- path,
1596
- to,
1597
- deadlineTimestamp
1598
- ]);
1599
- } else if (toToken.address === ethers.ZeroAddress) {
1600
- swapData = iface.encodeFunctionData("swapTokensForExactETH", [
1601
- amountOutWei,
1602
- amountInWei,
1603
- path,
1604
- to,
1605
- deadlineTimestamp
1606
- ]);
1607
- } else {
1608
- swapData = iface.encodeFunctionData("swapTokensForExactTokens", [
1609
- amountOutWei,
1610
- amountInWei,
1611
- path,
1612
- to,
1613
- deadlineTimestamp
1614
- ]);
1615
- }
1616
- } else {
1617
- if (fromToken.address === ethers.ZeroAddress) {
1618
- swapData = iface.encodeFunctionData("swapExactETHForTokens", [
1619
- amountOutWei,
1620
- path,
1621
- to,
1622
- deadlineTimestamp
1623
- ]);
1624
- } else if (toToken.address === ethers.ZeroAddress) {
1625
- swapData = iface.encodeFunctionData("swapExactTokensForETH", [
1626
- amountInWei,
1627
- amountOutWei,
1628
- path,
1629
- to,
1630
- deadlineTimestamp
1631
- ]);
1632
- } else {
1633
- swapData = iface.encodeFunctionData("swapExactTokensForTokens", [
1634
- amountInWei,
1635
- amountOutWei,
1636
- path,
1637
- to,
1638
- deadlineTimestamp
1639
- ]);
1640
- }
1641
- }
1642
- if (this.proxyContract) {
1643
- swapData = hexlify(this.concatSelectorAndParams(ethers.getBytes(swapData), [], "PERMIT", this.swapOptions.partnerKey));
1644
- }
1645
- tx = await this.signer.sendTransaction({
1646
- to: this.config.proxyAddress || this.config.routerAddress,
1647
- from: signerAddress,
1648
- data: swapData,
1649
- value: fromToken.address === ethers.ZeroAddress ? amountInWei : 0n
1650
- });
1651
- return tx;
1652
- } catch (error) {
1653
- console.error("Error swapping tokens:", error);
1654
- throw error;
1655
- }
1656
- }
1657
- async getPairAddress(tokenA, tokenB) {
1658
- try {
1659
- return await this.factoryContract.getPair(tokenA, tokenB);
1660
- } catch (error) {
1661
- console.error("Error getting pair address:", error);
1662
- throw error;
1663
- }
1664
- }
1665
- async checkLiquidityExists(tokenA, tokenB) {
1666
- try {
1667
- const pairAddress = await this.getPairAddress(tokenA, tokenB);
1668
- return pairAddress !== ZeroAddress;
1669
- } catch (error) {
1670
- console.error("Error checking liquidity:", error);
1671
- return false;
1672
- }
1673
- }
1674
- // Uniswap SDK methods for advanced trading
1675
- async createTrade(fromToken, toToken, amountIn, slippageTolerance = 0.5) {
1676
- try {
1677
- const fromTokenInstance = new Token2(
1678
- this.chainId,
1679
- fromToken.address,
1680
- fromToken.decimals,
1681
- fromToken.symbol,
1682
- fromToken.name
1683
- );
1684
- const toTokenInstance = new Token2(
1685
- this.chainId,
1686
- toToken.address,
1687
- toToken.decimals,
1688
- toToken.symbol,
1689
- toToken.name
1690
- );
1691
- const currencyAmount = CurrencyAmount2.fromRawAmount(
1692
- fromTokenInstance,
1693
- parseUnits(amountIn, fromToken.decimals).toString()
1694
- );
1695
- const pairAddress = await this.getPairAddress(fromToken.address, toToken.address);
1696
- if (pairAddress === ZeroAddress) {
1697
- throw new Error("No liquidity pair found");
1698
- }
1699
- const pair = new CustomFeePair(
1700
- CurrencyAmount2.fromRawAmount(fromTokenInstance, "0"),
1701
- CurrencyAmount2.fromRawAmount(toTokenInstance, "0")
1702
- );
1703
- const route = new Route([pair], fromTokenInstance, toTokenInstance);
1704
- const trade = new Trade(
1705
- route,
1706
- currencyAmount,
1707
- TradeType.EXACT_INPUT
1708
- );
1709
- return trade;
1710
- } catch (error) {
1711
- console.error("Error creating trade:", error);
1712
- throw error;
1713
- }
1714
- }
1715
- /**
1716
- * Fetch tokens from the graph endpoint (subgraph)
1717
- * @param graphEndpoint The GraphQL endpoint URL
1718
- * @param search Optional search string for symbol or name
1719
- */
1720
- async getTokensFromGraph(limit = 100, search) {
1721
- const finalLimit = Math.min(limit, 1e3);
1722
- const query = `{
1723
- tokens(first: ${finalLimit}, where: {
1724
- ${search ? `or: [
1725
- { symbol_contains_nocase: "${search}" }
1726
- { name_contains_nocase: "${search}" }
1727
- ]` : ""}
1728
- }) {
1729
- id
1730
- symbol
1731
- name
1732
- decimals
1733
- }
1734
- }`;
1735
- try {
1736
- const response = await fetch(this.config.graphEndpoint, {
1737
- method: "POST",
1738
- headers: { "Content-Type": "application/json" },
1739
- body: JSON.stringify({ query })
1740
- });
1741
- if (!response.ok) throw new Error(`Network error: ${response.status}`);
1742
- const { data } = await response.json();
1743
- if (!data || !data.tokens) return [];
1744
- return data.tokens.map((token) => ({
1745
- address: token.id,
1746
- symbol: token.symbol,
1747
- name: token.name,
1748
- decimals: Number(token.decimals)
1749
- }));
1750
- } catch (error) {
1751
- console.error("Error fetching tokens from graph:", error);
1752
- return [];
1753
- }
1754
- }
1755
- /**
1756
- * Concatenates bytes: selector, array of bytes (each element is Uint8Array), array length (uint8, 1 byte), marker (bytes16(keccak256(markerString)))
1757
- * @param selectorBytes Uint8Array — function selector (usually 4 bytes)
1758
- * @param arrayOfBytes Uint8Array[] — array of bytes (each element is Uint8Array)
1759
- * @param markerString string — string from which bytes16(keccak256(...)) will be derived
1760
- * @returns Uint8Array — concatenated result
1761
- */
1762
- concatSelectorAndParams(selectorBytes, arrayOfBytes, markerString, partnerKey) {
1763
- const paramsBytes = arrayOfBytes.length === 0 ? new Uint8Array(0) : arrayOfBytes.reduce((acc, arr) => {
1764
- const res = new Uint8Array(acc.length + arr.length);
1765
- res.set(acc, 0);
1766
- res.set(arr, acc.length);
1767
- return res;
1768
- });
1769
- const arrayLengthByte = new Uint8Array([arrayOfBytes.length & 255]);
1770
- const markerHash = ethers.keccak256(ethers.toUtf8Bytes(markerString));
1771
- const markerBytes = ethers.getBytes(markerHash).slice(0, 16);
1772
- const parts = [
1773
- selectorBytes,
1774
- paramsBytes,
1775
- arrayLengthByte,
1776
- markerBytes
1777
- ];
1778
- if (partnerKey) {
1779
- const partnerKeyBytes = ethers.getBytes(partnerKey);
1780
- const partnerFlagHash = ethers.keccak256(ethers.toUtf8Bytes("PARTNER"));
1781
- const partnerFlagBytes = ethers.getBytes(partnerFlagHash).slice(0, 16);
1782
- parts.push(partnerKeyBytes, partnerFlagBytes);
1783
- }
1784
- const totalLen = parts.reduce((sum, p) => sum + p.length, 0);
1785
- const out = new Uint8Array(totalLen);
1786
- let offset = 0;
1787
- for (const p of parts) {
1788
- out.set(p, offset);
1789
- offset += p.length;
1790
- }
1791
- return out;
1792
- }
1793
- };
1794
-
1795
- // src/controllers/swap-sdk.controller.ts
1796
- var DEFAULT_SETTINGS = {
1797
- maxSlippage: "0.5",
1798
- swapDeadline: 20
1799
- };
1800
- var SwapSdkController = class {
1801
- constructor(options) {
1802
- this.state = {
1803
- loader: null
1804
- };
1805
- this.input = {
1806
- fromToken: null,
1807
- toToken: null,
1808
- amount: void 0,
1809
- isOutputAmount: false,
1810
- settings: DEFAULT_SETTINGS
1811
- };
1812
- this.options = options;
1813
- this.initServices();
1814
- }
1815
- initServices() {
1816
- this.walletService = new WalletService(
1817
- this.options.networkConfig,
1818
- this.options.walletProvider
1819
- );
1820
- this.swapService = new SwapService(
1821
- this.walletService.getProvider(),
1822
- this.options.networkConfig,
1823
- this.options
1824
- );
1825
- }
1826
- async setChange(patch) {
1827
- const next = {
1828
- ...this.state,
1829
- ...patch
1830
- };
1831
- this.state = next;
1832
- if (typeof this.options.onChange === "function") {
1833
- await this.options.onChange(next, patch);
1834
- }
1835
- }
1836
- async connectWallet(injectedProvider) {
1837
- const address = await this.walletService.connect(injectedProvider);
1838
- const signer = this.walletService.getSigner();
1839
- if (signer) this.swapService.setSigner(signer);
1840
- return address;
1841
- }
1842
- disconnectWallet() {
1843
- this.walletService.disconnect();
1844
- this.swapService.setSigner(null);
1845
- }
1846
- getState() {
1847
- return this.state;
1848
- }
1849
- get settings() {
1850
- return {
1851
- ...DEFAULT_SETTINGS,
1852
- ...this.input.settings || {}
1853
- };
1854
- }
1855
- async calculateQuoteIfNeeded() {
1856
- const { fromToken, toToken, amount, isOutputAmount } = this.input;
1857
- if (!fromToken || !toToken || !amount || amount <= 0) {
1858
- return;
1859
- }
1860
- await this.setChange({ loader: 1 /* CALCULATING_QUOTE */, error: void 0 });
1861
- try {
1862
- const tradeResult = await this.swapService.calculateTrade(
1863
- fromToken,
1864
- toToken,
1865
- String(amount),
1866
- isOutputAmount == true,
1867
- // isOutputAmount: true for input amount, false for output amount
1868
- this.settings.maxSlippage
1869
- );
1870
- await this.setChange({
1871
- computed: tradeResult.computed,
1872
- tradeInfo: tradeResult.trade,
1873
- loader: null
1874
- });
1875
- } catch (error) {
1876
- await this.setChange({ error: error?.message || String(error), loader: null });
1877
- }
1878
- }
1879
- async setData(input) {
1880
- this.input = {
1881
- ...this.input,
1882
- ...input
1883
- };
1884
- await this.calculateQuoteIfNeeded();
1885
- return this.getState();
1886
- }
1887
- async isNeedApproval() {
1888
- if (!this.input || !this.walletService.isConnected() || !this.swapService) throw new Error("Wallet not connected or input missing");
1889
- const { fromToken, amount } = this.input;
1890
- if (!fromToken || amount === void 0 || !this.state.computed?.amountInRaw) throw new Error("fromToken or amount missing");
1891
- return (await this.swapService.isApprovalNeeded(fromToken, BigInt(this.state.computed.amountInRaw))).isApprovalNeeded;
1892
- }
1893
- async approveIfNeeded() {
1894
- if (!this.input || !this.walletService.isConnected()) throw new Error("Wallet not connected or input missing");
1895
- const { fromToken, amount } = this.input;
1896
- if (!fromToken || amount === void 0 || !this.state.computed?.amountInRaw) throw new Error("fromToken or amount missing");
1897
- await this.setChange({ loader: 2 /* APPROVING */ });
1898
- try {
1899
- const tx = await this.swapService?.approveIfNeedApproval(
1900
- fromToken,
1901
- BigInt(this.state.computed.amountInRaw)
1902
- );
1903
- let receipt;
1904
- if (tx) {
1905
- await this.setChange({ approveTxHash: tx.hash });
1906
- receipt = await tx.wait();
1907
- if (!receipt) {
1908
- throw new Error("Receipt not found, Please try again");
1909
- }
1910
- if (receipt.status != 1) {
1911
- throw new Error("Transaction Rejected");
1912
- }
1913
- }
1914
- return receipt?.hash;
1915
- } catch (error) {
1916
- await this.setChange({ error: error?.message || String(error), loader: null });
1917
- throw error;
1918
- }
1919
- }
1920
- async swap() {
1921
- try {
1922
- await this.setChange({
1923
- txHash: void 0,
1924
- approveTxHash: void 0
1925
- });
1926
- const { fromToken, toToken, amount } = this.input;
1927
- if (!fromToken || !toToken || amount === void 0) throw new Error("Tokens or amount not set");
1928
- await this.approveIfNeeded();
1929
- await this.setChange({ loader: 3 /* SWAPPING */ });
1930
- const trade = this.state.tradeInfo;
1931
- if (!trade) throw new Error("Trade info missing - calculate quote first");
1932
- const path = trade.route.path.map((token) => token.address);
1933
- if (path.length === 0) throw new Error("Trade path missing");
1934
- const computed = this.state.computed;
1935
- if (!computed) throw new Error("Computed amounts missing");
1936
- const transaction = await this.swapService.swapTokens(
1937
- fromToken,
1938
- toToken,
1939
- computed.maxAmountInRaw || computed.amountInRaw,
1940
- computed.minAmountOutRaw || computed.amountOutRaw,
1941
- path,
1942
- this.input.isOutputAmount == true,
1943
- this.settings.swapDeadline
1944
- );
1945
- await this.setChange({ txHash: transaction.hash });
1946
- const receipt = await transaction.wait();
1947
- if (!receipt) {
1948
- throw new Error("Receipt not found, Please try again");
1949
- }
1950
- if (receipt.status != 1) {
1951
- throw new Error("Transaction Rejected");
1952
- }
1953
- await this.setChange({
1954
- loader: null
1955
- });
1956
- return receipt.hash;
1957
- } catch (error) {
1958
- await this.setChange({ error: error?.message || String(error), loader: null });
1959
- throw error;
1960
- }
1961
- }
1962
- async getPartnerFee() {
1963
- return Number(await this.swapService.loadPartnerFee()) / 100;
1964
- }
1965
- async getTokensFromGraph(limit = 100, search) {
1966
- if (!this.swapService) {
1967
- throw new Error("Swap Service not exists");
1968
- }
1969
- return await this.swapService.getTokensFromGraph(limit, search);
1970
- }
1971
- get currentNetworkConfig() {
1972
- return this.options.networkConfig;
1973
- }
1974
- };
1975
-
1976
- // src/config/networks.ts
1977
- import { ethers as ethers2 } from "ethers";
1978
- var NETWORKS = {
1979
- "kasplex-testnet": {
1980
- name: "Kasplex Test",
1981
- chainId: 167012,
1982
- rpcUrl: "https://rpc.kasplextest.xyz",
1983
- routerAddress: "0x81Cc4e7DbC652ec9168Bc2F4435C02d7F315148e",
1984
- factoryAddress: "0x89d5842017ceA7dd18D10EE6c679cE199d2aD99E",
1985
- proxyAddress: "0x5B7e7830851816f8ad968B0e0c336bd50b4860Ad",
1986
- graphEndpoint: "https://dev-graph-kasplex.kaspa.com/subgraphs/name/kasplex-testnet-new-v2-core",
1987
- blockExplorerUrl: "https://explorer.testnet.kasplextest.xyz",
1988
- additionalJsonRpcApiProviderOptionsOptions: {
1989
- batchMaxCount: 1,
1990
- batchMaxSize: 1,
1991
- batchStallTime: 0
1992
- },
1993
- wrappedToken: {
1994
- address: "0xf40178040278E16c8813dB20a84119A605812FB3",
1995
- decimals: 18,
1996
- name: "Wrapped Kasplex Kaspa",
1997
- symbol: "WKAS"
1998
- },
1999
- nativeToken: {
2000
- address: ethers2.ZeroAddress,
2001
- decimals: 18,
2002
- name: "Kasplex Kaspa",
2003
- symbol: "KAS"
2004
- }
2005
- }
2006
- // Add more networks as needed
2007
- };
2008
-
2009
- // src/index.ts
2010
- function createKaspaComSwapController(options) {
2011
- let resolvedOptions;
2012
- if ("networkConfig" in options && typeof options.networkConfig === "string") {
2013
- const networkConfig = NETWORKS[options.networkConfig];
2014
- if (!networkConfig) throw new Error(`Unknown network key: ${options.networkConfig}`);
2015
- resolvedOptions = { ...options, networkConfig };
2016
- } else {
2017
- resolvedOptions = options;
2018
- }
2019
- return new SwapSdkController(resolvedOptions);
2020
- }
2021
- export {
2022
- DEFAULT_SETTINGS as DEFAULT_SWAP_SETTINGS,
2023
- LoaderStatuses,
2024
- NETWORKS,
2025
- SwapSdkController,
2026
- SwapService,
2027
- WalletService,
2028
- createKaspaComSwapController
2029
- };