@pancakeswap/v3-sdk 2.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/abi/MasterChefV3.d.ts +1222 -0
  2. package/dist/abi/MasterChefV3.d.ts.map +1 -0
  3. package/dist/abi/NonfungiblePositionManager.d.ts +962 -0
  4. package/dist/abi/NonfungiblePositionManager.d.ts.map +1 -0
  5. package/dist/abi/PeripheryPaymentsWithFee.d.ts +88 -0
  6. package/dist/abi/PeripheryPaymentsWithFee.d.ts.map +1 -0
  7. package/dist/abi/Quoter.d.ts +162 -0
  8. package/dist/abi/Quoter.d.ts.map +1 -0
  9. package/dist/abi/QuoterV2.d.ts +220 -0
  10. package/dist/abi/QuoterV2.d.ts.map +1 -0
  11. package/dist/abi/SelfPermit.d.ts +122 -0
  12. package/dist/abi/SelfPermit.d.ts.map +1 -0
  13. package/dist/abi/SwapRouter.d.ts +453 -0
  14. package/dist/abi/SwapRouter.d.ts.map +1 -0
  15. package/dist/abi/V3Staker.d.ts +547 -0
  16. package/dist/abi/V3Staker.d.ts.map +1 -0
  17. package/dist/constants.d.ts +36 -3
  18. package/dist/constants.d.ts.map +1 -1
  19. package/dist/entities/pool.d.ts +2 -1
  20. package/dist/entities/pool.d.ts.map +1 -1
  21. package/dist/entities/tick.d.ts.map +1 -1
  22. package/dist/index.d.ts +8 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1528 -1376
  25. package/dist/index.mjs +1516 -1371
  26. package/dist/masterchefV3.d.ts +1228 -9
  27. package/dist/masterchefV3.d.ts.map +1 -1
  28. package/dist/multicall.d.ts +16 -3
  29. package/dist/multicall.d.ts.map +1 -1
  30. package/dist/nonfungiblePositionManager.d.ts +976 -10
  31. package/dist/nonfungiblePositionManager.d.ts.map +1 -1
  32. package/dist/payments.d.ts +95 -6
  33. package/dist/payments.d.ts.map +1 -1
  34. package/dist/quoter.d.ts +385 -4
  35. package/dist/quoter.d.ts.map +1 -1
  36. package/dist/selfPermit.d.ts +128 -8
  37. package/dist/selfPermit.d.ts.map +1 -1
  38. package/dist/staker.d.ts +549 -3
  39. package/dist/staker.d.ts.map +1 -1
  40. package/dist/swapRouter.d.ts +452 -2
  41. package/dist/swapRouter.d.ts.map +1 -1
  42. package/dist/utils/calldata.d.ts +4 -3
  43. package/dist/utils/calldata.d.ts.map +1 -1
  44. package/dist/utils/computePoolAddress.d.ts +4 -3
  45. package/dist/utils/computePoolAddress.d.ts.map +1 -1
  46. package/dist/utils/encodeRouteToPath.d.ts +3 -2
  47. package/dist/utils/encodeRouteToPath.d.ts.map +1 -1
  48. package/dist/utils/encodeSqrtRatioX96.d.ts +1 -1
  49. package/dist/utils/encodeSqrtRatioX96.d.ts.map +1 -1
  50. package/dist/utils/feeCalculator.d.ts +5 -5
  51. package/dist/utils/feeCalculator.d.ts.map +1 -1
  52. package/dist/utils/parseProtocolFees.d.ts +1 -1
  53. package/dist/utils/parseProtocolFees.d.ts.map +1 -1
  54. package/dist/utils/positionMath.d.ts.map +1 -1
  55. package/dist/utils/priceTickConversions.d.ts +1 -1
  56. package/dist/utils/priceTickConversions.d.ts.map +1 -1
  57. package/package.json +6 -15
package/dist/index.js CHANGED
@@ -1,27 +1,61 @@
1
1
  'use strict';
2
2
 
3
3
  var sdk = require('@pancakeswap/sdk');
4
- var invariant11 = require('tiny-invariant');
4
+ var invariant9 = require('tiny-invariant');
5
5
  var swapSdkCore = require('@pancakeswap/swap-sdk-core');
6
- var abi = require('@ethersproject/abi');
7
- var address = require('@ethersproject/address');
8
- var solidity = require('@ethersproject/solidity');
6
+ var viem = require('viem');
9
7
 
10
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
9
 
12
- var invariant11__default = /*#__PURE__*/_interopDefault(invariant11);
10
+ var invariant9__default = /*#__PURE__*/_interopDefault(invariant9);
13
11
 
14
12
  // src/entities/pool.ts
15
13
  var FACTORY_ADDRESS = "0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865";
14
+ var FACTORY_ADDRESSES = {
15
+ [sdk.ChainId.ETHEREUM]: FACTORY_ADDRESS,
16
+ [sdk.ChainId.GOERLI]: FACTORY_ADDRESS,
17
+ [sdk.ChainId.BSC]: FACTORY_ADDRESS,
18
+ [sdk.ChainId.BSC_TESTNET]: FACTORY_ADDRESS,
19
+ // TODO: new chains
20
+ [sdk.ChainId.ARBITRUM_ONE]: FACTORY_ADDRESS,
21
+ [sdk.ChainId.ARBITRUM_GOERLI]: "0xBA40c83026213F9cbc79998752721a0312bdB74a",
22
+ [sdk.ChainId.POLYGON_ZKEVM]: FACTORY_ADDRESS,
23
+ [sdk.ChainId.POLYGON_ZKEVM_TESTNET]: "0x2430dbd123BC40f8Be6110065a448C1aA0619Cb1",
24
+ [sdk.ChainId.ZKSYNC]: "0x",
25
+ [sdk.ChainId.ZKSYNC_TESTNET]: "0x57d01Fbde077C04381a28840A24aCbEeF8314062",
26
+ [sdk.ChainId.LINEA_TESTNET]: "0x02a84c1b3BBD7401a5f7fa98a384EBC70bB5749E"
27
+ };
16
28
  var DEPLOYER_ADDRESS = "0x41ff9AA7e16B8B1a8a8dc4f0eFacd93D02d071c9";
17
29
  var DEPLOYER_ADDRESSES = {
18
30
  [sdk.ChainId.ETHEREUM]: DEPLOYER_ADDRESS,
19
31
  [sdk.ChainId.GOERLI]: DEPLOYER_ADDRESS,
20
32
  [sdk.ChainId.BSC]: DEPLOYER_ADDRESS,
21
- [sdk.ChainId.BSC_TESTNET]: DEPLOYER_ADDRESS
33
+ [sdk.ChainId.BSC_TESTNET]: DEPLOYER_ADDRESS,
34
+ // TODO: new chains
35
+ [sdk.ChainId.ARBITRUM_ONE]: DEPLOYER_ADDRESS,
36
+ [sdk.ChainId.ARBITRUM_GOERLI]: "0xbC465fbf687e4184103b67Ed86557A8155FA4343",
37
+ [sdk.ChainId.POLYGON_ZKEVM]: DEPLOYER_ADDRESS,
38
+ [sdk.ChainId.POLYGON_ZKEVM_TESTNET]: "0x86808Be3f426C9B4c8C706bCDe29dBC036A1259B",
39
+ [sdk.ChainId.ZKSYNC]: "0x",
40
+ [sdk.ChainId.ZKSYNC_TESTNET]: "0x71df5b7ea5355180EAb2A54de8aA534016040008",
41
+ [sdk.ChainId.LINEA_TESTNET]: "0xdAecee3C08e953Bd5f89A5Cc90ac560413d709E3"
22
42
  };
23
43
  var ADDRESS_ZERO = "0x0000000000000000000000000000000000000000";
24
44
  var POOL_INIT_CODE_HASH = "0x6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2";
