@kaspacom/swap-sdk 1.1.3 → 1.1.4

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