45
+ var POOL_INIT_CODE_HASHES = {
46
+ [sdk.ChainId.ETHEREUM]: POOL_INIT_CODE_HASH,
47
+ [sdk.ChainId.GOERLI]: POOL_INIT_CODE_HASH,
48
+ [sdk.ChainId.BSC]: POOL_INIT_CODE_HASH,
49
+ [sdk.ChainId.BSC_TESTNET]: POOL_INIT_CODE_HASH,
50
+ [sdk.ChainId.ARBITRUM_ONE]: POOL_INIT_CODE_HASH,
51
+ [sdk.ChainId.ARBITRUM_GOERLI]: POOL_INIT_CODE_HASH,
52
+ [sdk.ChainId.POLYGON_ZKEVM]: POOL_INIT_CODE_HASH,
53
+ [sdk.ChainId.POLYGON_ZKEVM_TESTNET]: POOL_INIT_CODE_HASH,
54
+ // TODO: new chains
55
+ [sdk.ChainId.ZKSYNC]: "0x01001487f1c11a662dda518635f8e1f03a41f505cbf7d981c899ba11bf847a8a",
56
+ [sdk.ChainId.ZKSYNC_TESTNET]: "0x01001487f1c11a662dda518635f8e1f03a41f505cbf7d981c899ba11bf847a8a",
57
+ [sdk.ChainId.LINEA_TESTNET]: POOL_INIT_CODE_HASH
58
+ };
25
59
  var FeeAmount = /* @__PURE__ */ ((FeeAmount4) => {
26
60
  FeeAmount4[FeeAmount4["LOWEST"] = 100] = "LOWEST";
27
61
  FeeAmount4[FeeAmount4["LOW"] = 500] = "LOW";
@@ -44,6 +78,20 @@ var MAX_FEE = 10n ** 6n;
44
78
  var ONE_HUNDRED_PERCENT = new swapSdkCore.Percent("1");
45
79
  var ZERO_PERCENT = new swapSdkCore.Percent("0");
46
80
  var Q128 = 2n ** 128n;
81
+ function getCreate2Address(from_, salt_, initCodeHash) {
82
+ const from = viem.toBytes(viem.getAddress(from_));
83
+ const salt = viem.pad(viem.isBytes(salt_) ? salt_ : viem.toBytes(salt_), {
84
+ size: 32
85
+ });
86
+ return viem.getAddress(viem.slice(viem.keccak256(viem.concat([viem.toBytes("0xff"), from, salt, viem.toBytes(initCodeHash)])), 12));
87
+ }
88
+ var EMPTY_INPU_HASH = "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
89
+ var ZKSYNC_PREFIX = "0x2020dba91b30cc0006188af794c2fb30dd8520db7e2c088b7fc7c103c00ca494";
90
+ function getCreate2AddressZkSync(from, salt, initCodeHash) {
91
+ return viem.getAddress(
92
+ viem.keccak256(viem.concat([ZKSYNC_PREFIX, viem.pad(from, { size: 32 }), salt, initCodeHash, EMPTY_INPU_HASH])).slice(26)
93
+ );
94
+ }
47
95
  function computePoolAddress({
48
96
  deployerAddress,
49
97
  tokenA,
@@ -52,13 +100,20 @@ function computePoolAddress({
52
100
  initCodeHashManualOverride
53
101
  }) {
54
102
  const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
55
- return address.getCreate2Address(
103
+ const salt = viem.keccak256(
104
+ viem.encodeAbiParameters(viem.parseAbiParameters(["address, address, uint24"]), [token0.address, token1.address, fee])
105
+ );
106
+ if (token0.chainId === sdk.ChainId.ZKSYNC || token0.chainId === sdk.ChainId.ZKSYNC_TESTNET) {
107
+ return getCreate2AddressZkSync(
108
+ deployerAddress,
109
+ salt,
110
+ initCodeHashManualOverride ?? POOL_INIT_CODE_HASHES[token0.chainId]
111
+ );
112
+ }
113
+ return getCreate2Address(
56
114
  deployerAddress,
57
- solidity.keccak256(
58
- ["bytes"],
59
- [abi.defaultAbiCoder.encode(["address", "address", "uint24"], [token0.address, token1.address, fee])]
60
- ),
61
- initCodeHashManualOverride ?? POOL_INIT_CODE_HASH
115
+ salt,
116
+ initCodeHashManualOverride ?? POOL_INIT_CODE_HASHES[token0.chainId]
62
117
  );
63
118
  }
64
119
 
@@ -95,11 +150,11 @@ var FullMath = class {
95
150
  var MaxUint160 = 2n ** 160n - ONE;
96
151
  function multiplyIn256(x, y) {
97
152
  const product = x * y;
98
- return product & sdk.MaxUint256;
153
+ return product & swapSdkCore.MaxUint256;
99
154
  }
100
155
  function addIn256(x, y) {
101
156
  const sum = x + y;
102
- return sum & sdk.MaxUint256;
157
+ return sum & swapSdkCore.MaxUint256;
103
158
  }
104
159
  var SqrtPriceMath = class {
105
160
  /**
@@ -124,13 +179,13 @@ var SqrtPriceMath = class {
124
179
  return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, Q96) : liquidity * (sqrtRatioBX96 - sqrtRatioAX96) / Q96;
125
180
  }
126
181
  static getNextSqrtPriceFromInput(sqrtPX96, liquidity, amountIn, zeroForOne) {
127
- invariant11__default.default(sqrtPX96 > ZERO);
128
- invariant11__default.default(liquidity > ZERO);
182
+ invariant9__default.default(sqrtPX96 > ZERO);
183
+ invariant9__default.default(liquidity > ZERO);
129
184
  return zeroForOne ? this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
130
185
  }
131
186
  static getNextSqrtPriceFromOutput(sqrtPX96, liquidity, amountOut, zeroForOne) {
132
- invariant11__default.default(sqrtPX96 > ZERO);
133
- invariant11__default.default(liquidity > ZERO);
187
+ invariant9__default.default(sqrtPX96 > ZERO);
188
+ invariant9__default.default(liquidity > ZERO);
134
189
  return zeroForOne ? this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
135
190
  }
136
191
  static getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amount, add) {
@@ -148,8 +203,8 @@ var SqrtPriceMath = class {
148
203
  return FullMath.mulDivRoundingUp(numerator1, ONE, numerator1 / sqrtPX96 + amount);
149
204
  }
150
205
  const product = multiplyIn256(amount, sqrtPX96);
151
- invariant11__default.default(product / amount === sqrtPX96);
152
- invariant11__default.default(numerator1 > product);
206
+ invariant9__default.default(product / amount === sqrtPX96);
207
+ invariant9__default.default(numerator1 > product);
153
208
  const denominator = numerator1 - product;
154
209
  return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator);
155
210
  }
@@ -159,7 +214,7 @@ var SqrtPriceMath = class {
159
214
  return sqrtPX96 + quotient2;
160
215
  }
161
216
  const quotient = FullMath.mulDivRoundingUp(amount, Q96, liquidity);
162
- invariant11__default.default(sqrtPX96 > quotient);
217
+ invariant9__default.default(sqrtPX96 > quotient);
163
218
  return sqrtPX96 - quotient;
164
219
  }
165
220
  };
@@ -227,8 +282,8 @@ var SwapMath = class {
227
282
  var TWO = 2n;
228
283
  var POWERS_OF_2 = [128, 64, 32, 16, 8, 4, 2, 1].map((pow) => [pow, TWO ** BigInt(pow)]);
229
284
  function mostSignificantBit(x) {
230
- invariant11__default.default(x > ZERO, "ZERO");
231
- invariant11__default.default(x <= sdk.MaxUint256, "MAX");
285
+ invariant9__default.default(x > ZERO, "ZERO");
286
+ invariant9__default.default(x <= swapSdkCore.MaxUint256, "MAX");
232
287
  let msb = 0;
233
288
  for (const [power, min] of POWERS_OF_2) {
234
289
  if (x >= min) {
@@ -255,7 +310,7 @@ var _TickMath = class {
255
310
  * @param tick the tick for which to compute the sqrt ratio
256
311
  */
257
312
  static getSqrtRatioAtTick(tick) {
258
- invariant11__default.default(tick >= _TickMath.MIN_TICK && tick <= _TickMath.MAX_TICK && Number.isInteger(tick), "TICK");
313
+ invariant9__default.default(tick >= _TickMath.MIN_TICK && tick <= _TickMath.MAX_TICK && Number.isInteger(tick), "TICK");
259
314
  const absTick = tick < 0 ? tick * -1 : tick;
260
315
  let ratio = (absTick & 1) != 0 ? BigInt("0xfffcb933bd6fad37aa2d162d1a594001") : BigInt("0x100000000000000000000000000000000");
261
316
  if ((absTick & 2) != 0)
@@ -297,7 +352,7 @@ var _TickMath = class {
297
352
  if ((absTick & 524288) != 0)
298
353
  ratio = mulShift(ratio, "0x48a170391f7dc42444e8fa2");
299
354
  if (tick > 0)
300
- ratio = sdk.MaxUint256 / ratio;
355
+ ratio = swapSdkCore.MaxUint256 / ratio;
301
356
  return ratio % Q32 > ZERO ? ratio / Q32 + ONE : ratio / Q32;
302
357
  }
303
358
  /**
@@ -306,7 +361,7 @@ var _TickMath = class {
306
361
  * @param sqrtRatioX96 the sqrt ratio as a Q64.96 for which to compute the tick
307
362
  */
308
363
  static getTickAtSqrtRatio(sqrtRatioX96) {
309
- invariant11__default.default(sqrtRatioX96 >= _TickMath.MIN_SQRT_RATIO && sqrtRatioX96 < _TickMath.MAX_SQRT_RATIO, "SQRT_RATIO");
364
+ invariant9__default.default(sqrtRatioX96 >= _TickMath.MIN_SQRT_RATIO && sqrtRatioX96 < _TickMath.MAX_SQRT_RATIO, "SQRT_RATIO");
310
365
  const sqrtRatioX128 = sqrtRatioX96 << 32n;
311
366
  const msb = mostSignificantBit(sqrtRatioX128);
312
367
  let r;
@@ -380,25 +435,25 @@ var TickList = class {
380
435
  constructor() {
381
436
  }
382
437
  static validateList(ticks, tickSpacing) {
383
- invariant11__default.default(tickSpacing > 0, "TICK_SPACING_NONZERO");
384
- invariant11__default.default(
438
+ invariant9__default.default(tickSpacing > 0, "TICK_SPACING_NONZERO");
439
+ invariant9__default.default(
385
440
  ticks.every(({ index }) => index % tickSpacing === 0),
386
441
  "TICK_SPACING"
387
442
  );
388
- invariant11__default.default(ticks.reduce((accumulator, { liquidityNet }) => accumulator + liquidityNet, ZERO) === ZERO, "ZERO_NET");
389
- invariant11__default.default(isSorted(ticks, tickComparator), "SORTED");
443
+ invariant9__default.default(ticks.reduce((accumulator, { liquidityNet }) => accumulator + liquidityNet, ZERO) === ZERO, "ZERO_NET");
444
+ invariant9__default.default(isSorted(ticks, tickComparator), "SORTED");
390
445
  }
391
446
  static isBelowSmallest(ticks, tick) {
392
- invariant11__default.default(ticks.length > 0, "LENGTH");
447
+ invariant9__default.default(ticks.length > 0, "LENGTH");
393
448
  return tick < ticks[0].index;
394
449
  }
395
450
  static isAtOrAboveLargest(ticks, tick) {
396
- invariant11__default.default(ticks.length > 0, "LENGTH");
451
+ invariant9__default.default(ticks.length > 0, "LENGTH");
397
452
  return tick >= ticks[ticks.length - 1].index;
398
453
  }
399
454
  static getTick(ticks, index) {
400
455
  const tick = ticks[this.binarySearch(ticks, index)];
401
- invariant11__default.default(tick.index === index, "NOT_CONTAINED");
456
+ invariant9__default.default(tick.index === index, "NOT_CONTAINED");
402
457
  return tick;
403
458
  }
404
459
  /**
@@ -408,7 +463,7 @@ var TickList = class {
408
463
  * @private
409
464
  */
410
465
  static binarySearch(ticks, tick) {
411
- invariant11__default.default(!this.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
466
+ invariant9__default.default(!this.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
412
467
  let l = 0;
413
468
  let r = ticks.length - 1;
414
469
  let i;
@@ -426,14 +481,14 @@ var TickList = class {
426
481
  }
427
482
  static nextInitializedTick(ticks, tick, lte) {
428
483
  if (lte) {
429
- invariant11__default.default(!TickList.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
484
+ invariant9__default.default(!TickList.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
430
485
  if (TickList.isAtOrAboveLargest(ticks, tick)) {
431
486
  return ticks[ticks.length - 1];
432
487
  }
433
488
  const index2 = this.binarySearch(ticks, tick);
434
489
  return ticks[index2];
435
490
  }
436
- invariant11__default.default(!this.isAtOrAboveLargest(ticks, tick), "AT_OR_ABOVE_LARGEST");
491
+ invariant9__default.default(!this.isAtOrAboveLargest(ticks, tick), "AT_OR_ABOVE_LARGEST");
437
492
  if (this.isBelowSmallest(ticks, tick)) {
438
493
  return ticks[0];
439
494
  }
@@ -470,44 +525,219 @@ var TickList = class {
470
525
  return Math.abs(beforeIndex - afterIndex);
471
526
  }
472
527
  };
528
+ var Tick = class {
529
+ constructor({ index, liquidityGross, liquidityNet }) {
530
+ invariant9__default.default(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK, "TICK");
531
+ this.index = index;
532
+ this.liquidityGross = BigInt(liquidityGross);
533
+ this.liquidityNet = BigInt(liquidityNet);
534
+ }
535
+ };
473
536
 
474
- // src/utils/calldata.ts
475
- function toHex(bigintIsh) {
476
- const bigInt = BigInt(bigintIsh);
477
- let hex = bigInt.toString(16);
478
- if (hex.length % 2 !== 0) {
479
- hex = `0${hex}`;
537
+ // src/entities/tickListDataProvider.ts
538
+ var TickListDataProvider = class {
539
+ constructor(ticks) {
540
+ const ticksMapped = ticks.map((t) => t instanceof Tick ? t : new Tick(t));
541
+ this.ticks = ticksMapped;
480
542
  }
481
- return `0x${hex}`;
482
- }
483
- function encodeRouteToPath(route, exactOutput) {
484
- const firstInputToken = route.input.wrapped;
485
- const { path, types } = route.pools.reduce(
486
- ({ inputToken, path: path2, types: types2 }, pool, index) => {
487
- const outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
488
- if (index === 0) {
489
- return {
490
- inputToken: outputToken,
491
- types: ["address", "uint24", "address"],
492
- path: [inputToken.address, pool.fee, outputToken.address]
493
- };
543
+ async getTick(tick) {
544
+ return TickList.getTick(this.ticks, tick);
545
+ }
546
+ async nextInitializedTickWithinOneWord(tick, lte, tickSpacing) {
547
+ return TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing);
548
+ }
549
+ };
550
+
551
+ // src/entities/pool.ts
552
+ var NO_TICK_DATA_PROVIDER_DEFAULT = new NoTickDataProvider();
553
+ var Pool = class {
554
+ static getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, deployerAddressOverride) {
555
+ return computePoolAddress({
556
+ deployerAddress: deployerAddressOverride ?? DEPLOYER_ADDRESSES[tokenA.chainId],
557
+ fee,
558
+ tokenA,
559
+ tokenB,
560
+ initCodeHashManualOverride
561
+ });
562
+ }
563
+ /**
564
+ * Construct a pool
565
+ * @param tokenA One of the tokens in the pool
566
+ * @param tokenB The other token in the pool
567
+ * @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
568
+ * @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0
569
+ * @param liquidity The current value of in range liquidity
570
+ * @param tickCurrent The current tick of the pool
571
+ * @param ticks The current state of the pool ticks or a data provider that can return tick data
572
+ */
573
+ constructor(tokenA, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks = NO_TICK_DATA_PROVIDER_DEFAULT) {
574
+ invariant9__default.default(Number.isInteger(fee) && fee < 1e6, "FEE");
575
+ [this.token0, this.token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
576
+ this.fee = fee;
577
+ this.sqrtRatioX96 = BigInt(sqrtRatioX96);
578
+ this.liquidity = BigInt(liquidity);
579
+ this.tickCurrent = tickCurrent;
580
+ this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks) : ticks;
581
+ }
582
+ /**
583
+ * Returns true if the token is either token0 or token1
584
+ * @param token The token to check
585
+ * @returns True if token is either token0 or token
586
+ */
587
+ involvesToken(token) {
588
+ return token.equals(this.token0) || token.equals(this.token1);
589
+ }
590
+ /**
591
+ * Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
592
+ */
593
+ get token0Price() {
594
+ return this._token0Price ?? (this._token0Price = new sdk.Price(this.token0, this.token1, Q192, this.sqrtRatioX96 * this.sqrtRatioX96));
595
+ }
596
+ /**
597
+ * Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
598
+ */
599
+ get token1Price() {
600
+ return this._token1Price ?? (this._token1Price = new sdk.Price(this.token1, this.token0, this.sqrtRatioX96 * this.sqrtRatioX96, Q192));
601
+ }
602
+ /**
603
+ * Return the price of the given token in terms of the other token in the pool.
604
+ * @param token The token to return price of
605
+ * @returns The price of the given token, in terms of the other.
606
+ */
607
+ priceOf(token) {
608
+ invariant9__default.default(this.involvesToken(token), "TOKEN");
609
+ return token.equals(this.token0) ? this.token0Price : this.token1Price;
610
+ }
611
+ /**
612
+ * Returns the chain ID of the tokens in the pool.
613
+ */
614
+ get chainId() {
615
+ return this.token0.chainId;
616
+ }
617
+ /**
618
+ * Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
619
+ * @param inputAmount The input amount for which to quote the output amount
620
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
621
+ * @returns The output amount and the pool with updated state
622
+ */
623
+ async getOutputAmount(inputAmount, sqrtPriceLimitX96) {
624
+ invariant9__default.default(this.involvesToken(inputAmount.currency), "TOKEN");
625
+ const zeroForOne = inputAmount.currency.equals(this.token0);
626
+ const {
627
+ amountCalculated: outputAmount,
628
+ sqrtRatioX96,
629
+ liquidity,
630
+ tickCurrent
631
+ } = await this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96);
632
+ const outputToken = zeroForOne ? this.token1 : this.token0;
633
+ return [
634
+ sdk.CurrencyAmount.fromRawAmount(outputToken, outputAmount * NEGATIVE_ONE),
635
+ new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)
636
+ ];
637
+ }
638
+ /**
639
+ * Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
640
+ * @param outputAmount the output amount for which to quote the input amount
641
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
642
+ * @returns The input amount and the pool with updated state
643
+ */
644
+ async getInputAmount(outputAmount, sqrtPriceLimitX96) {
645
+ invariant9__default.default(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency), "TOKEN");
646
+ const zeroForOne = outputAmount.currency.equals(this.token1);
647
+ const {
648
+ amountSpecifiedRemaining,
649
+ amountCalculated: inputAmount,
650
+ sqrtRatioX96,
651
+ liquidity,
652
+ tickCurrent
653
+ } = await this.swap(zeroForOne, outputAmount.quotient * NEGATIVE_ONE, sqrtPriceLimitX96);
654
+ invariant9__default.default(amountSpecifiedRemaining === ZERO, "INSUFICIENT_LIQUIDITY");
655
+ const inputToken = zeroForOne ? this.token0 : this.token1;
656
+ return [
657
+ sdk.CurrencyAmount.fromRawAmount(inputToken, inputAmount),
658
+ new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)
659
+ ];
660
+ }
661
+ /**
662
+ * Executes a swap
663
+ * @param zeroForOne Whether the amount in is token0 or token1
664
+ * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
665
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
666
+ * @returns amountCalculated
667
+ * @returns sqrtRatioX96
668
+ * @returns liquidity
669
+ * @returns tickCurrent
670
+ */
671
+ async swap(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
672
+ if (!sqrtPriceLimitX96)
673
+ sqrtPriceLimitX96 = zeroForOne ? TickMath.MIN_SQRT_RATIO + ONE : TickMath.MAX_SQRT_RATIO - ONE;
674
+ if (zeroForOne) {
675
+ invariant9__default.default(sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO, "RATIO_MIN");
676
+ invariant9__default.default(sqrtPriceLimitX96 < this.sqrtRatioX96, "RATIO_CURRENT");
677
+ } else {
678
+ invariant9__default.default(sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO, "RATIO_MAX");
679
+ invariant9__default.default(sqrtPriceLimitX96 > this.sqrtRatioX96, "RATIO_CURRENT");
680
+ }
681
+ const exactInput = amountSpecified >= ZERO;
682
+ const state = {
683
+ amountSpecifiedRemaining: amountSpecified,
684
+ amountCalculated: ZERO,
685
+ sqrtPriceX96: this.sqrtRatioX96,
686
+ tick: this.tickCurrent,
687
+ liquidity: this.liquidity
688
+ };
689
+ while (state.amountSpecifiedRemaining !== ZERO && state.sqrtPriceX96 != sqrtPriceLimitX96) {
690
+ const step = {};
691
+ step.sqrtPriceStartX96 = state.sqrtPriceX96;
692
+ [step.tickNext, step.initialized] = await this.tickDataProvider.nextInitializedTickWithinOneWord(
693
+ state.tick,
694
+ zeroForOne,
695
+ this.tickSpacing
696
+ );
697
+ if (step.tickNext < TickMath.MIN_TICK) {
698
+ step.tickNext = TickMath.MIN_TICK;
699
+ } else if (step.tickNext > TickMath.MAX_TICK) {
700
+ step.tickNext = TickMath.MAX_TICK;
494
701
  }
495
- return {
496
- inputToken: outputToken,
497
- types: [...types2, "uint24", "address"],
498
- path: [...path2, pool.fee, outputToken.address]
499
- };
500
- },
501
- { inputToken: firstInputToken, path: [], types: [] }
502
- );
503
- return exactOutput ? solidity.pack(types.reverse(), path.reverse()) : solidity.pack(types, path);
504
- }
505
- function encodeSqrtRatioX96(amount1, amount0) {
506
- const numerator = BigInt(amount1) << 192n;
507
- const denominator = BigInt(amount0);
508
- const ratioX192 = numerator / denominator;
509
- return sdk.sqrt(ratioX192);
510
- }
702
+ step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
703
+ [state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.computeSwapStep(
704
+ state.sqrtPriceX96,
705
+ (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96,
706
+ state.liquidity,
707
+ state.amountSpecifiedRemaining,
708
+ this.fee
709
+ );
710
+ if (exactInput) {
711
+ state.amountSpecifiedRemaining = state.amountSpecifiedRemaining - (step.amountIn + step.feeAmount);
712
+ state.amountCalculated = state.amountCalculated - step.amountOut;
713
+ } else {
714
+ state.amountSpecifiedRemaining = state.amountSpecifiedRemaining + step.amountOut;
715
+ state.amountCalculated = state.amountCalculated + (step.amountIn + step.feeAmount);
716
+ }
717
+ if (state.sqrtPriceX96 === step.sqrtPriceNextX96) {
718
+ if (step.initialized) {
719
+ let liquidityNet = BigInt((await this.tickDataProvider.getTick(step.tickNext)).liquidityNet);
720
+ if (zeroForOne)
721
+ liquidityNet = liquidityNet * NEGATIVE_ONE;
722
+ state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
723
+ }
724
+ state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
725
+ } else if (state.sqrtPriceX96 !== step.sqrtPriceStartX96) {
726
+ state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
727
+ }
728
+ }
729
+ return {
730
+ amountSpecifiedRemaining: state.amountSpecifiedRemaining,
731
+ amountCalculated: state.amountCalculated,
732
+ sqrtRatioX96: state.sqrtPriceX96,
733
+ liquidity: state.liquidity,
734
+ tickCurrent: state.tick
735
+ };
736
+ }
737
+ get tickSpacing() {
738
+ return TICK_SPACINGS[this.fee];
739
+ }
740
+ };
511
741
 
512
742
  // src/utils/maxLiquidityForAmounts.ts
513
743
  function maxLiquidityForAmount0Imprecise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
@@ -550,36 +780,18 @@ function maxLiquidityForAmounts(sqrtRatioCurrentX96, sqrtRatioAX96, sqrtRatioBX9
550
780
  }
551
781
  return maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
552
782
  }
553
- function nearestUsableTick(tick, tickSpacing) {
554
- invariant11__default.default(Number.isInteger(tick) && Number.isInteger(tickSpacing), "INTEGERS");
555
- invariant11__default.default(tickSpacing > 0, "TICK_SPACING");
556
- invariant11__default.default(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK, "TICK_BOUND");
557
- const rounded = Math.round(tick / tickSpacing) * tickSpacing;
558
- if (rounded < TickMath.MIN_TICK)
559
- return rounded + tickSpacing;
560
- if (rounded > TickMath.MAX_TICK)
561
- return rounded - tickSpacing;
562
- return rounded;
783
+ function encodeSqrtRatioX96(amount1, amount0) {
784
+ const numerator = BigInt(amount1) << 192n;
785
+ const denominator = BigInt(amount0);
786
+ const ratioX192 = numerator / denominator;
787
+ return swapSdkCore.sqrt(ratioX192);
563
788
  }
564
789
 
565
- // src/utils/position.ts
566
- var PositionLibrary = class {
567
- /**
568
- * Cannot be constructed.
569
- */
570
- constructor() {
571
- }
572
- // replicates the portions of Position#update required to compute unaccounted fees
573
- static getTokensOwed(feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, feeGrowthInside0X128, feeGrowthInside1X128) {
574
- const tokensOwed0 = subIn256(feeGrowthInside0X128, feeGrowthInside0LastX128) * liquidity / Q128;
575
- const tokensOwed1 = subIn256(feeGrowthInside1X128, feeGrowthInside1LastX128) * liquidity / Q128;
576
- return [tokensOwed0, tokensOwed1];
577
- }
578
- };
790
+ // src/utils/priceTickConversions.ts
579
791
  function tickToPrice(baseToken, quoteToken, tick) {
580
792
  const sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
581
793
  const ratioX192 = sqrtRatioX96 * sqrtRatioX96;
582
- return baseToken.sortsBefore(quoteToken) ? new sdk.Price(baseToken, quoteToken, Q192, ratioX192) : new sdk.Price(baseToken, quoteToken, ratioX192, Q192);
794
+ return baseToken.sortsBefore(quoteToken) ? new swapSdkCore.Price(baseToken, quoteToken, Q192, ratioX192) : new swapSdkCore.Price(baseToken, quoteToken, ratioX192, Q192);
583
795
  }
584
796
  function priceToClosestTick(price) {
585
797
  const sorted = price.baseCurrency.sortsBefore(price.quoteCurrency);
@@ -596,47 +808,6 @@ function priceToClosestTick(price) {
596
808
  return tick;
597
809
  }
598
810
 
599
- // src/utils/tickLibrary.ts
600
- var Q256 = 2n ** 256n;
601
- function subIn256(x, y) {
602
- const difference = x - y;
603
- if (difference < ZERO) {
604
- return Q256 + difference;
605
- }
606
- return difference;
607
- }
608
- var TickLibrary = class {
609
- /**
610
- * Cannot be constructed.
611
- */
612
- constructor() {
613
- }
614
- static getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) {
615
- let feeGrowthBelow0X128;
616
- let feeGrowthBelow1X128;
617
- if (tickCurrent >= tickLower) {
618
- feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128;
619
- feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128;
620
- } else {
621
- feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128);
622
- feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128);
623
- }
624
- let feeGrowthAbove0X128;
625
- let feeGrowthAbove1X128;
626
- if (tickCurrent < tickUpper) {
627
- feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128;
628
- feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128;
629
- } else {
630
- feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128);
631
- feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128);
632
- }
633
- return [
634
- subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128),
635
- subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)
636
- ];
637
- }
638
- };
639
-
640
811
  // src/utils/positionMath.ts
641
812
  function getToken0Amount(tickCurrent, tickLower, tickUpper, sqrtRatioX96, liquidity) {
642
813
  if (tickCurrent < tickLower) {
@@ -670,914 +841,514 @@ var PositionMath = {
670
841
  getToken0Amount,
671
842
  getToken1Amount
672
843
  };
673
- function parseNumberToFraction(num, precision = 6) {
674
- const scalar = 10 ** precision;
675
- return new swapSdkCore.Fraction(BigInt(Math.floor(num * scalar)), BigInt(scalar));
676
- }
677
844
 
678
- // src/utils/feeCalculator.ts
679
- var FeeCalculator = {
680
- getEstimatedLPFee,
681
- getEstimatedLPFeeByAmounts,
682
- getLiquidityFromTick,
683
- getLiquidityFromSqrtRatioX96,
684
- getAverageLiquidity,
685
- getLiquidityBySingleAmount,
686
- getDependentAmount,
687
- getLiquidityByAmountsAndPrice,
688
- getAmountsByLiquidityAndPrice,
689
- getAmountsAtNewPrice
690
- };
691
- function getEstimatedLPFeeWithProtocolFee({ amount, currency, ...rest }) {
692
- return getEstimatedLPFeeByAmountsWithProtocolFee({
693
- ...rest,
694
- amountA: amount,
695
- amountB: sdk.CurrencyAmount.fromRawAmount(currency, sdk.MaxUint256)
696
- });
697
- }
698
- function getEstimatedLPFee({ amount, currency, ...rest }) {
699
- return getEstimatedLPFeeByAmounts({
700
- ...rest,
701
- amountA: amount,
702
- amountB: sdk.CurrencyAmount.fromRawAmount(currency, sdk.MaxUint256)
703
- });
704
- }
705
- function getEstimatedLPFeeByAmountsWithProtocolFee(options) {
706
- try {
707
- return tryGetEstimatedLPFeeByAmounts(options);
708
- } catch (e) {
709
- console.error(e);
710
- return new sdk.Fraction(sdk.ZERO);
711
- }
712
- }
713
- function getEstimatedLPFeeByAmounts({ protocolFee = ZERO_PERCENT, ...rest }) {
714
- try {
715
- const fee = tryGetEstimatedLPFeeByAmounts(rest);
716
- return ONE_HUNDRED_PERCENT.subtract(protocolFee).multiply(fee).asFraction;
717
- } catch (e) {
718
- console.error(e);
719
- return new sdk.Fraction(sdk.ZERO);
845
+ // src/entities/position.ts
846
+ var Position = class {
847
+ /**
848
+ * Constructs a position for a given pool with the given liquidity
849
+ * @param pool For which pool the liquidity is assigned
850
+ * @param liquidity The amount of liquidity that is in the position
851
+ * @param tickLower The lower tick of the position
852
+ * @param tickUpper The upper tick of the position
853
+ */
854
+ constructor({ pool, liquidity, tickLower, tickUpper }) {
855
+ // cached resuts for the getters
856
+ this._token0Amount = null;
857
+ this._token1Amount = null;
858
+ this._mintAmounts = null;
859
+ invariant9__default.default(tickLower < tickUpper, "TICK_ORDER");
860
+ invariant9__default.default(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0, "TICK_LOWER");
861
+ invariant9__default.default(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0, "TICK_UPPER");
862
+ this.pool = pool;
863
+ this.tickLower = tickLower;
864
+ this.tickUpper = tickUpper;
865
+ this.liquidity = BigInt(liquidity);
720
866
  }
721
- }
722
- function tryGetEstimatedLPFeeByAmounts({
723
- amountA,
724
- amountB,
725
- volume24H,
726
- sqrtRatioX96,
727
- tickLower,
728
- tickUpper,
729
- mostActiveLiquidity,
730
- fee,
731
- insidePercentage = ONE_HUNDRED_PERCENT
732
- }) {
733
- invariant11__default.default(!Number.isNaN(fee) && fee >= 0, "INVALID_FEE");
734
- const tickCurrent = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
735
- if (tickCurrent < tickLower || tickCurrent > tickUpper) {
736
- return new sdk.Fraction(sdk.ZERO);
867
+ /**
868
+ * Returns the price of token0 at the lower tick
869
+ */
870
+ get token0PriceLower() {
871
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickLower);
737
872
  }
738
- const liquidity = FeeCalculator.getLiquidityByAmountsAndPrice({
739
- amountA,
740
- amountB,
741
- tickUpper,
742
- tickLower,
743
- sqrtRatioX96
744
- });
745
- return insidePercentage.multiply(parseNumberToFraction(volume24H).multiply(BigInt(fee)).multiply(liquidity)).divide(MAX_FEE * (liquidity + mostActiveLiquidity)).asFraction;
746
- }
747
- function getDependentAmount(options) {
748
- const { currency, amount, sqrtRatioX96, tickLower, tickUpper } = options;
749
- const currentTick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
750
- const liquidity = FeeCalculator.getLiquidityBySingleAmount(options);
751
- const isToken0 = currency.wrapped.sortsBefore(amount.currency.wrapped);
752
- const getTokenAmount = isToken0 ? PositionMath.getToken0Amount : PositionMath.getToken1Amount;
753
- return sdk.CurrencyAmount.fromRawAmount(
754
- currency,
755
- getTokenAmount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity)
756
- );
757
- }
758
- function getLiquidityBySingleAmount({ amount, currency, ...rest }) {
759
- return getLiquidityByAmountsAndPrice({
760
- amountA: amount,
761
- amountB: sdk.CurrencyAmount.fromRawAmount(currency, sdk.MaxUint256),
762
- ...rest
763
- });
764
- }
765
- function getLiquidityByAmountsAndPrice({
766
- amountA,
767
- amountB,
768
- tickUpper,
769
- tickLower,
770
- sqrtRatioX96
771
- }) {
772
- const isToken0 = amountA.currency.wrapped.sortsBefore(amountB.currency.wrapped);
773
- const [inputAmount0, inputAmount1] = isToken0 ? [amountA.quotient, amountB.quotient] : [amountB.quotient, amountA.quotient];
774
- const sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
775
- const sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
776
- return maxLiquidityForAmounts(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, inputAmount0, inputAmount1, true);
777
- }
778
- function getAmountsByLiquidityAndPrice(options) {
779
- const { currencyA, currencyB, liquidity, sqrtRatioX96, tickLower, tickUpper } = options;
780
- const currentTick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
781
- const isToken0 = currencyA.wrapped.sortsBefore(currencyB.wrapped);
782
- const adjustedAmount0 = PositionMath.getToken0Amount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity);
783
- const adjustedAmount1 = PositionMath.getToken1Amount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity);
784
- return [
785
- sdk.CurrencyAmount.fromRawAmount(currencyA, isToken0 ? adjustedAmount0 : adjustedAmount1),
786
- sdk.CurrencyAmount.fromRawAmount(currencyB, isToken0 ? adjustedAmount1 : adjustedAmount0)
787
- ];
788
- }
789
- function getAmountsAtNewPrice({ newSqrtRatioX96, ...rest }) {
790
- const { tickLower, tickUpper, amountA, amountB } = rest;
791
- const liquidity = FeeCalculator.getLiquidityByAmountsAndPrice(rest);
792
- return FeeCalculator.getAmountsByLiquidityAndPrice({
793
- liquidity,
794
- currencyA: amountA.currency,
795
- currencyB: amountB.currency,
796
- tickLower,
797
- tickUpper,
798
- sqrtRatioX96: newSqrtRatioX96
799
- });
800
- }
801
- function getAverageLiquidity(ticks, tickSpacing, tickLower, tickUpper) {
802
- invariant11__default.default(tickLower <= tickUpper, "INVALID_TICK_RANGE");
803
- TickList.validateList(ticks, tickSpacing);
804
- if (tickLower === tickUpper) {
805
- return FeeCalculator.getLiquidityFromTick(ticks, tickLower);
873
+ /**
874
+ * Returns the price of token0 at the upper tick
875
+ */
876
+ get token0PriceUpper() {
877
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickUpper);
806
878
  }
807
- const lowerOutOfBound = tickLower < ticks[0].index;
808
- let lastTick = lowerOutOfBound ? new Tick({ index: TickMath.MIN_TICK, liquidityNet: sdk.ZERO, liquidityGross: sdk.ZERO }) : TickList.nextInitializedTick(ticks, tickLower, true);
809
- let currentTick = TickList.nextInitializedTick(ticks, tickLower, false);
810
- let currentL = lowerOutOfBound ? sdk.ZERO : FeeCalculator.getLiquidityFromTick(ticks, currentTick.index);
811
- let weightedL = sdk.ZERO;
812
- const getWeightedLFromLastTickTo = (toTick) => currentL * BigInt(toTick - Math.max(lastTick.index, tickLower));
813
- while (currentTick.index < tickUpper) {
814
- weightedL += getWeightedLFromLastTickTo(currentTick.index);
815
- currentL += currentTick.liquidityNet;
816
- lastTick = currentTick;
817
- if (currentTick.index === ticks[ticks.length - 1].index) {
818
- break;
879
+ /**
880
+ * Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
881
+ */
882
+ get amount0() {
883
+ if (this._token0Amount === null) {
884
+ this._token0Amount = sdk.CurrencyAmount.fromRawAmount(
885
+ this.pool.token0,
886
+ PositionMath.getToken0Amount(
887
+ this.pool.tickCurrent,
888
+ this.tickLower,
889
+ this.tickUpper,
890
+ this.pool.sqrtRatioX96,
891
+ this.liquidity
892
+ )
893
+ );
819
894
  }
820
- currentTick = TickList.nextInitializedTick(ticks, currentTick.index, false);
821
- }
822
- weightedL += getWeightedLFromLastTickTo(tickUpper);
823
- return weightedL / BigInt(tickUpper - tickLower);
824
- }
825
- function getLiquidityFromSqrtRatioX96(ticks, sqrtRatioX96) {
826
- const tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
827
- return FeeCalculator.getLiquidityFromTick(ticks, tick);
828
- }
829
- function getLiquidityFromTick(ticks, tick) {
830
- let liquidity = sdk.ZERO;
831
- if (!ticks?.length)
832
- return liquidity;
833
- if (tick < ticks[0].index || tick > ticks[ticks.length - 1].index) {
834
- return liquidity;
895
+ return this._token0Amount;
835
896
  }
836
- for (let i = 0; i < ticks.length - 1; ++i) {
837
- liquidity += ticks[i].liquidityNet;
838
- const lowerTick = ticks[i].index;
839
- const upperTick = ticks[i + 1]?.index;
840
- if (lowerTick <= tick && tick <= upperTick) {
841
- break;
897
+ /**
898
+ * Returns the amount of token1 that this position's liquidity could be burned for at the current pool price
899
+ */
900
+ get amount1() {
901
+ if (this._token1Amount === null) {
902
+ this._token1Amount = sdk.CurrencyAmount.fromRawAmount(
903
+ this.pool.token1,
904
+ PositionMath.getToken1Amount(
905
+ this.pool.tickCurrent,
906
+ this.tickLower,
907
+ this.tickUpper,
908
+ this.pool.sqrtRatioX96,
909
+ this.liquidity
910
+ )
911
+ );
842
912
  }
843
- }
844
- return liquidity;
845
- }
846
- var FEE_BASE = 10n ** 4n;
847
- function parseProtocolFees(feeProtocol) {
848
- const packed = Number(feeProtocol);
849
- if (Number.isNaN(packed)) {
850
- throw new Error(`Invalid fee protocol ${feeProtocol}`);
851
- }
852
- const token0ProtocolFee = packed % 2 ** 16;
853
- const token1ProtocolFee = packed >> 16;
854
- return [new sdk.Percent(token0ProtocolFee, FEE_BASE), new sdk.Percent(token1ProtocolFee, FEE_BASE)];
855
- }
856
- function sqrtRatioX96ToPrice(sqrtRatioX96, currencyA, currencyB) {
857
- const ratioX192 = sqrtRatioX96 * sqrtRatioX96;
858
- return currencyA.wrapped.sortsBefore(currencyB.wrapped) ? new swapSdkCore.Price(currencyA.wrapped, currencyB.wrapped, Q192, ratioX192) : new swapSdkCore.Price(currencyA.wrapped, currencyB.wrapped, ratioX192, Q192);
859
- }
860
-
861
- // src/entities/tick.ts
862
- var Tick = class {
863
- constructor({ index, liquidityGross, liquidityNet }) {
864
- invariant11__default.default(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK, "TICK");
865
- this.index = index;
866
- this.liquidityGross = BigInt(liquidityGross);
867
- this.liquidityNet = BigInt(liquidityNet);
868
- }
869
- };
870
-
871
- // src/entities/tickListDataProvider.ts
872
- var TickListDataProvider = class {
873
- constructor(ticks) {
874
- const ticksMapped = ticks.map((t) => t instanceof Tick ? t : new Tick(t));
875
- this.ticks = ticksMapped;
876
- }
877
- async getTick(tick) {
878
- return TickList.getTick(this.ticks, tick);
879
- }
880
- async nextInitializedTickWithinOneWord(tick, lte, tickSpacing) {
881
- return TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing);
882
- }
883
- };
884
-
885
- // src/entities/pool.ts
886
- var NO_TICK_DATA_PROVIDER_DEFAULT = new NoTickDataProvider();
887
- var Pool = class {
888
- static getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, deployerAddressOverride) {
889
- return computePoolAddress({
890
- deployerAddress: deployerAddressOverride ?? DEPLOYER_ADDRESSES[tokenA.chainId],
891
- fee,
892
- tokenA,
893
- tokenB,
894
- initCodeHashManualOverride
895
- });
913
+ return this._token1Amount;
896
914
  }
897
915
  /**
898
- * Construct a pool
899
- * @param tokenA One of the tokens in the pool
900
- * @param tokenB The other token in the pool
901
- * @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
902
- * @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0
903
- * @param liquidity The current value of in range liquidity
904
- * @param tickCurrent The current tick of the pool
905
- * @param ticks The current state of the pool ticks or a data provider that can return tick data
916
+ * Returns the lower and upper sqrt ratios if the price 'slips' up to slippage tolerance percentage
917
+ * @param slippageTolerance The amount by which the price can 'slip' before the transaction will revert
918
+ * @returns The sqrt ratios after slippage
906
919
  */
907
- constructor(tokenA, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks = NO_TICK_DATA_PROVIDER_DEFAULT) {
908
- invariant11__default.default(Number.isInteger(fee) && fee < 1e6, "FEE");
909
- [this.token0, this.token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
910
- this.fee = fee;
911
- this.sqrtRatioX96 = BigInt(sqrtRatioX96);
912
- this.liquidity = BigInt(liquidity);
913
- this.tickCurrent = tickCurrent;
914
- this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks) : ticks;
920
+ ratiosAfterSlippage(slippageTolerance) {
921
+ const priceLower = this.pool.token0Price.asFraction.multiply(new sdk.Percent(1).subtract(slippageTolerance));
922
+ const priceUpper = this.pool.token0Price.asFraction.multiply(slippageTolerance.add(1));
923
+ let sqrtRatioX96Lower = encodeSqrtRatioX96(priceLower.numerator, priceLower.denominator);
924
+ if (sqrtRatioX96Lower <= TickMath.MIN_SQRT_RATIO) {
925
+ sqrtRatioX96Lower = TickMath.MIN_SQRT_RATIO + 1n;
926
+ }
927
+ let sqrtRatioX96Upper = encodeSqrtRatioX96(priceUpper.numerator, priceUpper.denominator);
928
+ if (sqrtRatioX96Upper >= TickMath.MAX_SQRT_RATIO) {
929
+ sqrtRatioX96Upper = TickMath.MAX_SQRT_RATIO - 1n;
930
+ }
931
+ return {
932
+ sqrtRatioX96Lower,
933
+ sqrtRatioX96Upper
934
+ };
915
935
  }
916
936
  /**
917
- * Returns true if the token is either token0 or token1
918
- * @param token The token to check
919
- * @returns True if token is either token0 or token
937
+ * Returns the minimum amounts that must be sent in order to safely mint the amount of liquidity held by the position
938
+ * with the given slippage tolerance
939
+ * @param slippageTolerance Tolerance of unfavorable slippage from the current price
940
+ * @returns The amounts, with slippage
920
941
  */
921
- involvesToken(token) {
922
- return token.equals(this.token0) || token.equals(this.token1);
942
+ mintAmountsWithSlippage(slippageTolerance) {
943
+ const { sqrtRatioX96Upper, sqrtRatioX96Lower } = this.ratiosAfterSlippage(slippageTolerance);
944
+ const poolLower = new Pool(
945
+ this.pool.token0,
946
+ this.pool.token1,
947
+ this.pool.fee,
948
+ sqrtRatioX96Lower,
949
+ 0,
950
+ TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower)
951
+ );
952
+ const poolUpper = new Pool(
953
+ this.pool.token0,
954
+ this.pool.token1,
955
+ this.pool.fee,
956
+ sqrtRatioX96Upper,
957
+ 0,
958
+ TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper)
959
+ );
960
+ const positionThatWillBeCreated = Position.fromAmounts({
961
+ pool: this.pool,
962
+ tickLower: this.tickLower,
963
+ tickUpper: this.tickUpper,
964
+ ...this.mintAmounts,
965
+ // the mint amounts are what will be passed as calldata
966
+ useFullPrecision: false
967
+ });
968
+ const { amount0 } = new Position({
969
+ pool: poolUpper,
970
+ liquidity: positionThatWillBeCreated.liquidity,
971
+ tickLower: this.tickLower,
972
+ tickUpper: this.tickUpper
973
+ }).mintAmounts;
974
+ const { amount1 } = new Position({
975
+ pool: poolLower,
976
+ liquidity: positionThatWillBeCreated.liquidity,
977
+ tickLower: this.tickLower,
978
+ tickUpper: this.tickUpper
979
+ }).mintAmounts;
980
+ return { amount0, amount1 };
923
981
  }
924
982
  /**
925
- * Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
983
+ * Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the
984
+ * position with the given slippage tolerance
985
+ * @param slippageTolerance tolerance of unfavorable slippage from the current price
986
+ * @returns The amounts, with slippage
926
987
  */
927
- get token0Price() {
928
- return this._token0Price ?? (this._token0Price = new sdk.Price(this.token0, this.token1, Q192, this.sqrtRatioX96 * this.sqrtRatioX96));
988
+ burnAmountsWithSlippage(slippageTolerance) {
989
+ const { sqrtRatioX96Upper, sqrtRatioX96Lower } = this.ratiosAfterSlippage(slippageTolerance);
990
+ const poolLower = new Pool(
991
+ this.pool.token0,
992
+ this.pool.token1,
993
+ this.pool.fee,
994
+ sqrtRatioX96Lower,
995
+ 0,
996
+ TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower)
997
+ );
998
+ const poolUpper = new Pool(
999
+ this.pool.token0,
1000
+ this.pool.token1,
1001
+ this.pool.fee,
1002
+ sqrtRatioX96Upper,
1003
+ 0,
1004
+ TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper)
1005
+ );
1006
+ const { amount0 } = new Position({
1007
+ pool: poolUpper,
1008
+ liquidity: this.liquidity,
1009
+ tickLower: this.tickLower,
1010
+ tickUpper: this.tickUpper
1011
+ });
1012
+ const { amount1 } = new Position({
1013
+ pool: poolLower,
1014
+ liquidity: this.liquidity,
1015
+ tickLower: this.tickLower,
1016
+ tickUpper: this.tickUpper
1017
+ });
1018
+ return { amount0: amount0.quotient, amount1: amount1.quotient };
929
1019
  }
930
1020
  /**
931
- * Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
1021
+ * Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at
1022
+ * the current price for the pool
932
1023
  */
933
- get token1Price() {
934
- return this._token1Price ?? (this._token1Price = new sdk.Price(this.token1, this.token0, this.sqrtRatioX96 * this.sqrtRatioX96, Q192));
1024
+ get mintAmounts() {
1025
+ if (this._mintAmounts === null) {
1026
+ if (this.pool.tickCurrent < this.tickLower) {
1027
+ return {
1028
+ amount0: SqrtPriceMath.getAmount0Delta(
1029
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1030
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1031
+ this.liquidity,
1032
+ true
1033
+ ),
1034
+ amount1: ZERO
1035
+ };
1036
+ }
1037
+ if (this.pool.tickCurrent < this.tickUpper) {
1038
+ return {
1039
+ amount0: SqrtPriceMath.getAmount0Delta(
1040
+ this.pool.sqrtRatioX96,
1041
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1042
+ this.liquidity,
1043
+ true
1044
+ ),
1045
+ amount1: SqrtPriceMath.getAmount1Delta(
1046
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1047
+ this.pool.sqrtRatioX96,
1048
+ this.liquidity,
1049
+ true
1050
+ )
1051
+ };
1052
+ }
1053
+ return {
1054
+ amount0: ZERO,
1055
+ amount1: SqrtPriceMath.getAmount1Delta(
1056
+ TickMath.getSqrtRatioAtTick(this.tickLower),
1057
+ TickMath.getSqrtRatioAtTick(this.tickUpper),
1058
+ this.liquidity,
1059
+ true
1060
+ )
1061
+ };
1062
+ }
1063
+ return this._mintAmounts;
935
1064
  }
936
1065
  /**
937
- * Return the price of the given token in terms of the other token in the pool.
938
- * @param token The token to return price of
939
- * @returns The price of the given token, in terms of the other.
1066
+ * Computes the maximum amount of liquidity received for a given amount of token0, token1,
1067
+ * and the prices at the tick boundaries.
1068
+ * @param pool The pool for which the position should be created
1069
+ * @param tickLower The lower tick of the position
1070
+ * @param tickUpper The upper tick of the position
1071
+ * @param amount0 token0 amount
1072
+ * @param amount1 token1 amount
1073
+ * @param useFullPrecision If false, liquidity will be maximized according to what the router can calculate,
1074
+ * not what core can theoretically support
1075
+ * @returns The amount of liquidity for the position
940
1076
  */
941
- priceOf(token) {
942
- invariant11__default.default(this.involvesToken(token), "TOKEN");
943
- return token.equals(this.token0) ? this.token0Price : this.token1Price;
1077
+ static fromAmounts({
1078
+ pool,
1079
+ tickLower,
1080
+ tickUpper,
1081
+ amount0,
1082
+ amount1,
1083
+ useFullPrecision
1084
+ }) {
1085
+ const sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
1086
+ const sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
1087
+ return new Position({
1088
+ pool,
1089
+ tickLower,
1090
+ tickUpper,
1091
+ liquidity: maxLiquidityForAmounts(
1092
+ pool.sqrtRatioX96,
1093
+ sqrtRatioAX96,
1094
+ sqrtRatioBX96,
1095
+ amount0,
1096
+ amount1,
1097
+ useFullPrecision
1098
+ )
1099
+ });
944
1100
  }
945
1101
  /**
946
- * Returns the chain ID of the tokens in the pool.
947
- */
948
- get chainId() {
949
- return this.token0.chainId;
1102
+ * Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1
1103
+ * @param pool The pool for which the position is created
1104
+ * @param tickLower The lower tick
1105
+ * @param tickUpper The upper tick
1106
+ * @param amount0 The desired amount of token0
1107
+ * @param useFullPrecision If true, liquidity will be maximized according to what the router can calculate,
1108
+ * not what core can theoretically support
1109
+ * @returns The position
1110
+ */
1111
+ static fromAmount0({
1112
+ pool,
1113
+ tickLower,
1114
+ tickUpper,
1115
+ amount0,
1116
+ useFullPrecision
1117
+ }) {
1118
+ return Position.fromAmounts({ pool, tickLower, tickUpper, amount0, amount1: sdk.MaxUint256, useFullPrecision });
950
1119
  }
951
1120
  /**
952
- * Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
953
- * @param inputAmount The input amount for which to quote the output amount
954
- * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
955
- * @returns The output amount and the pool with updated state
1121
+ * Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
1122
+ * @param pool The pool for which the position is created
1123
+ * @param tickLower The lower tick
1124
+ * @param tickUpper The upper tick
1125
+ * @param amount1 The desired amount of token1
1126
+ * @returns The position
956
1127
  */
957
- async getOutputAmount(inputAmount, sqrtPriceLimitX96) {
958
- invariant11__default.default(this.involvesToken(inputAmount.currency), "TOKEN");
959
- const zeroForOne = inputAmount.currency.equals(this.token0);
960
- const {
961
- amountCalculated: outputAmount,
962
- sqrtRatioX96,
963
- liquidity,
964
- tickCurrent
965
- } = await this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96);
966
- const outputToken = zeroForOne ? this.token1 : this.token0;
967
- return [
968
- sdk.CurrencyAmount.fromRawAmount(outputToken, outputAmount * NEGATIVE_ONE),
969
- new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)
970
- ];
1128
+ static fromAmount1({
1129
+ pool,
1130
+ tickLower,
1131
+ tickUpper,
1132
+ amount1
1133
+ }) {
1134
+ return Position.fromAmounts({ pool, tickLower, tickUpper, amount0: sdk.MaxUint256, amount1, useFullPrecision: true });
971
1135
  }
1136
+ };
1137
+ var Route = class {
972
1138
  /**
973
- * Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
974
- * @param outputAmount the output amount for which to quote the input amount
975
- * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
976
- * @returns The input amount and the pool with updated state
1139
+ * Creates an instance of route.
1140
+ * @param pools An array of `Pool` objects, ordered by the route the swap will take
1141
+ * @param input The input token
1142
+ * @param output The output token
977
1143
  */
978
- async getInputAmount(outputAmount, sqrtPriceLimitX96) {
979
- invariant11__default.default(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency), "TOKEN");
980
- const zeroForOne = outputAmount.currency.equals(this.token1);
981
- const {
982
- amountSpecifiedRemaining,
983
- amountCalculated: inputAmount,
984
- sqrtRatioX96,
985
- liquidity,
986
- tickCurrent
987
- } = await this.swap(zeroForOne, outputAmount.quotient * NEGATIVE_ONE, sqrtPriceLimitX96);
988
- invariant11__default.default(amountSpecifiedRemaining === ZERO, "INSUFICIENT_LIQUIDITY");
989
- const inputToken = zeroForOne ? this.token0 : this.token1;
990
- return [
991
- sdk.CurrencyAmount.fromRawAmount(inputToken, inputAmount),
992
- new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)
993
- ];
1144
+ constructor(pools, input, output) {
1145
+ this._midPrice = null;
1146
+ invariant9__default.default(pools.length > 0, "POOLS");
1147
+ const { chainId } = pools[0];
1148
+ const allOnSameChain = pools.every((pool) => pool.chainId === chainId);
1149
+ invariant9__default.default(allOnSameChain, "CHAIN_IDS");
1150
+ const wrappedInput = input.wrapped;
1151
+ invariant9__default.default(pools[0].involvesToken(wrappedInput), "INPUT");
1152
+ invariant9__default.default(pools[pools.length - 1].involvesToken(output.wrapped), "OUTPUT");
1153
+ const tokenPath = [wrappedInput];
1154
+ for (const [i, pool] of pools.entries()) {
1155
+ const currentInputToken = tokenPath[i];
1156
+ invariant9__default.default(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1), "PATH");
1157
+ const nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0;
1158
+ tokenPath.push(nextToken);
1159
+ }
1160
+ this.pools = pools;
1161
+ this.tokenPath = tokenPath;
1162
+ this.input = input;
1163
+ this.output = output ?? tokenPath[tokenPath.length - 1];
1164
+ }
1165
+ get chainId() {
1166
+ return this.pools[0].chainId;
994
1167
  }
995
1168
  /**
996
- * Executes a swap
997
- * @param zeroForOne Whether the amount in is token0 or token1
998
- * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
999
- * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap
1000
- * @returns amountCalculated
1001
- * @returns sqrtRatioX96
1002
- * @returns liquidity
1003
- * @returns tickCurrent
1169
+ * Returns the mid price of the route
1004
1170
  */
1005
- async swap(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
1006
- if (!sqrtPriceLimitX96)
1007
- sqrtPriceLimitX96 = zeroForOne ? TickMath.MIN_SQRT_RATIO + ONE : TickMath.MAX_SQRT_RATIO - ONE;
1008
- if (zeroForOne) {
1009
- invariant11__default.default(sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO, "RATIO_MIN");
1010
- invariant11__default.default(sqrtPriceLimitX96 < this.sqrtRatioX96, "RATIO_CURRENT");
1011
- } else {
1012
- invariant11__default.default(sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO, "RATIO_MAX");
1013
- invariant11__default.default(sqrtPriceLimitX96 > this.sqrtRatioX96, "RATIO_CURRENT");
1014
- }
1015
- const exactInput = amountSpecified >= ZERO;
1016
- const state = {
1017
- amountSpecifiedRemaining: amountSpecified,
1018
- amountCalculated: ZERO,
1019
- sqrtPriceX96: this.sqrtRatioX96,
1020
- tick: this.tickCurrent,
1021
- liquidity: this.liquidity
1022
- };
1023
- while (state.amountSpecifiedRemaining !== ZERO && state.sqrtPriceX96 != sqrtPriceLimitX96) {
1024
- const step = {};
1025
- step.sqrtPriceStartX96 = state.sqrtPriceX96;
1026
- [step.tickNext, step.initialized] = await this.tickDataProvider.nextInitializedTickWithinOneWord(
1027
- state.tick,
1028
- zeroForOne,
1029
- this.tickSpacing
1030
- );
1031
- if (step.tickNext < TickMath.MIN_TICK) {
1032
- step.tickNext = TickMath.MIN_TICK;
1033
- } else if (step.tickNext > TickMath.MAX_TICK) {
1034
- step.tickNext = TickMath.MAX_TICK;
1035
- }
1036
- step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
1037
- [state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.computeSwapStep(
1038
- state.sqrtPriceX96,
1039
- (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96,
1040
- state.liquidity,
1041
- state.amountSpecifiedRemaining,
1042
- this.fee
1043
- );
1044
- if (exactInput) {
1045
- state.amountSpecifiedRemaining = state.amountSpecifiedRemaining - (step.amountIn + step.feeAmount);
1046
- state.amountCalculated = state.amountCalculated - step.amountOut;
1047
- } else {
1048
- state.amountSpecifiedRemaining = state.amountSpecifiedRemaining + step.amountOut;
1049
- state.amountCalculated = state.amountCalculated + (step.amountIn + step.feeAmount);
1050
- }
1051
- if (state.sqrtPriceX96 === step.sqrtPriceNextX96) {
1052
- if (step.initialized) {
1053
- let liquidityNet = BigInt((await this.tickDataProvider.getTick(step.tickNext)).liquidityNet);
1054
- if (zeroForOne)
1055
- liquidityNet = liquidityNet * NEGATIVE_ONE;
1056
- state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
1057
- }
1058
- state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
1059
- } else if (state.sqrtPriceX96 !== step.sqrtPriceStartX96) {
1060
- state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
1171
+ get midPrice() {
1172
+ if (this._midPrice !== null)
1173
+ return this._midPrice;
1174
+ const { price } = this.pools.slice(1).reduce(
1175
+ ({ nextInput, price: price2 }, pool) => {
1176
+ return nextInput.equals(pool.token0) ? {
1177
+ nextInput: pool.token1,
1178
+ price: price2.multiply(pool.token0Price)
1179
+ } : {
1180
+ nextInput: pool.token0,
1181
+ price: price2.multiply(pool.token1Price)
1182
+ };
1183
+ },
1184
+ this.pools[0].token0.equals(this.input.wrapped) ? {
1185
+ nextInput: this.pools[0].token1,
1186
+ price: this.pools[0].token0Price
1187
+ } : {
1188
+ nextInput: this.pools[0].token0,
1189
+ price: this.pools[0].token1Price
1061
1190
  }
1191
+ );
1192
+ return this._midPrice = new swapSdkCore.Price(this.input, this.output, price.denominator, price.numerator);
1193
+ }
1194
+ };
1195
+ function tradeComparator(a, b) {
1196
+ invariant9__default.default(a.inputAmount.currency.equals(b.inputAmount.currency), "INPUT_CURRENCY");
1197
+ invariant9__default.default(a.outputAmount.currency.equals(b.outputAmount.currency), "OUTPUT_CURRENCY");
1198
+ if (a.outputAmount.equalTo(b.outputAmount)) {
1199
+ if (a.inputAmount.equalTo(b.inputAmount)) {
1200
+ const aHops = a.swaps.reduce((total, cur) => total + cur.route.tokenPath.length, 0);
1201
+ const bHops = b.swaps.reduce((total, cur) => total + cur.route.tokenPath.length, 0);
1202
+ return aHops - bHops;
1062
1203
  }
1063
- return {
1064
- amountSpecifiedRemaining: state.amountSpecifiedRemaining,
1065
- amountCalculated: state.amountCalculated,
1066
- sqrtRatioX96: state.sqrtPriceX96,
1067
- liquidity: state.liquidity,
1068
- tickCurrent: state.tick
1069
- };
1204
+ if (a.inputAmount.lessThan(b.inputAmount)) {
1205
+ return -1;
1206
+ }
1207
+ return 1;
1070
1208
  }
1071
- get tickSpacing() {
1072
- return TICK_SPACINGS[this.fee];
1209
+ if (a.outputAmount.lessThan(b.outputAmount)) {
1210
+ return 1;
1073
1211
  }
1074
- };
1075
- var Position = class {
1212
+ return -1;
1213
+ }
1214
+ var Trade = class {
1076
1215
  /**
1077
- * Constructs a position for a given pool with the given liquidity
1078
- * @param pool For which pool the liquidity is assigned
1079
- * @param liquidity The amount of liquidity that is in the position
1080
- * @param tickLower The lower tick of the position
1081
- * @param tickUpper The upper tick of the position
1216
+ * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
1217
+ * this will return an error.
1218
+ *
1219
+ * When the trade consists of just a single route, this returns the route of the trade,
1220
+ * i.e. which pools the trade goes through.
1082
1221
  */
1083
- constructor({ pool, liquidity, tickLower, tickUpper }) {
1084
- // cached resuts for the getters
1085
- this._token0Amount = null;
1086
- this._token1Amount = null;
1087
- this._mintAmounts = null;
1088
- invariant11__default.default(tickLower < tickUpper, "TICK_ORDER");
1089
- invariant11__default.default(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0, "TICK_LOWER");
1090
- invariant11__default.default(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0, "TICK_UPPER");
1091
- this.pool = pool;
1092
- this.tickLower = tickLower;
1093
- this.tickUpper = tickUpper;
1094
- this.liquidity = BigInt(liquidity);
1222
+ get route() {
1223
+ invariant9__default.default(this.swaps.length == 1, "MULTIPLE_ROUTES");
1224
+ return this.swaps[0].route;
1095
1225
  }
1096
1226
  /**
1097
- * Returns the price of token0 at the lower tick
1227
+ * The input amount for the trade assuming no slippage.
1098
1228
  */
1099
- get token0PriceLower() {
1100
- return tickToPrice(this.pool.token0, this.pool.token1, this.tickLower);
1229
+ get inputAmount() {
1230
+ if (this._inputAmount) {
1231
+ return this._inputAmount;
1232
+ }
1233
+ const inputCurrency = this.swaps[0].inputAmount.currency;
1234
+ const totalInputFromRoutes = this.swaps.map(({ inputAmount }) => inputAmount).reduce((total, cur) => total.add(cur), sdk.CurrencyAmount.fromRawAmount(inputCurrency, 0));
1235
+ this._inputAmount = totalInputFromRoutes;
1236
+ return this._inputAmount;
1101
1237
  }
1102
1238
  /**
1103
- * Returns the price of token0 at the upper tick
1239
+ * The output amount for the trade assuming no slippage.
1104
1240
  */
1105
- get token0PriceUpper() {
1106
- return tickToPrice(this.pool.token0, this.pool.token1, this.tickUpper);
1241
+ get outputAmount() {
1242
+ if (this._outputAmount) {
1243
+ return this._outputAmount;
1244
+ }
1245
+ const outputCurrency = this.swaps[0].outputAmount.currency;
1246
+ const totalOutputFromRoutes = this.swaps.map(({ outputAmount }) => outputAmount).reduce((total, cur) => total.add(cur), sdk.CurrencyAmount.fromRawAmount(outputCurrency, 0));
1247
+ this._outputAmount = totalOutputFromRoutes;
1248
+ return this._outputAmount;
1107
1249
  }
1108
1250
  /**
1109
- * Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
1251
+ * The price expressed in terms of output amount/input amount.
1110
1252
  */
1111
- get amount0() {
1112
- if (this._token0Amount === null) {
1113
- this._token0Amount = sdk.CurrencyAmount.fromRawAmount(
1114
- this.pool.token0,
1115
- PositionMath.getToken0Amount(
1116
- this.pool.tickCurrent,
1117
- this.tickLower,
1118
- this.tickUpper,
1119
- this.pool.sqrtRatioX96,
1120
- this.liquidity
1121
- )
1122
- );
1123
- }
1124
- return this._token0Amount;
1125
- }
1126
- /**
1127
- * Returns the amount of token1 that this position's liquidity could be burned for at the current pool price
1128
- */
1129
- get amount1() {
1130
- if (this._token1Amount === null) {
1131
- this._token1Amount = sdk.CurrencyAmount.fromRawAmount(
1132
- this.pool.token1,
1133
- PositionMath.getToken1Amount(
1134
- this.pool.tickCurrent,
1135
- this.tickLower,
1136
- this.tickUpper,
1137
- this.pool.sqrtRatioX96,
1138
- this.liquidity
1139
- )
1140
- );
1141
- }
1142
- return this._token1Amount;
1253
+ get executionPrice() {
1254
+ return this._executionPrice ?? (this._executionPrice = new sdk.Price(
1255
+ this.inputAmount.currency,
1256
+ this.outputAmount.currency,
1257
+ this.inputAmount.quotient,
1258
+ this.outputAmount.quotient
1259
+ ));
1143
1260
  }
1144
1261
  /**
1145
- * Returns the lower and upper sqrt ratios if the price 'slips' up to slippage tolerance percentage
1146
- * @param slippageTolerance The amount by which the price can 'slip' before the transaction will revert
1147
- * @returns The sqrt ratios after slippage
1262
+ * Returns the percent difference between the route's mid price and the price impact
1148
1263
  */
1149
- ratiosAfterSlippage(slippageTolerance) {
1150
- const priceLower = this.pool.token0Price.asFraction.multiply(new sdk.Percent(1).subtract(slippageTolerance));
1151
- const priceUpper = this.pool.token0Price.asFraction.multiply(slippageTolerance.add(1));
1152
- let sqrtRatioX96Lower = encodeSqrtRatioX96(priceLower.numerator, priceLower.denominator);
1153
- if (sqrtRatioX96Lower <= TickMath.MIN_SQRT_RATIO) {
1154
- sqrtRatioX96Lower = TickMath.MIN_SQRT_RATIO + 1n;
1264
+ get priceImpact() {
1265
+ if (this._priceImpact) {
1266
+ return this._priceImpact;
1155
1267
  }
1156
- let sqrtRatioX96Upper = encodeSqrtRatioX96(priceUpper.numerator, priceUpper.denominator);
1157
- if (sqrtRatioX96Upper >= TickMath.MAX_SQRT_RATIO) {
1158
- sqrtRatioX96Upper = TickMath.MAX_SQRT_RATIO - 1n;
1268
+ let spotOutputAmount = sdk.CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0);
1269
+ for (const { route, inputAmount } of this.swaps) {
1270
+ const { midPrice } = route;
1271
+ spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount));
1159
1272
  }
1160
- return {
1161
- sqrtRatioX96Lower,
1162
- sqrtRatioX96Upper
1163
- };
1273
+ const priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount);
1274
+ this._priceImpact = new sdk.Percent(priceImpact.numerator, priceImpact.denominator);
1275
+ return this._priceImpact;
1164
1276
  }
1165
1277
  /**
1166
- * Returns the minimum amounts that must be sent in order to safely mint the amount of liquidity held by the position
1167
- * with the given slippage tolerance
1168
- * @param slippageTolerance Tolerance of unfavorable slippage from the current price
1169
- * @returns The amounts, with slippage
1278
+ * Constructs an exact in trade with the given amount in and route
1279
+ * @template TInput The input token, either Ether or an ERC-20
1280
+ * @template TOutput The output token, either Ether or an ERC-20
1281
+ * @param route The route of the exact in trade
1282
+ * @param amountIn The amount being passed in
1283
+ * @returns The exact in trade
1170
1284
  */
1171
- mintAmountsWithSlippage(slippageTolerance) {
1172
- const { sqrtRatioX96Upper, sqrtRatioX96Lower } = this.ratiosAfterSlippage(slippageTolerance);
1173
- const poolLower = new Pool(
1174
- this.pool.token0,
1175
- this.pool.token1,
1176
- this.pool.fee,
1177
- sqrtRatioX96Lower,
1178
- 0,
1179
- TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower)
1180
- );
1181
- const poolUpper = new Pool(
1182
- this.pool.token0,
1183
- this.pool.token1,
1184
- this.pool.fee,
1185
- sqrtRatioX96Upper,
1186
- 0,
1187
- TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper)
1188
- );
1189
- const positionThatWillBeCreated = Position.fromAmounts({
1190
- pool: this.pool,
1191
- tickLower: this.tickLower,
1192
- tickUpper: this.tickUpper,
1193
- ...this.mintAmounts,
1194
- // the mint amounts are what will be passed as calldata
1195
- useFullPrecision: false
1196
- });
1197
- const { amount0 } = new Position({
1198
- pool: poolUpper,
1199
- liquidity: positionThatWillBeCreated.liquidity,
1200
- tickLower: this.tickLower,
1201
- tickUpper: this.tickUpper
1202
- }).mintAmounts;
1203
- const { amount1 } = new Position({
1204
- pool: poolLower,
1205
- liquidity: positionThatWillBeCreated.liquidity,
1206
- tickLower: this.tickLower,
1207
- tickUpper: this.tickUpper
1208
- }).mintAmounts;
1209
- return { amount0, amount1 };
1285
+ static async exactIn(route, amountIn) {
1286
+ return Trade.fromRoute(route, amountIn, sdk.TradeType.EXACT_INPUT);
1210
1287
  }
1211
1288
  /**
1212
- * Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the
1213
- * position with the given slippage tolerance
1214
- * @param slippageTolerance tolerance of unfavorable slippage from the current price
1215
- * @returns The amounts, with slippage
1289
+ * Constructs an exact out trade with the given amount out and route
1290
+ * @template TInput The input token, either Ether or an ERC-20
1291
+ * @template TOutput The output token, either Ether or an ERC-20
1292
+ * @param route The route of the exact out trade
1293
+ * @param amountOut The amount returned by the trade
1294
+ * @returns The exact out trade
1216
1295
  */
1217
- burnAmountsWithSlippage(slippageTolerance) {
1218
- const { sqrtRatioX96Upper, sqrtRatioX96Lower } = this.ratiosAfterSlippage(slippageTolerance);
1219
- const poolLower = new Pool(
1220
- this.pool.token0,
1221
- this.pool.token1,
1222
- this.pool.fee,
1223
- sqrtRatioX96Lower,
1224
- 0,
1225
- TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower)
1226
- );
1227
- const poolUpper = new Pool(
1228
- this.pool.token0,
1229
- this.pool.token1,
1230
- this.pool.fee,
1231
- sqrtRatioX96Upper,
1232
- 0,
1233
- TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper)
1234
- );
1235
- const { amount0 } = new Position({
1236
- pool: poolUpper,
1237
- liquidity: this.liquidity,
1238
- tickLower: this.tickLower,
1239
- tickUpper: this.tickUpper
1240
- });
1241
- const { amount1 } = new Position({
1242
- pool: poolLower,
1243
- liquidity: this.liquidity,
1244
- tickLower: this.tickLower,
1245
- tickUpper: this.tickUpper
1246
- });
1247
- return { amount0: amount0.quotient, amount1: amount1.quotient };
1296
+ static async exactOut(route, amountOut) {
1297
+ return Trade.fromRoute(route, amountOut, sdk.TradeType.EXACT_OUTPUT);
1248
1298
  }
1249
1299
  /**
1250
- * Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at
1251
- * the current price for the pool
1300
+ * Constructs a trade by simulating swaps through the given route
1301
+ * @template TInput The input token, either Ether or an ERC-20.
1302
+ * @template TOutput The output token, either Ether or an ERC-20.
1303
+ * @template TTradeType The type of the trade, either exact in or exact out.
1304
+ * @param route route to swap through
1305
+ * @param amount the amount specified, either input or output, depending on tradeType
1306
+ * @param tradeType whether the trade is an exact input or exact output swap
1307
+ * @returns The route
1252
1308
  */
1253
- get mintAmounts() {
1254
- if (this._mintAmounts === null) {
1255
- if (this.pool.tickCurrent < this.tickLower) {
1256
- return {
1257
- amount0: SqrtPriceMath.getAmount0Delta(
1258
- TickMath.getSqrtRatioAtTick(this.tickLower),
1259
- TickMath.getSqrtRatioAtTick(this.tickUpper),
1260
- this.liquidity,
1261
- true
1262
- ),
1263
- amount1: ZERO
1264
- };
1309
+ static async fromRoute(route, amount, tradeType) {
1310
+ const amounts = new Array(route.tokenPath.length);
1311
+ let inputAmount;
1312
+ let outputAmount;
1313
+ if (tradeType === sdk.TradeType.EXACT_INPUT) {
1314
+ invariant9__default.default(amount.currency.equals(route.input), "INPUT");
1315
+ amounts[0] = amount.wrapped;
1316
+ for (let i = 0; i < route.tokenPath.length - 1; i++) {
1317
+ const pool = route.pools[i];
1318
+ const [outputAmount2] = await pool.getOutputAmount(amounts[i]);
1319
+ amounts[i + 1] = outputAmount2;
1265
1320
  }
1266
- if (this.pool.tickCurrent < this.tickUpper) {
1267
- return {
1268
- amount0: SqrtPriceMath.getAmount0Delta(
1269
- this.pool.sqrtRatioX96,
1270
- TickMath.getSqrtRatioAtTick(this.tickUpper),
1271
- this.liquidity,
1272
- true
1273
- ),
1274
- amount1: SqrtPriceMath.getAmount1Delta(
1275
- TickMath.getSqrtRatioAtTick(this.tickLower),
1276
- this.pool.sqrtRatioX96,
1277
- this.liquidity,
1278
- true
1279
- )
1280
- };
1321
+ inputAmount = sdk.CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1322
+ outputAmount = sdk.CurrencyAmount.fromFractionalAmount(
1323
+ route.output,
1324
+ amounts[amounts.length - 1].numerator,
1325
+ amounts[amounts.length - 1].denominator
1326
+ );
1327
+ } else {
1328
+ invariant9__default.default(amount.currency.equals(route.output), "OUTPUT");
1329
+ amounts[amounts.length - 1] = amount.wrapped;
1330
+ for (let i = route.tokenPath.length - 1; i > 0; i--) {
1331
+ const pool = route.pools[i - 1];
1332
+ const [inputAmount2] = await pool.getInputAmount(amounts[i]);
1333
+ amounts[i - 1] = inputAmount2;
1281
1334
  }
1282
- return {
1283
- amount0: ZERO,
1284
- amount1: SqrtPriceMath.getAmount1Delta(
1285
- TickMath.getSqrtRatioAtTick(this.tickLower),
1286
- TickMath.getSqrtRatioAtTick(this.tickUpper),
1287
- this.liquidity,
1288
- true
1289
- )
1290
- };
1335
+ inputAmount = sdk.CurrencyAmount.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
1336
+ outputAmount = sdk.CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1291
1337
  }
1292
- return this._mintAmounts;
1338
+ return new Trade({
1339
+ routes: [{ inputAmount, outputAmount, route }],
1340
+ tradeType
1341
+ });
1293
1342
  }
1294
1343
  /**
1295
- * Computes the maximum amount of liquidity received for a given amount of token0, token1,
1296
- * and the prices at the tick boundaries.
1297
- * @param pool The pool for which the position should be created
1298
- * @param tickLower The lower tick of the position
1299
- * @param tickUpper The upper tick of the position
1300
- * @param amount0 token0 amount
1301
- * @param amount1 token1 amount
1302
- * @param useFullPrecision If false, liquidity will be maximized according to what the router can calculate,
1303
- * not what core can theoretically support
1304
- * @returns The amount of liquidity for the position
1305
- */
1306
- static fromAmounts({
1307
- pool,
1308
- tickLower,
1309
- tickUpper,
1310
- amount0,
1311
- amount1,
1312
- useFullPrecision
1313
- }) {
1314
- const sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
1315
- const sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
1316
- return new Position({
1317
- pool,
1318
- tickLower,
1319
- tickUpper,
1320
- liquidity: maxLiquidityForAmounts(
1321
- pool.sqrtRatioX96,
1322
- sqrtRatioAX96,
1323
- sqrtRatioBX96,
1324
- amount0,
1325
- amount1,
1326
- useFullPrecision
1327
- )
1328
- });
1329
- }
1330
- /**
1331
- * Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1
1332
- * @param pool The pool for which the position is created
1333
- * @param tickLower The lower tick
1334
- * @param tickUpper The upper tick
1335
- * @param amount0 The desired amount of token0
1336
- * @param useFullPrecision If true, liquidity will be maximized according to what the router can calculate,
1337
- * not what core can theoretically support
1338
- * @returns The position
1339
- */
1340
- static fromAmount0({
1341
- pool,
1342
- tickLower,
1343
- tickUpper,
1344
- amount0,
1345
- useFullPrecision
1346
- }) {
1347
- return Position.fromAmounts({ pool, tickLower, tickUpper, amount0, amount1: sdk.MaxUint256, useFullPrecision });
1348
- }
1349
- /**
1350
- * Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
1351
- * @param pool The pool for which the position is created
1352
- * @param tickLower The lower tick
1353
- * @param tickUpper The upper tick
1354
- * @param amount1 The desired amount of token1
1355
- * @returns The position
1356
- */
1357
- static fromAmount1({
1358
- pool,
1359
- tickLower,
1360
- tickUpper,
1361
- amount1
1362
- }) {
1363
- return Position.fromAmounts({ pool, tickLower, tickUpper, amount0: sdk.MaxUint256, amount1, useFullPrecision: true });
1364
- }
1365
- };
1366
- var Route = class {
1367
- /**
1368
- * Creates an instance of route.
1369
- * @param pools An array of `Pool` objects, ordered by the route the swap will take
1370
- * @param input The input token
1371
- * @param output The output token
1372
- */
1373
- constructor(pools, input, output) {
1374
- this._midPrice = null;
1375
- invariant11__default.default(pools.length > 0, "POOLS");
1376
- const { chainId } = pools[0];
1377
- const allOnSameChain = pools.every((pool) => pool.chainId === chainId);
1378
- invariant11__default.default(allOnSameChain, "CHAIN_IDS");
1379
- const wrappedInput = input.wrapped;
1380
- invariant11__default.default(pools[0].involvesToken(wrappedInput), "INPUT");
1381
- invariant11__default.default(pools[pools.length - 1].involvesToken(output.wrapped), "OUTPUT");
1382
- const tokenPath = [wrappedInput];
1383
- for (const [i, pool] of pools.entries()) {
1384
- const currentInputToken = tokenPath[i];
1385
- invariant11__default.default(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1), "PATH");
1386
- const nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0;
1387
- tokenPath.push(nextToken);
1388
- }
1389
- this.pools = pools;
1390
- this.tokenPath = tokenPath;
1391
- this.input = input;
1392
- this.output = output ?? tokenPath[tokenPath.length - 1];
1393
- }
1394
- get chainId() {
1395
- return this.pools[0].chainId;
1396
- }
1397
- /**
1398
- * Returns the mid price of the route
1399
- */
1400
- get midPrice() {
1401
- if (this._midPrice !== null)
1402
- return this._midPrice;
1403
- const { price } = this.pools.slice(1).reduce(
1404
- ({ nextInput, price: price2 }, pool) => {
1405
- return nextInput.equals(pool.token0) ? {
1406
- nextInput: pool.token1,
1407
- price: price2.multiply(pool.token0Price)
1408
- } : {
1409
- nextInput: pool.token0,
1410
- price: price2.multiply(pool.token1Price)
1411
- };
1412
- },
1413
- this.pools[0].token0.equals(this.input.wrapped) ? {
1414
- nextInput: this.pools[0].token1,
1415
- price: this.pools[0].token0Price
1416
- } : {
1417
- nextInput: this.pools[0].token0,
1418
- price: this.pools[0].token1Price
1419
- }
1420
- );
1421
- return this._midPrice = new swapSdkCore.Price(this.input, this.output, price.denominator, price.numerator);
1422
- }
1423
- };
1424
- function tradeComparator(a, b) {
1425
- invariant11__default.default(a.inputAmount.currency.equals(b.inputAmount.currency), "INPUT_CURRENCY");
1426
- invariant11__default.default(a.outputAmount.currency.equals(b.outputAmount.currency), "OUTPUT_CURRENCY");
1427
- if (a.outputAmount.equalTo(b.outputAmount)) {
1428
- if (a.inputAmount.equalTo(b.inputAmount)) {
1429
- const aHops = a.swaps.reduce((total, cur) => total + cur.route.tokenPath.length, 0);
1430
- const bHops = b.swaps.reduce((total, cur) => total + cur.route.tokenPath.length, 0);
1431
- return aHops - bHops;
1432
- }
1433
- if (a.inputAmount.lessThan(b.inputAmount)) {
1434
- return -1;
1435
- }
1436
- return 1;
1437
- }
1438
- if (a.outputAmount.lessThan(b.outputAmount)) {
1439
- return 1;
1440
- }
1441
- return -1;
1442
- }
1443
- var Trade = class {
1444
- /**
1445
- * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
1446
- * this will return an error.
1447
- *
1448
- * When the trade consists of just a single route, this returns the route of the trade,
1449
- * i.e. which pools the trade goes through.
1450
- */
1451
- get route() {
1452
- invariant11__default.default(this.swaps.length == 1, "MULTIPLE_ROUTES");
1453
- return this.swaps[0].route;
1454
- }
1455
- /**
1456
- * The input amount for the trade assuming no slippage.
1457
- */
1458
- get inputAmount() {
1459
- if (this._inputAmount) {
1460
- return this._inputAmount;
1461
- }
1462
- const inputCurrency = this.swaps[0].inputAmount.currency;
1463
- const totalInputFromRoutes = this.swaps.map(({ inputAmount }) => inputAmount).reduce((total, cur) => total.add(cur), sdk.CurrencyAmount.fromRawAmount(inputCurrency, 0));
1464
- this._inputAmount = totalInputFromRoutes;
1465
- return this._inputAmount;
1466
- }
1467
- /**
1468
- * The output amount for the trade assuming no slippage.
1469
- */
1470
- get outputAmount() {
1471
- if (this._outputAmount) {
1472
- return this._outputAmount;
1473
- }
1474
- const outputCurrency = this.swaps[0].outputAmount.currency;
1475
- const totalOutputFromRoutes = this.swaps.map(({ outputAmount }) => outputAmount).reduce((total, cur) => total.add(cur), sdk.CurrencyAmount.fromRawAmount(outputCurrency, 0));
1476
- this._outputAmount = totalOutputFromRoutes;
1477
- return this._outputAmount;
1478
- }
1479
- /**
1480
- * The price expressed in terms of output amount/input amount.
1481
- */
1482
- get executionPrice() {
1483
- return this._executionPrice ?? (this._executionPrice = new sdk.Price(
1484
- this.inputAmount.currency,
1485
- this.outputAmount.currency,
1486
- this.inputAmount.quotient,
1487
- this.outputAmount.quotient
1488
- ));
1489
- }
1490
- /**
1491
- * Returns the percent difference between the route's mid price and the price impact
1492
- */
1493
- get priceImpact() {
1494
- if (this._priceImpact) {
1495
- return this._priceImpact;
1496
- }
1497
- let spotOutputAmount = sdk.CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0);
1498
- for (const { route, inputAmount } of this.swaps) {
1499
- const { midPrice } = route;
1500
- spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount));
1501
- }
1502
- const priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount);
1503
- this._priceImpact = new sdk.Percent(priceImpact.numerator, priceImpact.denominator);
1504
- return this._priceImpact;
1505
- }
1506
- /**
1507
- * Constructs an exact in trade with the given amount in and route
1508
- * @template TInput The input token, either Ether or an ERC-20
1509
- * @template TOutput The output token, either Ether or an ERC-20
1510
- * @param route The route of the exact in trade
1511
- * @param amountIn The amount being passed in
1512
- * @returns The exact in trade
1513
- */
1514
- static async exactIn(route, amountIn) {
1515
- return Trade.fromRoute(route, amountIn, sdk.TradeType.EXACT_INPUT);
1516
- }
1517
- /**
1518
- * Constructs an exact out trade with the given amount out and route
1519
- * @template TInput The input token, either Ether or an ERC-20
1520
- * @template TOutput The output token, either Ether or an ERC-20
1521
- * @param route The route of the exact out trade
1522
- * @param amountOut The amount returned by the trade
1523
- * @returns The exact out trade
1524
- */
1525
- static async exactOut(route, amountOut) {
1526
- return Trade.fromRoute(route, amountOut, sdk.TradeType.EXACT_OUTPUT);
1527
- }
1528
- /**
1529
- * Constructs a trade by simulating swaps through the given route
1530
- * @template TInput The input token, either Ether or an ERC-20.
1531
- * @template TOutput The output token, either Ether or an ERC-20.
1532
- * @template TTradeType The type of the trade, either exact in or exact out.
1533
- * @param route route to swap through
1534
- * @param amount the amount specified, either input or output, depending on tradeType
1535
- * @param tradeType whether the trade is an exact input or exact output swap
1536
- * @returns The route
1537
- */
1538
- static async fromRoute(route, amount, tradeType) {
1539
- const amounts = new Array(route.tokenPath.length);
1540
- let inputAmount;
1541
- let outputAmount;
1542
- if (tradeType === sdk.TradeType.EXACT_INPUT) {
1543
- invariant11__default.default(amount.currency.equals(route.input), "INPUT");
1544
- amounts[0] = amount.wrapped;
1545
- for (let i = 0; i < route.tokenPath.length - 1; i++) {
1546
- const pool = route.pools[i];
1547
- const [outputAmount2] = await pool.getOutputAmount(amounts[i]);
1548
- amounts[i + 1] = outputAmount2;
1549
- }
1550
- inputAmount = sdk.CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1551
- outputAmount = sdk.CurrencyAmount.fromFractionalAmount(
1552
- route.output,
1553
- amounts[amounts.length - 1].numerator,
1554
- amounts[amounts.length - 1].denominator
1555
- );
1556
- } else {
1557
- invariant11__default.default(amount.currency.equals(route.output), "OUTPUT");
1558
- amounts[amounts.length - 1] = amount.wrapped;
1559
- for (let i = route.tokenPath.length - 1; i > 0; i--) {
1560
- const pool = route.pools[i - 1];
1561
- const [inputAmount2] = await pool.getInputAmount(amounts[i]);
1562
- amounts[i - 1] = inputAmount2;
1563
- }
1564
- inputAmount = sdk.CurrencyAmount.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
1565
- outputAmount = sdk.CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1566
- }
1567
- return new Trade({
1568
- routes: [{ inputAmount, outputAmount, route }],
1569
- tradeType
1570
- });
1571
- }
1572
- /**
1573
- * Constructs a trade from routes by simulating swaps
1574
- *
1575
- * @template TInput The input token, either Ether or an ERC-20.
1576
- * @template TOutput The output token, either Ether or an ERC-20.
1577
- * @template TTradeType The type of the trade, either exact in or exact out.
1578
- * @param routes the routes to swap through and how much of the amount should be routed through each
1579
- * @param tradeType whether the trade is an exact input or exact output swap
1580
- * @returns The trade
1344
+ * Constructs a trade from routes by simulating swaps
1345
+ *
1346
+ * @template TInput The input token, either Ether or an ERC-20.
1347
+ * @template TOutput The output token, either Ether or an ERC-20.
1348
+ * @template TTradeType The type of the trade, either exact in or exact out.
1349
+ * @param routes the routes to swap through and how much of the amount should be routed through each
1350
+ * @param tradeType whether the trade is an exact input or exact output swap
1351
+ * @returns The trade
1581
1352
  */
1582
1353
  static async fromRoutes(routes, tradeType) {
1583
1354
  const populatedRoutes = [];
@@ -1586,7 +1357,7 @@ var Trade = class {
1586
1357
  let inputAmount;
1587
1358
  let outputAmount;
1588
1359
  if (tradeType === sdk.TradeType.EXACT_INPUT) {
1589
- invariant11__default.default(amount.currency.equals(route.input), "INPUT");
1360
+ invariant9__default.default(amount.currency.equals(route.input), "INPUT");
1590
1361
  inputAmount = sdk.CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1591
1362
  amounts[0] = sdk.CurrencyAmount.fromFractionalAmount(route.input.wrapped, amount.numerator, amount.denominator);
1592
1363
  for (let i = 0; i < route.tokenPath.length - 1; i++) {
@@ -1600,7 +1371,7 @@ var Trade = class {
1600
1371
  amounts[amounts.length - 1].denominator
1601
1372
  );
1602
1373
  } else {
1603
- invariant11__default.default(amount.currency.equals(route.output), "OUTPUT");
1374
+ invariant9__default.default(amount.currency.equals(route.output), "OUTPUT");
1604
1375
  outputAmount = sdk.CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1605
1376
  amounts[amounts.length - 1] = sdk.CurrencyAmount.fromFractionalAmount(
1606
1377
  route.output.wrapped,
@@ -1665,11 +1436,11 @@ var Trade = class {
1665
1436
  }) {
1666
1437
  const inputCurrency = routes[0].inputAmount.currency;
1667
1438
  const outputCurrency = routes[0].outputAmount.currency;
1668
- invariant11__default.default(
1439
+ invariant9__default.default(
1669
1440
  routes.every(({ route }) => inputCurrency.wrapped.equals(route.input.wrapped)),
1670
1441
  "INPUT_CURRENCY_MATCH"
1671
1442
  );
1672
- invariant11__default.default(
1443
+ invariant9__default.default(
1673
1444
  routes.every(({ route }) => outputCurrency.wrapped.equals(route.output.wrapped)),
1674
1445
  "OUTPUT_CURRENCY_MATCH"
1675
1446
  );
@@ -1680,7 +1451,7 @@ var Trade = class {
1680
1451
  poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, pool.fee));
1681
1452
  }
1682
1453
  }
1683
- invariant11__default.default(numPools == poolAddressSet.size, "POOLS_DUPLICATED");
1454
+ invariant9__default.default(numPools == poolAddressSet.size, "POOLS_DUPLICATED");
1684
1455
  this.swaps = routes;
1685
1456
  this.tradeType = tradeType;
1686
1457
  }
@@ -1690,169 +1461,473 @@ var Trade = class {
1690
1461
  * @returns The amount out
1691
1462
  */
1692
1463
  minimumAmountOut(slippageTolerance, amountOut = this.outputAmount) {
1693
- invariant11__default.default(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1464
+ invariant9__default.default(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1694
1465
  if (this.tradeType === sdk.TradeType.EXACT_OUTPUT) {
1695
1466
  return amountOut;
1696
1467
  }
1697
1468
  const slippageAdjustedAmountOut = new sdk.Fraction(ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
1698
1469
  return sdk.CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
1699
1470
  }
1700
- /**
1701
- * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
1702
- * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
1703
- * @returns The amount in
1704
- */
1705
- maximumAmountIn(slippageTolerance, amountIn = this.inputAmount) {
1706
- invariant11__default.default(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1707
- if (this.tradeType === sdk.TradeType.EXACT_INPUT) {
1708
- return amountIn;
1471
+ /**
1472
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
1473
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
1474
+ * @returns The amount in
1475
+ */
1476
+ maximumAmountIn(slippageTolerance, amountIn = this.inputAmount) {
1477
+ invariant9__default.default(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1478
+ if (this.tradeType === sdk.TradeType.EXACT_INPUT) {
1479
+ return amountIn;
1480
+ }
1481
+ const slippageAdjustedAmountIn = new sdk.Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
1482
+ return sdk.CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
1483
+ }
1484
+ /**
1485
+ * Return the execution price after accounting for slippage tolerance
1486
+ * @param slippageTolerance the allowed tolerated slippage
1487
+ * @returns The execution price
1488
+ */
1489
+ worstExecutionPrice(slippageTolerance) {
1490
+ return new sdk.Price(
1491
+ this.inputAmount.currency,
1492
+ this.outputAmount.currency,
1493
+ this.maximumAmountIn(slippageTolerance).quotient,
1494
+ this.minimumAmountOut(slippageTolerance).quotient
1495
+ );
1496
+ }
1497
+ /**
1498
+ * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
1499
+ * amount to an output token, making at most `maxHops` hops.
1500
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
1501
+ * the amount in among multiple routes.
1502
+ * @param pools the pools to consider in finding the best trade
1503
+ * @param nextAmountIn exact amount of input currency to spend
1504
+ * @param currencyOut the desired currency out
1505
+ * @param maxNumResults maximum number of results to return
1506
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1507
+ * @param currentPools used in recursion; the current list of pools
1508
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
1509
+ * @param bestTrades used in recursion; the current list of best trades
1510
+ * @returns The exact in trade
1511
+ */
1512
+ static async bestTradeExactIn(pools, currencyAmountIn, currencyOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountIn = currencyAmountIn, bestTrades = []) {
1513
+ invariant9__default.default(pools.length > 0, "POOLS");
1514
+ invariant9__default.default(maxHops > 0, "MAX_HOPS");
1515
+ invariant9__default.default(currencyAmountIn === nextAmountIn || currentPools.length > 0, "INVALID_RECURSION");
1516
+ const amountIn = nextAmountIn.wrapped;
1517
+ const tokenOut = currencyOut.wrapped;
1518
+ for (let i = 0; i < pools.length; i++) {
1519
+ const pool = pools[i];
1520
+ if (!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency))
1521
+ continue;
1522
+ let amountOut;
1523
+ try {
1524
+ const [result] = await pool.getOutputAmount(amountIn);
1525
+ amountOut = result;
1526
+ } catch (error) {
1527
+ if (error.isInsufficientInputAmountError) {
1528
+ continue;
1529
+ }
1530
+ throw error;
1531
+ }
1532
+ if (amountOut.currency.isToken && amountOut.currency.equals(tokenOut)) {
1533
+ sdk.sortedInsert(
1534
+ bestTrades,
1535
+ await Trade.fromRoute(
1536
+ new Route([...currentPools, pool], currencyAmountIn.currency, currencyOut),
1537
+ currencyAmountIn,
1538
+ sdk.TradeType.EXACT_INPUT
1539
+ ),
1540
+ maxNumResults,
1541
+ tradeComparator
1542
+ );
1543
+ } else if (maxHops > 1 && pools.length > 1) {
1544
+ const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1545
+ await Trade.bestTradeExactIn(
1546
+ poolsExcludingThisPool,
1547
+ currencyAmountIn,
1548
+ currencyOut,
1549
+ {
1550
+ maxNumResults,
1551
+ maxHops: maxHops - 1
1552
+ },
1553
+ [...currentPools, pool],
1554
+ amountOut,
1555
+ bestTrades
1556
+ );
1557
+ }
1558
+ }
1559
+ return bestTrades;
1560
+ }
1561
+ /**
1562
+ * similar to the above method but instead targets a fixed output amount
1563
+ * given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
1564
+ * to an output token amount, making at most `maxHops` hops
1565
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
1566
+ * the amount in among multiple routes.
1567
+ * @param pools the pools to consider in finding the best trade
1568
+ * @param currencyIn the currency to spend
1569
+ * @param currencyAmountOut the desired currency amount out
1570
+ * @param nextAmountOut the exact amount of currency out
1571
+ * @param maxNumResults maximum number of results to return
1572
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1573
+ * @param currentPools used in recursion; the current list of pools
1574
+ * @param bestTrades used in recursion; the current list of best trades
1575
+ * @returns The exact out trade
1576
+ */
1577
+ static async bestTradeExactOut(pools, currencyIn, currencyAmountOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountOut = currencyAmountOut, bestTrades = []) {
1578
+ invariant9__default.default(pools.length > 0, "POOLS");
1579
+ invariant9__default.default(maxHops > 0, "MAX_HOPS");
1580
+ invariant9__default.default(currencyAmountOut === nextAmountOut || currentPools.length > 0, "INVALID_RECURSION");
1581
+ const amountOut = nextAmountOut.wrapped;
1582
+ const tokenIn = currencyIn.wrapped;
1583
+ for (let i = 0; i < pools.length; i++) {
1584
+ const pool = pools[i];
1585
+ if (!pool.token0.equals(amountOut.currency) && !pool.token1.equals(amountOut.currency))
1586
+ continue;
1587
+ let amountIn;
1588
+ try {
1589
+ const [result] = await pool.getInputAmount(amountOut);
1590
+ amountIn = result;
1591
+ } catch (error) {
1592
+ if (error.isInsufficientReservesError) {
1593
+ continue;
1594
+ }
1595
+ throw error;
1596
+ }
1597
+ if (amountIn.currency.equals(tokenIn)) {
1598
+ sdk.sortedInsert(
1599
+ bestTrades,
1600
+ await Trade.fromRoute(
1601
+ new Route([pool, ...currentPools], currencyIn, currencyAmountOut.currency),
1602
+ currencyAmountOut,
1603
+ sdk.TradeType.EXACT_OUTPUT
1604
+ ),
1605
+ maxNumResults,
1606
+ tradeComparator
1607
+ );
1608
+ } else if (maxHops > 1 && pools.length > 1) {
1609
+ const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1610
+ await Trade.bestTradeExactOut(
1611
+ poolsExcludingThisPool,
1612
+ currencyIn,
1613
+ currencyAmountOut,
1614
+ {
1615
+ maxNumResults,
1616
+ maxHops: maxHops - 1
1617
+ },
1618
+ [pool, ...currentPools],
1619
+ amountIn,
1620
+ bestTrades
1621
+ );
1622
+ }
1623
+ }
1624
+ return bestTrades;
1625
+ }
1626
+ };
1627
+
1628
+ // src/utils/calldata.ts
1629
+ function toHex(bigintIsh) {
1630
+ const bigInt = BigInt(bigintIsh);
1631
+ let hex = bigInt.toString(16);
1632
+ if (hex.length % 2 !== 0) {
1633
+ hex = `0${hex}`;
1634
+ }
1635
+ return `0x${hex}`;
1636
+ }
1637
+ function encodeRouteToPath(route, exactOutput) {
1638
+ const firstInputToken = route.input.wrapped;
1639
+ const { path, types } = route.pools.reduce(
1640
+ ({ inputToken, path: path2, types: types2 }, pool, index) => {
1641
+ const outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
1642
+ if (index === 0) {
1643
+ return {
1644
+ inputToken: outputToken,
1645
+ types: ["address", "uint24", "address"],
1646
+ path: [inputToken.address, pool.fee, outputToken.address]
1647
+ };
1648
+ }
1649
+ return {
1650
+ inputToken: outputToken,
1651
+ types: [...types2, "uint24", "address"],
1652
+ path: [...path2, pool.fee, outputToken.address]
1653
+ };
1654
+ },
1655
+ { inputToken: firstInputToken, path: [], types: [] }
1656
+ );
1657
+ return exactOutput ? viem.encodePacked(types.reverse(), path.reverse()) : viem.encodePacked(types, path);
1658
+ }
1659
+ function nearestUsableTick(tick, tickSpacing) {
1660
+ invariant9__default.default(Number.isInteger(tick) && Number.isInteger(tickSpacing), "INTEGERS");
1661
+ invariant9__default.default(tickSpacing > 0, "TICK_SPACING");
1662
+ invariant9__default.default(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK, "TICK_BOUND");
1663
+ const rounded = Math.round(tick / tickSpacing) * tickSpacing;
1664
+ if (rounded < TickMath.MIN_TICK)
1665
+ return rounded + tickSpacing;
1666
+ if (rounded > TickMath.MAX_TICK)
1667
+ return rounded - tickSpacing;
1668
+ return rounded;
1669
+ }
1670
+
1671
+ // src/utils/position.ts
1672
+ var PositionLibrary = class {
1673
+ /**
1674
+ * Cannot be constructed.
1675
+ */
1676
+ constructor() {
1677
+ }
1678
+ // replicates the portions of Position#update required to compute unaccounted fees
1679
+ static getTokensOwed(feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, feeGrowthInside0X128, feeGrowthInside1X128) {
1680
+ const tokensOwed0 = subIn256(feeGrowthInside0X128, feeGrowthInside0LastX128) * liquidity / Q128;
1681
+ const tokensOwed1 = subIn256(feeGrowthInside1X128, feeGrowthInside1LastX128) * liquidity / Q128;
1682
+ return [tokensOwed0, tokensOwed1];
1683
+ }
1684
+ };
1685
+
1686
+ // src/utils/tickLibrary.ts
1687
+ var Q256 = 2n ** 256n;
1688
+ function subIn256(x, y) {
1689
+ const difference = x - y;
1690
+ if (difference < ZERO) {
1691
+ return Q256 + difference;
1692
+ }
1693
+ return difference;
1694
+ }
1695
+ var TickLibrary = class {
1696
+ /**
1697
+ * Cannot be constructed.
1698
+ */
1699
+ constructor() {
1700
+ }
1701
+ static getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) {
1702
+ let feeGrowthBelow0X128;
1703
+ let feeGrowthBelow1X128;
1704
+ if (tickCurrent >= tickLower) {
1705
+ feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128;
1706
+ feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128;
1707
+ } else {
1708
+ feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128);
1709
+ feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128);
1710
+ }
1711
+ let feeGrowthAbove0X128;
1712
+ let feeGrowthAbove1X128;
1713
+ if (tickCurrent < tickUpper) {
1714
+ feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128;
1715
+ feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128;
1716
+ } else {
1717
+ feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128);
1718
+ feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128);
1719
+ }
1720
+ return [
1721
+ subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128),
1722
+ subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)
1723
+ ];
1724
+ }
1725
+ };
1726
+ function parseNumberToFraction(num, precision = 6) {
1727
+ if (Number.isNaN(num) || !Number.isFinite(num)) {
1728
+ return void 0;
1729
+ }
1730
+ const scalar = 10 ** precision;
1731
+ return new swapSdkCore.Fraction(BigInt(Math.floor(num * scalar)), BigInt(scalar));
1732
+ }
1733
+
1734
+ // src/utils/feeCalculator.ts
1735
+ var FeeCalculator = {
1736
+ getEstimatedLPFee,
1737
+ getEstimatedLPFeeByAmounts,
1738
+ getLiquidityFromTick,
1739
+ getLiquidityFromSqrtRatioX96,
1740
+ getAverageLiquidity,
1741
+ getLiquidityBySingleAmount,
1742
+ getDependentAmount,
1743
+ getLiquidityByAmountsAndPrice,
1744
+ getAmountsByLiquidityAndPrice,
1745
+ getAmountsAtNewPrice
1746
+ };
1747
+ function getEstimatedLPFeeWithProtocolFee({ amount, currency, ...rest }) {
1748
+ return getEstimatedLPFeeByAmountsWithProtocolFee({
1749
+ ...rest,
1750
+ amountA: amount,
1751
+ amountB: swapSdkCore.CurrencyAmount.fromRawAmount(currency, swapSdkCore.MaxUint256)
1752
+ });
1753
+ }
1754
+ function getEstimatedLPFee({ amount, currency, ...rest }) {
1755
+ return getEstimatedLPFeeByAmounts({
1756
+ ...rest,
1757
+ amountA: amount,
1758
+ amountB: swapSdkCore.CurrencyAmount.fromRawAmount(currency, swapSdkCore.MaxUint256)
1759
+ });
1760
+ }
1761
+ function getEstimatedLPFeeByAmountsWithProtocolFee(options) {
1762
+ try {
1763
+ return tryGetEstimatedLPFeeByAmounts(options);
1764
+ } catch (e) {
1765
+ console.error(e);
1766
+ return new swapSdkCore.Fraction(swapSdkCore.ZERO);
1767
+ }
1768
+ }
1769
+ function getEstimatedLPFeeByAmounts({ protocolFee = ZERO_PERCENT, ...rest }) {
1770
+ try {
1771
+ const fee = tryGetEstimatedLPFeeByAmounts(rest);
1772
+ return ONE_HUNDRED_PERCENT.subtract(protocolFee).multiply(fee).asFraction;
1773
+ } catch (e) {
1774
+ console.error(e);
1775
+ return new swapSdkCore.Fraction(swapSdkCore.ZERO);
1776
+ }
1777
+ }
1778
+ function tryGetEstimatedLPFeeByAmounts({
1779
+ amountA,
1780
+ amountB,
1781
+ volume24H,
1782
+ sqrtRatioX96,
1783
+ tickLower,
1784
+ tickUpper,
1785
+ mostActiveLiquidity,
1786
+ fee,
1787
+ insidePercentage = ONE_HUNDRED_PERCENT
1788
+ }) {
1789
+ invariant9__default.default(!Number.isNaN(fee) && fee >= 0, "INVALID_FEE");
1790
+ const tickCurrent = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1791
+ if (tickCurrent < tickLower || tickCurrent > tickUpper) {
1792
+ return new swapSdkCore.Fraction(swapSdkCore.ZERO);
1793
+ }
1794
+ const liquidity = FeeCalculator.getLiquidityByAmountsAndPrice({
1795
+ amountA,
1796
+ amountB,
1797
+ tickUpper,
1798
+ tickLower,
1799
+ sqrtRatioX96
1800
+ });
1801
+ if (!liquidity) {
1802
+ return new swapSdkCore.Fraction(swapSdkCore.ZERO);
1803
+ }
1804
+ const volumeInFraction = parseNumberToFraction(volume24H) || new swapSdkCore.Fraction(swapSdkCore.ZERO);
1805
+ return insidePercentage.multiply(volumeInFraction.multiply(BigInt(fee)).multiply(liquidity)).divide(MAX_FEE * (liquidity + mostActiveLiquidity)).asFraction;
1806
+ }
1807
+ function getDependentAmount(options) {
1808
+ const { currency, amount, sqrtRatioX96, tickLower, tickUpper } = options;
1809
+ const currentTick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1810
+ const liquidity = FeeCalculator.getLiquidityBySingleAmount(options);
1811
+ const isToken0 = currency.wrapped.sortsBefore(amount.currency.wrapped);
1812
+ const getTokenAmount = isToken0 ? PositionMath.getToken0Amount : PositionMath.getToken1Amount;
1813
+ if (!liquidity) {
1814
+ return void 0;
1815
+ }
1816
+ return swapSdkCore.CurrencyAmount.fromRawAmount(
1817
+ currency,
1818
+ getTokenAmount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity)
1819
+ );
1820
+ }
1821
+ function getLiquidityBySingleAmount({ amount, currency, ...rest }) {
1822
+ return getLiquidityByAmountsAndPrice({
1823
+ amountA: amount,
1824
+ amountB: swapSdkCore.CurrencyAmount.fromRawAmount(currency, swapSdkCore.MaxUint256),
1825
+ ...rest
1826
+ });
1827
+ }
1828
+ function getLiquidityByAmountsAndPrice({
1829
+ amountA,
1830
+ amountB,
1831
+ tickUpper,
1832
+ tickLower,
1833
+ sqrtRatioX96
1834
+ }) {
1835
+ const isToken0 = amountA.currency.wrapped.address !== amountB.currency.wrapped.address ? amountA.currency.wrapped.sortsBefore(amountB.currency.wrapped) : true;
1836
+ const [inputAmount0, inputAmount1] = isToken0 ? [amountA.quotient, amountB.quotient] : [amountB.quotient, amountA.quotient];
1837
+ const sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
1838
+ const sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
1839
+ try {
1840
+ return maxLiquidityForAmounts(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, inputAmount0, inputAmount1, true);
1841
+ } catch (e) {
1842
+ console.error(e);
1843
+ return void 0;
1844
+ }
1845
+ }
1846
+ function getAmountsByLiquidityAndPrice(options) {
1847
+ const { currencyA, currencyB, liquidity, sqrtRatioX96, tickLower, tickUpper } = options;
1848
+ const currentTick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1849
+ const isToken0 = currencyA.wrapped.sortsBefore(currencyB.wrapped);
1850
+ const adjustedAmount0 = PositionMath.getToken0Amount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity);
1851
+ const adjustedAmount1 = PositionMath.getToken1Amount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity);
1852
+ return [
1853
+ swapSdkCore.CurrencyAmount.fromRawAmount(currencyA, isToken0 ? adjustedAmount0 : adjustedAmount1),
1854
+ swapSdkCore.CurrencyAmount.fromRawAmount(currencyB, isToken0 ? adjustedAmount1 : adjustedAmount0)
1855
+ ];
1856
+ }
1857
+ function getAmountsAtNewPrice({ newSqrtRatioX96, ...rest }) {
1858
+ const { tickLower, tickUpper, amountA, amountB } = rest;
1859
+ const liquidity = FeeCalculator.getLiquidityByAmountsAndPrice(rest);
1860
+ if (!liquidity) {
1861
+ return void 0;
1862
+ }
1863
+ return FeeCalculator.getAmountsByLiquidityAndPrice({
1864
+ liquidity,
1865
+ currencyA: amountA.currency,
1866
+ currencyB: amountB.currency,
1867
+ tickLower,
1868
+ tickUpper,
1869
+ sqrtRatioX96: newSqrtRatioX96
1870
+ });
1871
+ }
1872
+ function getAverageLiquidity(ticks, tickSpacing, tickLower, tickUpper) {
1873
+ invariant9__default.default(tickLower <= tickUpper, "INVALID_TICK_RANGE");
1874
+ TickList.validateList(ticks, tickSpacing);
1875
+ if (tickLower === tickUpper) {
1876
+ return FeeCalculator.getLiquidityFromTick(ticks, tickLower);
1877
+ }
1878
+ const lowerOutOfBound = tickLower < ticks[0].index;
1879
+ let lastTick = lowerOutOfBound ? new Tick({ index: TickMath.MIN_TICK, liquidityNet: swapSdkCore.ZERO, liquidityGross: swapSdkCore.ZERO }) : TickList.nextInitializedTick(ticks, tickLower, true);
1880
+ let currentTick = TickList.nextInitializedTick(ticks, tickLower, false);
1881
+ let currentL = lowerOutOfBound ? swapSdkCore.ZERO : FeeCalculator.getLiquidityFromTick(ticks, currentTick.index);
1882
+ let weightedL = swapSdkCore.ZERO;
1883
+ const getWeightedLFromLastTickTo = (toTick) => currentL * BigInt(toTick - Math.max(lastTick.index, tickLower));
1884
+ while (currentTick.index < tickUpper) {
1885
+ weightedL += getWeightedLFromLastTickTo(currentTick.index);
1886
+ currentL += currentTick.liquidityNet;
1887
+ lastTick = currentTick;
1888
+ if (currentTick.index === ticks[ticks.length - 1].index) {
1889
+ break;
1709
1890
  }
1710
- const slippageAdjustedAmountIn = new sdk.Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
1711
- return sdk.CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
1891
+ currentTick = TickList.nextInitializedTick(ticks, currentTick.index, false);
1712
1892
  }
1713
- /**
1714
- * Return the execution price after accounting for slippage tolerance
1715
- * @param slippageTolerance the allowed tolerated slippage
1716
- * @returns The execution price
1717
- */
1718
- worstExecutionPrice(slippageTolerance) {
1719
- return new sdk.Price(
1720
- this.inputAmount.currency,
1721
- this.outputAmount.currency,
1722
- this.maximumAmountIn(slippageTolerance).quotient,
1723
- this.minimumAmountOut(slippageTolerance).quotient
1724
- );
1893
+ weightedL += getWeightedLFromLastTickTo(tickUpper);
1894
+ return weightedL / BigInt(tickUpper - tickLower);
1895
+ }
1896
+ function getLiquidityFromSqrtRatioX96(ticks, sqrtRatioX96) {
1897
+ const tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1898
+ return FeeCalculator.getLiquidityFromTick(ticks, tick);
1899
+ }
1900
+ function getLiquidityFromTick(ticks, tick) {
1901
+ let liquidity = swapSdkCore.ZERO;
1902
+ if (!ticks?.length)
1903
+ return liquidity;
1904
+ if (tick < ticks[0].index || tick > ticks[ticks.length - 1].index) {
1905
+ return liquidity;
1725
1906
  }
1726
- /**
1727
- * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
1728
- * amount to an output token, making at most `maxHops` hops.
1729
- * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
1730
- * the amount in among multiple routes.
1731
- * @param pools the pools to consider in finding the best trade
1732
- * @param nextAmountIn exact amount of input currency to spend
1733
- * @param currencyOut the desired currency out
1734
- * @param maxNumResults maximum number of results to return
1735
- * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1736
- * @param currentPools used in recursion; the current list of pools
1737
- * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
1738
- * @param bestTrades used in recursion; the current list of best trades
1739
- * @returns The exact in trade
1740
- */
1741
- static async bestTradeExactIn(pools, currencyAmountIn, currencyOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountIn = currencyAmountIn, bestTrades = []) {
1742
- invariant11__default.default(pools.length > 0, "POOLS");
1743
- invariant11__default.default(maxHops > 0, "MAX_HOPS");
1744
- invariant11__default.default(currencyAmountIn === nextAmountIn || currentPools.length > 0, "INVALID_RECURSION");
1745
- const amountIn = nextAmountIn.wrapped;
1746
- const tokenOut = currencyOut.wrapped;
1747
- for (let i = 0; i < pools.length; i++) {
1748
- const pool = pools[i];
1749
- if (!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency))
1750
- continue;
1751
- let amountOut;
1752
- try {
1753
- const [result] = await pool.getOutputAmount(amountIn);
1754
- amountOut = result;
1755
- } catch (error) {
1756
- if (error.isInsufficientInputAmountError) {
1757
- continue;
1758
- }
1759
- throw error;
1760
- }
1761
- if (amountOut.currency.isToken && amountOut.currency.equals(tokenOut)) {
1762
- sdk.sortedInsert(
1763
- bestTrades,
1764
- await Trade.fromRoute(
1765
- new Route([...currentPools, pool], currencyAmountIn.currency, currencyOut),
1766
- currencyAmountIn,
1767
- sdk.TradeType.EXACT_INPUT
1768
- ),
1769
- maxNumResults,
1770
- tradeComparator
1771
- );
1772
- } else if (maxHops > 1 && pools.length > 1) {
1773
- const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1774
- await Trade.bestTradeExactIn(
1775
- poolsExcludingThisPool,
1776
- currencyAmountIn,
1777
- currencyOut,
1778
- {
1779
- maxNumResults,
1780
- maxHops: maxHops - 1
1781
- },
1782
- [...currentPools, pool],
1783
- amountOut,
1784
- bestTrades
1785
- );
1786
- }
1907
+ for (let i = 0; i < ticks.length - 1; ++i) {
1908
+ liquidity += ticks[i].liquidityNet;
1909
+ const lowerTick = ticks[i].index;
1910
+ const upperTick = ticks[i + 1]?.index;
1911
+ if (lowerTick <= tick && tick <= upperTick) {
1912
+ break;
1787
1913
  }
1788
- return bestTrades;
1789
1914
  }
1790
- /**
1791
- * similar to the above method but instead targets a fixed output amount
1792
- * given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
1793
- * to an output token amount, making at most `maxHops` hops
1794
- * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
1795
- * the amount in among multiple routes.
1796
- * @param pools the pools to consider in finding the best trade
1797
- * @param currencyIn the currency to spend
1798
- * @param currencyAmountOut the desired currency amount out
1799
- * @param nextAmountOut the exact amount of currency out
1800
- * @param maxNumResults maximum number of results to return
1801
- * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1802
- * @param currentPools used in recursion; the current list of pools
1803
- * @param bestTrades used in recursion; the current list of best trades
1804
- * @returns The exact out trade
1805
- */
1806
- static async bestTradeExactOut(pools, currencyIn, currencyAmountOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountOut = currencyAmountOut, bestTrades = []) {
1807
- invariant11__default.default(pools.length > 0, "POOLS");
1808
- invariant11__default.default(maxHops > 0, "MAX_HOPS");
1809
- invariant11__default.default(currencyAmountOut === nextAmountOut || currentPools.length > 0, "INVALID_RECURSION");
1810
- const amountOut = nextAmountOut.wrapped;
1811
- const tokenIn = currencyIn.wrapped;
1812
- for (let i = 0; i < pools.length; i++) {
1813
- const pool = pools[i];
1814
- if (!pool.token0.equals(amountOut.currency) && !pool.token1.equals(amountOut.currency))
1815
- continue;
1816
- let amountIn;
1817
- try {
1818
- const [result] = await pool.getInputAmount(amountOut);
1819
- amountIn = result;
1820
- } catch (error) {
1821
- if (error.isInsufficientReservesError) {
1822
- continue;
1823
- }
1824
- throw error;
1825
- }
1826
- if (amountIn.currency.equals(tokenIn)) {
1827
- sdk.sortedInsert(
1828
- bestTrades,
1829
- await Trade.fromRoute(
1830
- new Route([pool, ...currentPools], currencyIn, currencyAmountOut.currency),
1831
- currencyAmountOut,
1832
- sdk.TradeType.EXACT_OUTPUT
1833
- ),
1834
- maxNumResults,
1835
- tradeComparator
1836
- );
1837
- } else if (maxHops > 1 && pools.length > 1) {
1838
- const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1839
- await Trade.bestTradeExactOut(
1840
- poolsExcludingThisPool,
1841
- currencyIn,
1842
- currencyAmountOut,
1843
- {
1844
- maxNumResults,
1845
- maxHops: maxHops - 1
1846
- },
1847
- [pool, ...currentPools],
1848
- amountIn,
1849
- bestTrades
1850
- );
1851
- }
1852
- }
1853
- return bestTrades;
1915
+ return liquidity;
1916
+ }
1917
+ var FEE_BASE = 10n ** 4n;
1918
+ function parseProtocolFees(feeProtocol) {
1919
+ const packed = Number(feeProtocol);
1920
+ if (Number.isNaN(packed)) {
1921
+ throw new Error(`Invalid fee protocol ${feeProtocol}`);
1854
1922
  }
1855
- };
1923
+ const token0ProtocolFee = packed % 2 ** 16;
1924
+ const token1ProtocolFee = packed >> 16;
1925
+ return [new swapSdkCore.Percent(token0ProtocolFee, FEE_BASE), new swapSdkCore.Percent(token1ProtocolFee, FEE_BASE)];
1926
+ }
1927
+ function sqrtRatioX96ToPrice(sqrtRatioX96, currencyA, currencyB) {
1928
+ const ratioX192 = sqrtRatioX96 * sqrtRatioX96;
1929
+ return currencyA.wrapped.sortsBefore(currencyB.wrapped) ? new swapSdkCore.Price(currencyA.wrapped, currencyB.wrapped, Q192, ratioX192) : new swapSdkCore.Price(currencyA.wrapped, currencyB.wrapped, ratioX192, Q192);
1930
+ }
1856
1931
  var IMulticall = [
1857
1932
  {
1858
1933
  inputs: [
@@ -1884,14 +1959,14 @@ var _Multicall = class {
1884
1959
  if (!Array.isArray(calldatas)) {
1885
1960
  calldatas = [calldatas];
1886
1961
  }
1887
- return calldatas.length === 1 ? calldatas[0] : _Multicall.INTERFACE.encodeFunctionData("multicall", [calldatas]);
1962
+ return calldatas.length === 1 ? calldatas[0] : viem.encodeFunctionData({ abi: _Multicall.ABI, functionName: "multicall", args: [calldatas] });
1888
1963
  }
1889
1964
  };
1890
1965
  var Multicall = _Multicall;
1891
- Multicall.INTERFACE = new abi.Interface(IMulticall);
1966
+ Multicall.ABI = IMulticall;
1892
1967
 
1893
- // src/abi/NonfungiblePositionManager.json
1894
- var NonfungiblePositionManager_default = [
1968
+ // src/abi/NonfungiblePositionManager.ts
1969
+ var nonfungiblePositionManagerABI = [
1895
1970
  {
1896
1971
  inputs: [
1897
1972
  { internalType: "address", name: "_deployer", type: "address" },
@@ -2397,8 +2472,8 @@ var NonfungiblePositionManager_default = [
2397
2472
  { stateMutability: "payable", type: "receive" }
2398
2473
  ];
2399
2474
 
2400
- // src/abi/SelfPermit.json
2401
- var SelfPermit_default = [
2475
+ // src/abi/SelfPermit.ts
2476
+ var selfPermitABI = [
2402
2477
  {
2403
2478
  inputs: [
2404
2479
  {
@@ -2564,28 +2639,22 @@ var _SelfPermit = class {
2564
2639
  constructor() {
2565
2640
  }
2566
2641
  static encodePermit(token, options) {
2567
- return isAllowedPermit(options) ? _SelfPermit.INTERFACE.encodeFunctionData("selfPermitAllowed", [
2568
- token.address,
2569
- toHex(options.nonce),
2570
- toHex(options.expiry),
2571
- options.v,
2572
- options.r,
2573
- options.s
2574
- ]) : _SelfPermit.INTERFACE.encodeFunctionData("selfPermit", [
2575
- token.address,
2576
- toHex(options.amount),
2577
- toHex(options.deadline),
2578
- options.v,
2579
- options.r,
2580
- options.s
2581
- ]);
2642
+ return isAllowedPermit(options) ? viem.encodeFunctionData({
2643
+ abi: _SelfPermit.ABI,
2644
+ functionName: "selfPermitAllowed",
2645
+ args: [token.address, BigInt(options.nonce), BigInt(options.expiry), options.v, options.r, options.s]
2646
+ }) : viem.encodeFunctionData({
2647
+ abi: _SelfPermit.ABI,
2648
+ functionName: "selfPermit",
2649
+ args: [token.address, BigInt(options.amount), BigInt(options.deadline), options.v, options.r, options.s]
2650
+ });
2582
2651
  }
2583
2652
  };
2584
2653
  var SelfPermit = _SelfPermit;
2585
- SelfPermit.INTERFACE = new abi.Interface(SelfPermit_default);
2654
+ SelfPermit.ABI = selfPermitABI;
2586
2655
 
2587
- // src/abi/IPeripheryPaymentsWithFee.json
2588
- var IPeripheryPaymentsWithFee_default = [
2656
+ // src/abi/PeripheryPaymentsWithFee.ts
2657
+ var peripheryPaymentsWithFeeABI = [
2589
2658
  {
2590
2659
  inputs: [],
2591
2660
  name: "refundETH",
@@ -2705,46 +2774,47 @@ var _Payments = class {
2705
2774
  constructor() {
2706
2775
  }
2707
2776
  static encodeFeeBips(fee) {
2708
- return toHex(fee.multiply(1e4).quotient);
2777
+ return fee.multiply(1e4).quotient;
2709
2778
  }
2710
2779
  static encodeUnwrapWETH9(amountMinimum, recipient, feeOptions) {
2711
2780
  recipient = sdk.validateAndParseAddress(recipient);
2712
2781
  if (feeOptions) {
2713
2782
  const feeBips = this.encodeFeeBips(feeOptions.fee);
2714
2783
  const feeRecipient = sdk.validateAndParseAddress(feeOptions.recipient);
2715
- return _Payments.INTERFACE.encodeFunctionData("unwrapWETH9WithFee", [
2716
- toHex(amountMinimum),
2717
- recipient,
2718
- feeBips,
2719
- feeRecipient
2720
- ]);
2784
+ return viem.encodeFunctionData({
2785
+ abi: _Payments.ABI,
2786
+ functionName: "unwrapWETH9WithFee",
2787
+ args: [amountMinimum, recipient, feeBips, feeRecipient]
2788
+ });
2721
2789
  }
2722
- return _Payments.INTERFACE.encodeFunctionData("unwrapWETH9", [toHex(amountMinimum), recipient]);
2790
+ return viem.encodeFunctionData({ abi: _Payments.ABI, functionName: "unwrapWETH9", args: [amountMinimum, recipient] });
2723
2791
  }
2724
2792
  static encodeSweepToken(token, amountMinimum, recipient, feeOptions) {
2725
2793
  recipient = sdk.validateAndParseAddress(recipient);
2726
2794
  if (feeOptions) {
2727
2795
  const feeBips = this.encodeFeeBips(feeOptions.fee);
2728
2796
  const feeRecipient = sdk.validateAndParseAddress(feeOptions.recipient);
2729
- return _Payments.INTERFACE.encodeFunctionData("sweepTokenWithFee", [
2730
- token.address,
2731
- toHex(amountMinimum),
2732
- recipient,
2733
- feeBips,
2734
- feeRecipient
2735
- ]);
2797
+ return viem.encodeFunctionData({
2798
+ abi: _Payments.ABI,
2799
+ functionName: "sweepTokenWithFee",
2800
+ args: [token.address, amountMinimum, recipient, feeBips, feeRecipient]
2801
+ });
2736
2802
  }
2737
- return _Payments.INTERFACE.encodeFunctionData("sweepToken", [token.address, toHex(amountMinimum), recipient]);
2803
+ return viem.encodeFunctionData({
2804
+ abi: _Payments.ABI,
2805
+ functionName: "sweepToken",
2806
+ args: [token.address, amountMinimum, recipient]
2807
+ });
2738
2808
  }
2739
2809
  static encodeRefundETH() {
2740
- return _Payments.INTERFACE.encodeFunctionData("refundETH");
2810
+ return viem.encodeFunctionData({ abi: _Payments.ABI, functionName: "refundETH" });
2741
2811
  }
2742
2812
  };
2743
2813
  var Payments = _Payments;
2744
- Payments.INTERFACE = new abi.Interface(IPeripheryPaymentsWithFee_default);
2814
+ Payments.ABI = peripheryPaymentsWithFeeABI;
2745
2815
 
2746
2816
  // src/nonfungiblePositionManager.ts
2747
- var MaxUint128 = toHex(2n ** 128n - 1n);
2817
+ var MaxUint128 = 2n ** 128n - 1n;
2748
2818
  function isMint(options) {
2749
2819
  return Object.keys(options).some((k) => k === "recipient");
2750
2820
  }
@@ -2756,12 +2826,11 @@ var _NonfungiblePositionManager = class {
2756
2826
  constructor() {
2757
2827
  }
2758
2828
  static encodeCreate(pool) {
2759
- return _NonfungiblePositionManager.INTERFACE.encodeFunctionData("createAndInitializePoolIfNecessary", [
2760
- pool.token0.address,
2761
- pool.token1.address,
2762
- pool.fee,
2763
- toHex(pool.sqrtRatioX96)
2764
- ]);
2829
+ return viem.encodeFunctionData({
2830
+ abi: _NonfungiblePositionManager.ABI,
2831
+ functionName: "createAndInitializePoolIfNecessary",
2832
+ args: [pool.token0.address, pool.token1.address, pool.fee, pool.sqrtRatioX96]
2833
+ });
2765
2834
  }
2766
2835
  static createCallParameters(pool) {
2767
2836
  return {
@@ -2770,13 +2839,13 @@ var _NonfungiblePositionManager = class {
2770
2839
  };
2771
2840
  }
2772
2841
  static addCallParameters(position, options) {
2773
- invariant11__default.default(position.liquidity > ZERO, "ZERO_LIQUIDITY");
2842
+ invariant9__default.default(position.liquidity > ZERO, "ZERO_LIQUIDITY");
2774
2843
  const calldatas = [];
2775
2844
  const { amount0: amount0Desired, amount1: amount1Desired } = position.mintAmounts;
2776
2845
  const minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
2777
- const amount0Min = toHex(minimumAmounts.amount0);
2778
- const amount1Min = toHex(minimumAmounts.amount1);
2779
- const deadline = toHex(options.deadline);
2846
+ const amount0Min = minimumAmounts.amount0;
2847
+ const amount1Min = minimumAmounts.amount1;
2848
+ const deadline = BigInt(options.deadline);
2780
2849
  if (isMint(options) && options.createPool) {
2781
2850
  calldatas.push(this.encodeCreate(position.pool));
2782
2851
  }
@@ -2789,40 +2858,48 @@ var _NonfungiblePositionManager = class {
2789
2858
  if (isMint(options)) {
2790
2859
  const recipient = sdk.validateAndParseAddress(options.recipient);
2791
2860
  calldatas.push(
2792
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("mint", [
2793
- {
2794
- token0: position.pool.token0.address,
2795
- token1: position.pool.token1.address,
2796
- fee: position.pool.fee,
2797
- tickLower: position.tickLower,
2798
- tickUpper: position.tickUpper,
2799
- amount0Desired: toHex(amount0Desired),
2800
- amount1Desired: toHex(amount1Desired),
2801
- amount0Min,
2802
- amount1Min,
2803
- recipient,
2804
- deadline
2805
- }
2806
- ])
2861
+ viem.encodeFunctionData({
2862
+ abi: _NonfungiblePositionManager.ABI,
2863
+ functionName: "mint",
2864
+ args: [
2865
+ {
2866
+ token0: position.pool.token0.address,
2867
+ token1: position.pool.token1.address,
2868
+ fee: position.pool.fee,
2869
+ tickLower: position.tickLower,
2870
+ tickUpper: position.tickUpper,
2871
+ amount0Desired,
2872
+ amount1Desired,
2873
+ amount0Min,
2874
+ amount1Min,
2875
+ recipient,
2876
+ deadline
2877
+ }
2878
+ ]
2879
+ })
2807
2880
  );
2808
2881
  } else {
2809
2882
  calldatas.push(
2810
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("increaseLiquidity", [
2811
- {
2812
- tokenId: toHex(options.tokenId),
2813
- amount0Desired: toHex(amount0Desired),
2814
- amount1Desired: toHex(amount1Desired),
2815
- amount0Min,
2816
- amount1Min,
2817
- deadline
2818
- }
2819
- ])
2883
+ viem.encodeFunctionData({
2884
+ abi: _NonfungiblePositionManager.ABI,
2885
+ functionName: "increaseLiquidity",
2886
+ args: [
2887
+ {
2888
+ tokenId: BigInt(options.tokenId),
2889
+ amount0Desired,
2890
+ amount1Desired,
2891
+ amount0Min,
2892
+ amount1Min,
2893
+ deadline
2894
+ }
2895
+ ]
2896
+ })
2820
2897
  );
2821
2898
  }
2822
2899
  let value = toHex(0);
2823
2900
  if (options.useNative) {
2824
2901
  const { wrapped } = options.useNative;
2825
- invariant11__default.default(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
2902
+ invariant9__default.default(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
2826
2903
  const wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired;
2827
2904
  if (wrappedValue > ZERO) {
2828
2905
  calldatas.push(Payments.encodeRefundETH());
@@ -2836,18 +2913,22 @@ var _NonfungiblePositionManager = class {
2836
2913
  }
2837
2914
  static encodeCollect(options) {
2838
2915
  const calldatas = [];
2839
- const tokenId = toHex(options.tokenId);
2916
+ const tokenId = BigInt(options.tokenId);
2840
2917
  const involvesETH = options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative;
2841
2918
  const recipient = sdk.validateAndParseAddress(options.recipient);
2842
2919
  calldatas.push(
2843
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("collect", [
2844
- {
2845
- tokenId,
2846
- recipient: involvesETH ? ADDRESS_ZERO : recipient,
2847
- amount0Max: MaxUint128,
2848
- amount1Max: MaxUint128
2849
- }
2850
- ])
2920
+ viem.encodeFunctionData({
2921
+ abi: _NonfungiblePositionManager.ABI,
2922
+ functionName: "collect",
2923
+ args: [
2924
+ {
2925
+ tokenId,
2926
+ recipient: involvesETH ? ADDRESS_ZERO : recipient,
2927
+ amount0Max: MaxUint128,
2928
+ amount1Max: MaxUint128
2929
+ }
2930
+ ]
2931
+ })
2851
2932
  );
2852
2933
  if (involvesETH) {
2853
2934
  const ethAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed0.quotient : options.expectedCurrencyOwed1.quotient;
@@ -2873,40 +2954,48 @@ var _NonfungiblePositionManager = class {
2873
2954
  */
2874
2955
  static removeCallParameters(position, options) {
2875
2956
  const calldatas = [];
2876
- const deadline = toHex(options.deadline);
2877
- const tokenId = toHex(options.tokenId);
2957
+ const deadline = BigInt(options.deadline);
2958
+ const tokenId = BigInt(options.tokenId);
2878
2959
  const partialPosition = new Position({
2879
2960
  pool: position.pool,
2880
2961
  liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
2881
2962
  tickLower: position.tickLower,
2882
2963
  tickUpper: position.tickUpper
2883
2964
  });
2884
- invariant11__default.default(partialPosition.liquidity > ZERO, "ZERO_LIQUIDITY");
2965
+ invariant9__default.default(partialPosition.liquidity > ZERO, "ZERO_LIQUIDITY");
2885
2966
  const { amount0: amount0Min, amount1: amount1Min } = partialPosition.burnAmountsWithSlippage(
2886
2967
  options.slippageTolerance
2887
2968
  );
2888
2969
  if (options.permit) {
2889
2970
  calldatas.push(
2890
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("permit", [
2891
- sdk.validateAndParseAddress(options.permit.spender),
2892
- tokenId,
2893
- toHex(options.permit.deadline),
2894
- options.permit.v,
2895
- options.permit.r,
2896
- options.permit.s
2897
- ])
2971
+ viem.encodeFunctionData({
2972
+ abi: _NonfungiblePositionManager.ABI,
2973
+ functionName: "permit",
2974
+ args: [
2975
+ sdk.validateAndParseAddress(options.permit.spender),
2976
+ tokenId,
2977
+ BigInt(options.permit.deadline),
2978
+ options.permit.v,
2979
+ options.permit.r,
2980
+ options.permit.s
2981
+ ]
2982
+ })
2898
2983
  );
2899
2984
  }
2900
2985
  calldatas.push(
2901
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("decreaseLiquidity", [
2902
- {
2903
- tokenId,
2904
- liquidity: toHex(partialPosition.liquidity),
2905
- amount0Min: toHex(amount0Min),
2906
- amount1Min: toHex(amount1Min),
2907
- deadline
2908
- }
2909
- ])
2986
+ viem.encodeFunctionData({
2987
+ abi: _NonfungiblePositionManager.ABI,
2988
+ functionName: "decreaseLiquidity",
2989
+ args: [
2990
+ {
2991
+ tokenId,
2992
+ liquidity: partialPosition.liquidity,
2993
+ amount0Min,
2994
+ amount1Min,
2995
+ deadline
2996
+ }
2997
+ ]
2998
+ })
2910
2999
  );
2911
3000
  const { expectedCurrencyOwed0, expectedCurrencyOwed1, ...rest } = options.collectOptions;
2912
3001
  calldatas.push(
@@ -2924,10 +3013,12 @@ var _NonfungiblePositionManager = class {
2924
3013
  );
2925
3014
  if (options.liquidityPercentage.equalTo(ONE)) {
2926
3015
  if (options.burnToken) {
2927
- calldatas.push(_NonfungiblePositionManager.INTERFACE.encodeFunctionData("burn", [tokenId]));
3016
+ calldatas.push(
3017
+ viem.encodeFunctionData({ abi: _NonfungiblePositionManager.ABI, functionName: "burn", args: [tokenId] })
3018
+ );
2928
3019
  }
2929
3020
  } else {
2930
- invariant11__default.default(options.burnToken !== true, "CANNOT_BURN");
3021
+ invariant9__default.default(options.burnToken !== true, "CANNOT_BURN");
2931
3022
  }
2932
3023
  return {
2933
3024
  calldata: Multicall.encodeMulticall(calldatas),
@@ -2939,16 +3030,17 @@ var _NonfungiblePositionManager = class {
2939
3030
  const sender = sdk.validateAndParseAddress(options.sender);
2940
3031
  let calldata;
2941
3032
  if (options.data) {
2942
- calldata = _NonfungiblePositionManager.INTERFACE.encodeFunctionData(
2943
- "safeTransferFrom(address,address,uint256,bytes)",
2944
- [sender, recipient, toHex(options.tokenId), options.data]
2945
- );
3033
+ calldata = viem.encodeFunctionData({
3034
+ abi: _NonfungiblePositionManager.ABI,
3035
+ functionName: "safeTransferFrom",
3036
+ args: [sender, recipient, BigInt(options.tokenId), options.data]
3037
+ });
2946
3038
  } else {
2947
- calldata = _NonfungiblePositionManager.INTERFACE.encodeFunctionData("safeTransferFrom(address,address,uint256)", [
2948
- sender,
2949
- recipient,
2950
- toHex(options.tokenId)
2951
- ]);
3039
+ calldata = viem.encodeFunctionData({
3040
+ abi: _NonfungiblePositionManager.ABI,
3041
+ functionName: "safeTransferFrom",
3042
+ args: [sender, recipient, BigInt(options.tokenId)]
3043
+ });
2952
3044
  }
2953
3045
  return {
2954
3046
  calldata,
@@ -2957,10 +3049,10 @@ var _NonfungiblePositionManager = class {
2957
3049
  }
2958
3050
  };
2959
3051
  var NonfungiblePositionManager = _NonfungiblePositionManager;
2960
- NonfungiblePositionManager.INTERFACE = new abi.Interface(NonfungiblePositionManager_default);
3052
+ NonfungiblePositionManager.ABI = nonfungiblePositionManagerABI;
2961
3053
 
2962
- // src/abi/Quoter.json
2963
- var Quoter_default = [
3054
+ // src/abi/Quoter.ts
3055
+ var quoterABI = [
2964
3056
  {
2965
3057
  inputs: [
2966
3058
  {
@@ -3172,8 +3264,8 @@ var Quoter_default = [
3172
3264
  }
3173
3265
  ];
3174
3266
 
3175
- // src/abi/QuoterV2.json
3176
- var QuoterV2_default = [
3267
+ // src/abi/QuoterV2.ts
3268
+ var quoterV2ABI = [
3177
3269
  {
3178
3270
  inputs: [
3179
3271
  {
@@ -3474,19 +3566,19 @@ var SwapQuoter = class {
3474
3566
  */
3475
3567
  static quoteCallParameters(route, amount, tradeType, options = {}) {
3476
3568
  const singleHop = route.pools.length === 1;
3477
- const quoteAmount = toHex(amount.quotient);
3569
+ const quoteAmount = amount.quotient;
3478
3570
  let calldata;
3479
- const swapInterface = options.useQuoterV2 ? this.V2INTERFACE : this.V1INTERFACE;
3571
+ const swapAbi = options.useQuoterV2 ? this.V2ABI : this.V1ABI;
3480
3572
  if (singleHop) {
3481
3573
  const baseQuoteParams = {
3482
3574
  tokenIn: route.tokenPath[0].address,
3483
3575
  tokenOut: route.tokenPath[1].address,
3484
3576
  fee: route.pools[0].fee,
3485
- sqrtPriceLimitX96: toHex(options?.sqrtPriceLimitX96 ?? 0)
3577
+ sqrtPriceLimitX96: BigInt(options?.sqrtPriceLimitX96 ?? 0)
3486
3578
  };
3487
3579
  const v2QuoteParams = {
3488
3580
  ...baseQuoteParams,
3489
- ...tradeType == sdk.TradeType.EXACT_INPUT ? { amountIn: quoteAmount } : { amount: quoteAmount }
3581
+ ...tradeType === swapSdkCore.TradeType.EXACT_INPUT ? { amountIn: quoteAmount } : { amount: quoteAmount }
3490
3582
  };
3491
3583
  const v1QuoteParams = [
3492
3584
  baseQuoteParams.tokenIn,
@@ -3495,16 +3587,31 @@ var SwapQuoter = class {
3495
3587
  quoteAmount,
3496
3588
  baseQuoteParams.sqrtPriceLimitX96
3497
3589
  ];
3498
- const tradeTypeFunctionName = tradeType === sdk.TradeType.EXACT_INPUT ? "quoteExactInputSingle" : "quoteExactOutputSingle";
3499
- calldata = swapInterface.encodeFunctionData(
3500
- tradeTypeFunctionName,
3501
- options.useQuoterV2 ? [v2QuoteParams] : v1QuoteParams
3502
- );
3590
+ const tradeTypeFunctionName = tradeType === swapSdkCore.TradeType.EXACT_INPUT ? "quoteExactInputSingle" : "quoteExactOutputSingle";
3591
+ if (options.useQuoterV2) {
3592
+ calldata = viem.encodeFunctionData({
3593
+ abi: this.V2ABI,
3594
+ functionName: tradeTypeFunctionName,
3595
+ // @ts-ignore // FIXME
3596
+ args: [v2QuoteParams]
3597
+ });
3598
+ } else {
3599
+ calldata = viem.encodeFunctionData({
3600
+ abi: this.V1ABI,
3601
+ functionName: tradeTypeFunctionName,
3602
+ args: v1QuoteParams
3603
+ });
3604
+ }
3503
3605
  } else {
3504
- invariant11__default.default(options?.sqrtPriceLimitX96 === void 0, "MULTIHOP_PRICE_LIMIT");
3505
- const path = encodeRouteToPath(route, tradeType === sdk.TradeType.EXACT_OUTPUT);
3506
- const tradeTypeFunctionName = tradeType === sdk.TradeType.EXACT_INPUT ? "quoteExactInput" : "quoteExactOutput";
3507
- calldata = swapInterface.encodeFunctionData(tradeTypeFunctionName, [path, quoteAmount]);
3606
+ invariant9__default.default(options?.sqrtPriceLimitX96 === void 0, "MULTIHOP_PRICE_LIMIT");
3607
+ const path = encodeRouteToPath(route, tradeType === swapSdkCore.TradeType.EXACT_OUTPUT);
3608
+ const tradeTypeFunctionName = tradeType === swapSdkCore.TradeType.EXACT_INPUT ? "quoteExactInput" : "quoteExactOutput";
3609
+ calldata = viem.encodeFunctionData({
3610
+ // @ts-ignore
3611
+ abi: swapAbi,
3612
+ functionName: tradeTypeFunctionName,
3613
+ args: [path, quoteAmount]
3614
+ });
3508
3615
  }
3509
3616
  return {
3510
3617
  calldata,
@@ -3512,11 +3619,11 @@ var SwapQuoter = class {
3512
3619
  };
3513
3620
  }
3514
3621
  };
3515
- SwapQuoter.V1INTERFACE = new abi.Interface(Quoter_default);
3516
- SwapQuoter.V2INTERFACE = new abi.Interface(QuoterV2_default);
3622
+ SwapQuoter.V1ABI = quoterABI;
3623
+ SwapQuoter.V2ABI = quoterV2ABI;
3517
3624
 
3518
- // src/abi/V3Staker.json
3519
- var V3Staker_default = [
3625
+ // src/abi/V3Staker.ts
3626
+ var v3StakerABI = [
3520
3627
  {
3521
3628
  inputs: [
3522
3629
  {
@@ -4236,15 +4343,20 @@ var _Staker = class {
4236
4343
  static encodeClaim(incentiveKey, options) {
4237
4344
  const calldatas = [];
4238
4345
  calldatas.push(
4239
- _Staker.INTERFACE.encodeFunctionData("unstakeToken", [
4240
- this._encodeIncentiveKey(incentiveKey),
4241
- toHex(options.tokenId)
4242
- ])
4346
+ viem.encodeFunctionData({
4347
+ abi: _Staker.ABI,
4348
+ functionName: "unstakeToken",
4349
+ args: [this._encodeIncentiveKey(incentiveKey), BigInt(options.tokenId)]
4350
+ })
4243
4351
  );
4244
4352
  const recipient = sdk.validateAndParseAddress(options.recipient);
4245
4353
  const amount = options.amount ?? 0;
4246
4354
  calldatas.push(
4247
- _Staker.INTERFACE.encodeFunctionData("claimReward", [incentiveKey.rewardToken.address, recipient, toHex(amount)])
4355
+ viem.encodeFunctionData({
4356
+ abi: _Staker.ABI,
4357
+ functionName: "claimReward",
4358
+ args: [incentiveKey.rewardToken.address, recipient, BigInt(amount)]
4359
+ })
4248
4360
  );
4249
4361
  return calldatas;
4250
4362
  }
@@ -4264,10 +4376,11 @@ var _Staker = class {
4264
4376
  const incentiveKey = incentiveKeys[i];
4265
4377
  calldatas = calldatas.concat(this.encodeClaim(incentiveKey, options));
4266
4378
  calldatas.push(
4267
- _Staker.INTERFACE.encodeFunctionData("stakeToken", [
4268
- this._encodeIncentiveKey(incentiveKey),
4269
- toHex(options.tokenId)
4270
- ])
4379
+ viem.encodeFunctionData({
4380
+ abi: _Staker.ABI,
4381
+ functionName: "stakeToken",
4382
+ args: [this._encodeIncentiveKey(incentiveKey), BigInt(options.tokenId)]
4383
+ })
4271
4384
  );
4272
4385
  }
4273
4386
  return {
@@ -4295,11 +4408,11 @@ var _Staker = class {
4295
4408
  }
4296
4409
  const owner = sdk.validateAndParseAddress(withdrawOptions.owner);
4297
4410
  calldatas.push(
4298
- _Staker.INTERFACE.encodeFunctionData("withdrawToken", [
4299
- toHex(withdrawOptions.tokenId),
4300
- owner,
4301
- withdrawOptions.data ? withdrawOptions.data : toHex(0)
4302
- ])
4411
+ viem.encodeFunctionData({
4412
+ abi: _Staker.ABI,
4413
+ functionName: "withdrawToken",
4414
+ args: [BigInt(withdrawOptions.tokenId), owner, toHex(0)]
4415
+ })
4303
4416
  );
4304
4417
  return {
4305
4418
  calldata: Multicall.encodeMulticall(calldatas),
@@ -4320,16 +4433,18 @@ var _Staker = class {
4320
4433
  const incentiveKey = incentiveKeys[i];
4321
4434
  keys.push(this._encodeIncentiveKey(incentiveKey));
4322
4435
  }
4323
- data = abi.defaultAbiCoder.encode([`${_Staker.INCENTIVE_KEY_ABI}[]`], [keys]);
4436
+ data = viem.encodeAbiParameters(viem.parseAbiParameters([`${_Staker.INCENTIVE_KEY_ABI}[]`]), [keys]);
4324
4437
  } else {
4325
- data = abi.defaultAbiCoder.encode([_Staker.INCENTIVE_KEY_ABI], [this._encodeIncentiveKey(incentiveKeys[0])]);
4438
+ data = viem.encodeAbiParameters(viem.parseAbiParameters(_Staker.INCENTIVE_KEY_ABI), [
4439
+ this._encodeIncentiveKey(incentiveKeys[0])
4440
+ ]);
4326
4441
  }
4327
4442
  return data;
4328
4443
  }
4329
4444
  /**
4330
4445
  *
4331
4446
  * @param incentiveKey An `IncentiveKey` which represents a unique staking program.
4332
- * @returns An encoded IncentiveKey to be read by ethers
4447
+ * @returns An encoded IncentiveKey to be read by viem
4333
4448
  */
4334
4449
  static _encodeIncentiveKey(incentiveKey) {
4335
4450
  const { token0, token1, fee } = incentiveKey.pool;
@@ -4337,18 +4452,18 @@ var _Staker = class {
4337
4452
  return {
4338
4453
  rewardToken: incentiveKey.rewardToken.address,
4339
4454
  pool: Pool.getAddress(token0, token1, fee),
4340
- startTime: toHex(incentiveKey.startTime),
4341
- endTime: toHex(incentiveKey.endTime),
4455
+ startTime: BigInt(incentiveKey.startTime),
4456
+ endTime: BigInt(incentiveKey.endTime),
4342
4457
  refundee
4343
4458
  };
4344
4459
  }
4345
4460
  };
4346
4461
  var Staker = _Staker;
4347
- Staker.INTERFACE = new abi.Interface(V3Staker_default);
4462
+ Staker.ABI = v3StakerABI;
4348
4463
  Staker.INCENTIVE_KEY_ABI = "tuple(address rewardToken, address pool, uint256 startTime, uint256 endTime, address refundee)";
4349
4464
 
4350
- // src/abi/SwapRouter.json
4351
- var SwapRouter_default = [
4465
+ // src/abi/SwapRouter.ts
4466
+ var swapRouterABI = [
4352
4467
  {
4353
4468
  inputs: [
4354
4469
  {
@@ -4951,11 +5066,11 @@ var _SwapRouter = class {
4951
5066
  const sampleTrade = trades[0];
4952
5067
  const tokenIn = sampleTrade.inputAmount.currency.wrapped;
4953
5068
  const tokenOut = sampleTrade.outputAmount.currency.wrapped;
4954
- invariant11__default.default(
5069
+ invariant9__default.default(
4955
5070
  trades.every((trade) => trade.inputAmount.currency.wrapped.equals(tokenIn)),
4956
5071
  "TOKEN_IN_DIFF"
4957
5072
  );
4958
- invariant11__default.default(
5073
+ invariant9__default.default(
4959
5074
  trades.every((trade) => trade.outputAmount.currency.wrapped.equals(tokenOut)),
4960
5075
  "TOKEN_OUT_DIFF"
4961
5076
  );
@@ -4972,15 +5087,15 @@ var _SwapRouter = class {
4972
5087
  const routerMustCustody = outputIsNative || !!options.fee;
4973
5088
  const totalValue = inputIsNative ? trades.reduce((sum, trade) => sum.add(trade.maximumAmountIn(options.slippageTolerance)), ZERO_IN) : ZERO_IN;
4974
5089
  if (options.inputTokenPermit) {
4975
- invariant11__default.default(sampleTrade.inputAmount.currency.isToken, "NON_TOKEN_PERMIT");
5090
+ invariant9__default.default(sampleTrade.inputAmount.currency.isToken, "NON_TOKEN_PERMIT");
4976
5091
  calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency, options.inputTokenPermit));
4977
5092
  }
4978
5093
  const recipient = sdk.validateAndParseAddress(options.recipient);
4979
- const deadline = toHex(options.deadline);
5094
+ const deadline = BigInt(options.deadline);
4980
5095
  for (const trade of trades) {
4981
5096
  for (const { route, inputAmount, outputAmount } of trade.swaps) {
4982
- const amountIn = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
4983
- const amountOut = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient);
5097
+ const amountIn = BigInt(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
5098
+ const amountOut = BigInt(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient);
4984
5099
  const singleHop = route.pools.length === 1;
4985
5100
  if (singleHop) {
4986
5101
  if (trade.tradeType === sdk.TradeType.EXACT_INPUT) {
@@ -4992,9 +5107,15 @@ var _SwapRouter = class {
4992
5107
  deadline,
4993
5108
  amountIn,
4994
5109
  amountOutMinimum: amountOut,
4995
- sqrtPriceLimitX96: toHex(options.sqrtPriceLimitX96 ?? 0)
5110
+ sqrtPriceLimitX96: BigInt(options.sqrtPriceLimitX96 ?? 0)
4996
5111
  };
4997
- calldatas.push(_SwapRouter.INTERFACE.encodeFunctionData("exactInputSingle", [exactInputSingleParams]));
5112
+ calldatas.push(
5113
+ viem.encodeFunctionData({
5114
+ abi: _SwapRouter.ABI,
5115
+ functionName: "exactInputSingle",
5116
+ args: [exactInputSingleParams]
5117
+ })
5118
+ );
4998
5119
  } else {
4999
5120
  const exactOutputSingleParams = {
5000
5121
  tokenIn: route.tokenPath[0].address,
@@ -5004,12 +5125,18 @@ var _SwapRouter = class {
5004
5125
  deadline,
5005
5126
  amountOut,
5006
5127
  amountInMaximum: amountIn,
5007
- sqrtPriceLimitX96: toHex(options.sqrtPriceLimitX96 ?? 0)
5128
+ sqrtPriceLimitX96: BigInt(options.sqrtPriceLimitX96 ?? 0)
5008
5129
  };
5009
- calldatas.push(_SwapRouter.INTERFACE.encodeFunctionData("exactOutputSingle", [exactOutputSingleParams]));
5130
+ calldatas.push(
5131
+ viem.encodeFunctionData({
5132
+ abi: _SwapRouter.ABI,
5133
+ functionName: "exactOutputSingle",
5134
+ args: [exactOutputSingleParams]
5135
+ })
5136
+ );
5010
5137
  }
5011
5138
  } else {
5012
- invariant11__default.default(options.sqrtPriceLimitX96 === void 0, "MULTIHOP_PRICE_LIMIT");
5139
+ invariant9__default.default(options.sqrtPriceLimitX96 === void 0, "MULTIHOP_PRICE_LIMIT");
5013
5140
  const path = encodeRouteToPath(route, trade.tradeType === sdk.TradeType.EXACT_OUTPUT);
5014
5141
  if (trade.tradeType === sdk.TradeType.EXACT_INPUT) {
5015
5142
  const exactInputParams = {
@@ -5019,7 +5146,9 @@ var _SwapRouter = class {
5019
5146
  amountIn,
5020
5147
  amountOutMinimum: amountOut
5021
5148
  };
5022
- calldatas.push(_SwapRouter.INTERFACE.encodeFunctionData("exactInput", [exactInputParams]));
5149
+ calldatas.push(
5150
+ viem.encodeFunctionData({ abi: _SwapRouter.ABI, functionName: "exactInput", args: [exactInputParams] })
5151
+ );
5023
5152
  } else {
5024
5153
  const exactOutputParams = {
5025
5154
  path,
@@ -5028,7 +5157,9 @@ var _SwapRouter = class {
5028
5157
  amountOut,
5029
5158
  amountInMaximum: amountIn
5030
5159
  };
5031
- calldatas.push(_SwapRouter.INTERFACE.encodeFunctionData("exactOutput", [exactOutputParams]));
5160
+ calldatas.push(
5161
+ viem.encodeFunctionData({ abi: _SwapRouter.ABI, functionName: "exactOutput", args: [exactOutputParams] })
5162
+ );
5032
5163
  }
5033
5164
  }
5034
5165
  }
@@ -5061,10 +5192,11 @@ var _SwapRouter = class {
5061
5192
  }
5062
5193
  };
5063
5194
  var SwapRouter = _SwapRouter;
5064
- SwapRouter.INTERFACE = new abi.Interface(SwapRouter_default);
5195
+ // public static INTERFACE: Interface = new Interface(ISwapRouter)
5196
+ SwapRouter.ABI = swapRouterABI;
5065
5197
 
5066
- // src/abi/MasterChefV3.json
5067
- var MasterChefV3_default = [
5198
+ // src/abi/MasterChefV3.ts
5199
+ var masterChefV3ABI = [
5068
5200
  {
5069
5201
  inputs: [
5070
5202
  { internalType: "contract IERC20", name: "_CAKE", type: "address" },
@@ -5752,14 +5884,14 @@ var _MasterChefV3 = class {
5752
5884
  // Copy from NonfungiblePositionManager
5753
5885
  // Only support increaseLiquidity
5754
5886
  static addCallParameters(position, options) {
5755
- invariant11__default.default(position.liquidity > sdk.ZERO, "ZERO_LIQUIDITY");
5887
+ invariant9__default.default(position.liquidity > sdk.ZERO, "ZERO_LIQUIDITY");
5756
5888
  const calldatas = [];
5757
5889
  const { amount0: amount0Desired, amount1: amount1Desired } = position.mintAmounts;
5758
5890
  const minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
5759
- const amount0Min = toHex(minimumAmounts.amount0);
5760
- const amount1Min = toHex(minimumAmounts.amount1);
5761
- const deadline = toHex(options.deadline);
5762
- invariant11__default.default(!isMint(options), "NO_MINT_SUPPORT");
5891
+ const amount0Min = BigInt(minimumAmounts.amount0);
5892
+ const amount1Min = BigInt(minimumAmounts.amount1);
5893
+ const deadline = BigInt(options.deadline);
5894
+ invariant9__default.default(!isMint(options), "NO_MINT_SUPPORT");
5763
5895
  if (options.token0Permit) {
5764
5896
  calldatas.push(SelfPermit.encodePermit(position.pool.token0, options.token0Permit));
5765
5897
  }
@@ -5767,21 +5899,25 @@ var _MasterChefV3 = class {
5767
5899
  calldatas.push(SelfPermit.encodePermit(position.pool.token1, options.token1Permit));
5768
5900
  }
5769
5901
  calldatas.push(
5770
- _MasterChefV3.INTERFACE.encodeFunctionData("increaseLiquidity", [
5771
- {
5772
- tokenId: toHex(options.tokenId),
5773
- amount0Desired: toHex(amount0Desired),
5774
- amount1Desired: toHex(amount1Desired),
5775
- amount0Min,
5776
- amount1Min,
5777
- deadline
5778
- }
5779
- ])
5902
+ viem.encodeFunctionData({
5903
+ abi: _MasterChefV3.ABI,
5904
+ functionName: "increaseLiquidity",
5905
+ args: [
5906
+ {
5907
+ tokenId: BigInt(options.tokenId),
5908
+ amount0Desired,
5909
+ amount1Desired,
5910
+ amount0Min,
5911
+ amount1Min,
5912
+ deadline
5913
+ }
5914
+ ]
5915
+ })
5780
5916
  );
5781
5917
  let value = toHex(0);
5782
5918
  if (options.useNative) {
5783
5919
  const { wrapped } = options.useNative;
5784
- invariant11__default.default(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
5920
+ invariant9__default.default(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
5785
5921
  const wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired;
5786
5922
  value = toHex(wrappedValue);
5787
5923
  }
@@ -5793,18 +5929,22 @@ var _MasterChefV3 = class {
5793
5929
  // Copy from NonfungiblePositionManager
5794
5930
  static encodeCollect(options) {
5795
5931
  const calldatas = [];
5796
- const tokenId = toHex(options.tokenId);
5932
+ const tokenId = BigInt(options.tokenId);
5797
5933
  const involvesETH = options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative;
5798
5934
  const recipient = sdk.validateAndParseAddress(options.recipient);
5799
5935
  calldatas.push(
5800
- _MasterChefV3.INTERFACE.encodeFunctionData("collect", [
5801
- {
5802
- tokenId,
5803
- recipient: involvesETH ? ADDRESS_ZERO : recipient,
5804
- amount0Max: MaxUint128,
5805
- amount1Max: MaxUint128
5806
- }
5807
- ])
5936
+ viem.encodeFunctionData({
5937
+ abi: _MasterChefV3.ABI,
5938
+ functionName: "collect",
5939
+ args: [
5940
+ {
5941
+ tokenId,
5942
+ recipient: involvesETH ? ADDRESS_ZERO : recipient,
5943
+ amount0Max: MaxUint128,
5944
+ amount1Max: MaxUint128
5945
+ }
5946
+ ]
5947
+ })
5808
5948
  );
5809
5949
  if (involvesETH) {
5810
5950
  const ethAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed0.quotient : options.expectedCurrencyOwed1.quotient;
@@ -5824,40 +5964,35 @@ var _MasterChefV3 = class {
5824
5964
  }
5825
5965
  static removeCallParameters(position, options) {
5826
5966
  const calldatas = [];
5827
- const deadline = toHex(options.deadline);
5828
- const tokenId = toHex(options.tokenId);
5967
+ const deadline = BigInt(options.deadline);
5968
+ const tokenId = BigInt(options.tokenId);
5829
5969
  const partialPosition = new Position({
5830
5970
  pool: position.pool,
5831
5971
  liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
5832
5972
  tickLower: position.tickLower,
5833
5973
  tickUpper: position.tickUpper
5834
5974
  });
5835
- invariant11__default.default(partialPosition.liquidity > sdk.ZERO, "ZERO_LIQUIDITY");
5975
+ invariant9__default.default(partialPosition.liquidity > sdk.ZERO, "ZERO_LIQUIDITY");
5836
5976
  const { amount0: amount0Min, amount1: amount1Min } = partialPosition.burnAmountsWithSlippage(
5837
5977
  options.slippageTolerance
5838
5978
  );
5839
5979
  if (options.permit) {
5840
- calldatas.push(
5841
- _MasterChefV3.INTERFACE.encodeFunctionData("permit", [
5842
- sdk.validateAndParseAddress(options.permit.spender),
5843
- tokenId,
5844
- toHex(options.permit.deadline),
5845
- options.permit.v,
5846
- options.permit.r,
5847
- options.permit.s
5848
- ])
5849
- );
5980
+ throw new Error("NOT_IMPLEMENTED");
5850
5981
  }
5851
5982
  calldatas.push(
5852
- _MasterChefV3.INTERFACE.encodeFunctionData("decreaseLiquidity", [
5853
- {
5854
- tokenId,
5855
- liquidity: toHex(partialPosition.liquidity),
5856
- amount0Min: toHex(amount0Min),
5857
- amount1Min: toHex(amount1Min),
5858
- deadline
5859
- }
5860
- ])
5983
+ viem.encodeFunctionData({
5984
+ abi: _MasterChefV3.ABI,
5985
+ functionName: "decreaseLiquidity",
5986
+ args: [
5987
+ {
5988
+ tokenId,
5989
+ liquidity: partialPosition.liquidity,
5990
+ amount0Min,
5991
+ amount1Min,
5992
+ deadline
5993
+ }
5994
+ ]
5995
+ })
5861
5996
  );
5862
5997
  const { expectedCurrencyOwed0, expectedCurrencyOwed1, ...rest } = options.collectOptions;
5863
5998
  calldatas.push(
@@ -5876,26 +6011,28 @@ var _MasterChefV3 = class {
5876
6011
  if (rest?.recipient) {
5877
6012
  if (options.liquidityPercentage.equalTo(sdk.ONE)) {
5878
6013
  calldatas.push(
5879
- _MasterChefV3.INTERFACE.encodeFunctionData("withdraw", [
5880
- tokenId.toString(),
5881
- sdk.validateAndParseAddress(rest?.recipient)
5882
- ])
6014
+ viem.encodeFunctionData({
6015
+ abi: _MasterChefV3.ABI,
6016
+ functionName: "withdraw",
6017
+ args: [tokenId, sdk.validateAndParseAddress(rest?.recipient)]
6018
+ })
5883
6019
  );
5884
6020
  } else {
5885
6021
  calldatas.push(
5886
- _MasterChefV3.INTERFACE.encodeFunctionData("harvest", [
5887
- tokenId.toString(),
5888
- sdk.validateAndParseAddress(rest?.recipient)
5889
- ])
6022
+ viem.encodeFunctionData({
6023
+ abi: _MasterChefV3.ABI,
6024
+ functionName: "harvest",
6025
+ args: [tokenId, sdk.validateAndParseAddress(rest?.recipient)]
6026
+ })
5890
6027
  );
5891
6028
  }
5892
6029
  }
5893
6030
  if (options.liquidityPercentage.equalTo(sdk.ONE)) {
5894
6031
  if (options.burnToken) {
5895
- calldatas.push(_MasterChefV3.INTERFACE.encodeFunctionData("burn", [tokenId]));
6032
+ calldatas.push(viem.encodeFunctionData({ abi: _MasterChefV3.ABI, functionName: "burn", args: [tokenId] }));
5896
6033
  }
5897
6034
  } else {
5898
- invariant11__default.default(options.burnToken !== true, "CANNOT_BURN");
6035
+ invariant9__default.default(options.burnToken !== true, "CANNOT_BURN");
5899
6036
  }
5900
6037
  return {
5901
6038
  calldata: Multicall.encodeMulticall(calldatas),
@@ -5921,7 +6058,11 @@ var _MasterChefV3 = class {
5921
6058
  const { tokenId, to } = options;
5922
6059
  const calldatas = [];
5923
6060
  calldatas.push(
5924
- _MasterChefV3.INTERFACE.encodeFunctionData("harvest", [tokenId.toString(), sdk.validateAndParseAddress(to)])
6061
+ viem.encodeFunctionData({
6062
+ abi: _MasterChefV3.ABI,
6063
+ functionName: "harvest",
6064
+ args: [BigInt(tokenId), sdk.validateAndParseAddress(to)]
6065
+ })
5925
6066
  );
5926
6067
  return calldatas;
5927
6068
  }
@@ -5929,7 +6070,11 @@ var _MasterChefV3 = class {
5929
6070
  const { tokenId, to } = options;
5930
6071
  const calldatas = [];
5931
6072
  calldatas.push(
5932
- _MasterChefV3.INTERFACE.encodeFunctionData("withdraw", [tokenId.toString(), sdk.validateAndParseAddress(to)])
6073
+ viem.encodeFunctionData({
6074
+ abi: _MasterChefV3.ABI,
6075
+ functionName: "withdraw",
6076
+ args: [BigInt(tokenId), sdk.validateAndParseAddress(to)]
6077
+ })
5933
6078
  );
5934
6079
  return {
5935
6080
  calldata: Multicall.encodeMulticall(calldatas),
@@ -5938,12 +6083,11 @@ var _MasterChefV3 = class {
5938
6083
  }
5939
6084
  };
5940
6085
  var MasterChefV3 = _MasterChefV3;
5941
- MasterChefV3.INTERFACE = new abi.Interface(MasterChefV3_default);
6086
+ MasterChefV3.ABI = masterChefV3ABI;
5942
6087
 
5943
6088
  exports.ADDRESS_ZERO = ADDRESS_ZERO;
5944
- exports.DEPLOYER_ADDRESS = DEPLOYER_ADDRESS;
5945
6089
  exports.DEPLOYER_ADDRESSES = DEPLOYER_ADDRESSES;
5946
- exports.FACTORY_ADDRESS = FACTORY_ADDRESS;
6090
+ exports.FACTORY_ADDRESSES = FACTORY_ADDRESSES;
5947
6091
  exports.FeeAmount = FeeAmount;
5948
6092
  exports.FeeCalculator = FeeCalculator;
5949
6093
  exports.FullMath = FullMath;
@@ -5953,7 +6097,7 @@ exports.MaxUint128 = MaxUint128;
5953
6097
  exports.Multicall = Multicall;
5954
6098
  exports.NoTickDataProvider = NoTickDataProvider;
5955
6099
  exports.NonfungiblePositionManager = NonfungiblePositionManager;
5956
- exports.POOL_INIT_CODE_HASH = POOL_INIT_CODE_HASH;
6100
+ exports.POOL_INIT_CODE_HASHES = POOL_INIT_CODE_HASHES;
5957
6101
  exports.Payments = Payments;
5958
6102
  exports.Pool = Pool;
5959
6103
  exports.Position = Position;
@@ -5990,13 +6134,21 @@ exports.getLiquidityFromSqrtRatioX96 = getLiquidityFromSqrtRatioX96;
5990
6134
  exports.getLiquidityFromTick = getLiquidityFromTick;
5991
6135
  exports.isMint = isMint;
5992
6136
  exports.isSorted = isSorted;
6137
+ exports.masterChefV3ABI = masterChefV3ABI;
5993
6138
  exports.maxLiquidityForAmounts = maxLiquidityForAmounts;
5994
6139
  exports.mostSignificantBit = mostSignificantBit;
5995
6140
  exports.nearestUsableTick = nearestUsableTick;
6141
+ exports.nonfungiblePositionManagerABI = nonfungiblePositionManagerABI;
5996
6142
  exports.parseProtocolFees = parseProtocolFees;
6143
+ exports.peripheryPaymentsWithFeeABI = peripheryPaymentsWithFeeABI;
5997
6144
  exports.priceToClosestTick = priceToClosestTick;
6145
+ exports.quoterABI = quoterABI;
6146
+ exports.quoterV2ABI = quoterV2ABI;
6147
+ exports.selfPermitABI = selfPermitABI;
5998
6148
  exports.sqrtRatioX96ToPrice = sqrtRatioX96ToPrice;
5999
6149
  exports.subIn256 = subIn256;
6150
+ exports.swapRouterABI = swapRouterABI;
6000
6151
  exports.tickToPrice = tickToPrice;
6001
6152
  exports.toHex = toHex;
6002
6153
  exports.tradeComparator = tradeComparator;
6154
+ exports.v3StakerABI = v3StakerABI;