@pancakeswap/v3-sdk 1.0.0 → 3.0.0

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 (102) hide show
  1. package/LICENSE +674 -0
  2. package/dist/abi/MasterChefV3.d.ts +1222 -0
  3. package/dist/abi/MasterChefV3.d.ts.map +1 -0
  4. package/dist/abi/NonfungiblePositionManager.d.ts +962 -0
  5. package/dist/abi/NonfungiblePositionManager.d.ts.map +1 -0
  6. package/dist/abi/PeripheryPaymentsWithFee.d.ts +88 -0
  7. package/dist/abi/PeripheryPaymentsWithFee.d.ts.map +1 -0
  8. package/dist/abi/Quoter.d.ts +162 -0
  9. package/dist/abi/Quoter.d.ts.map +1 -0
  10. package/dist/abi/QuoterV2.d.ts +220 -0
  11. package/dist/abi/QuoterV2.d.ts.map +1 -0
  12. package/dist/abi/SelfPermit.d.ts +122 -0
  13. package/dist/abi/SelfPermit.d.ts.map +1 -0
  14. package/dist/abi/SwapRouter.d.ts +453 -0
  15. package/dist/abi/SwapRouter.d.ts.map +1 -0
  16. package/dist/abi/V3Staker.d.ts +547 -0
  17. package/dist/abi/V3Staker.d.ts.map +1 -0
  18. package/dist/constants.d.ts +26 -0
  19. package/dist/constants.d.ts.map +1 -0
  20. package/dist/entities/index.d.ts +8 -0
  21. package/dist/entities/index.d.ts.map +1 -0
  22. package/dist/entities/pool.d.ts +83 -0
  23. package/dist/entities/pool.d.ts.map +1 -0
  24. package/dist/entities/position.d.ts +131 -0
  25. package/dist/entities/position.d.ts.map +1 -0
  26. package/dist/entities/route.d.ts +27 -0
  27. package/dist/entities/route.d.ts.map +1 -0
  28. package/dist/entities/tick.d.ts +13 -0
  29. package/dist/entities/tick.d.ts.map +1 -0
  30. package/dist/entities/tickDataProvider.d.ts +32 -0
  31. package/dist/entities/tickDataProvider.d.ts.map +1 -0
  32. package/dist/entities/tickListDataProvider.d.ts +16 -0
  33. package/dist/entities/tickListDataProvider.d.ts.map +1 -0
  34. package/dist/entities/trade.d.ts +221 -0
  35. package/dist/entities/trade.d.ts.map +1 -0
  36. package/dist/index.d.ts +20 -1223
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +1167 -1092
  39. package/dist/index.mjs +1158 -1093
  40. package/dist/internalConstants.d.ts +11 -0
  41. package/dist/internalConstants.d.ts.map +1 -0
  42. package/dist/masterchefV3.d.ts +1258 -0
  43. package/dist/masterchefV3.d.ts.map +1 -0
  44. package/dist/multicall.d.ts +23 -0
  45. package/dist/multicall.d.ts.map +1 -0
  46. package/dist/nonfungiblePositionManager.d.ts +1115 -0
  47. package/dist/nonfungiblePositionManager.d.ts.map +1 -0
  48. package/dist/payments.d.ts +113 -0
  49. package/dist/payments.d.ts.map +1 -0
  50. package/dist/quoter.d.ts +419 -0
  51. package/dist/quoter.d.ts.map +1 -0
  52. package/dist/selfPermit.d.ts +146 -0
  53. package/dist/selfPermit.d.ts.map +1 -0
  54. package/dist/staker.d.ts +648 -0
  55. package/dist/staker.d.ts.map +1 -0
  56. package/dist/swapRouter.d.ts +502 -0
  57. package/dist/swapRouter.d.ts.map +1 -0
  58. package/dist/utils/calldata.d.ts +22 -0
  59. package/dist/utils/calldata.d.ts.map +1 -0
  60. package/dist/utils/computePoolAddress.d.ts +20 -0
  61. package/dist/utils/computePoolAddress.d.ts.map +1 -0
  62. package/dist/utils/encodeRouteToPath.d.ts +10 -0
  63. package/dist/utils/encodeRouteToPath.d.ts.map +1 -0
  64. package/dist/utils/encodeSqrtRatioX96.d.ts +9 -0
  65. package/dist/utils/encodeSqrtRatioX96.d.ts.map +1 -0
  66. package/dist/utils/feeCalculator.d.ts +65 -0
  67. package/dist/utils/feeCalculator.d.ts.map +1 -0
  68. package/dist/utils/fullMath.d.ts +8 -0
  69. package/dist/utils/fullMath.d.ts.map +1 -0
  70. package/dist/utils/index.d.ts +22 -0
  71. package/dist/utils/index.d.ts.map +1 -0
  72. package/dist/utils/isSorted.d.ts +8 -0
  73. package/dist/utils/isSorted.d.ts.map +1 -0
  74. package/dist/utils/liquidityMath.d.ts +8 -0
  75. package/dist/utils/liquidityMath.d.ts.map +1 -0
  76. package/dist/utils/maxLiquidityForAmounts.d.ts +14 -0
  77. package/dist/utils/maxLiquidityForAmounts.d.ts.map +1 -0
  78. package/dist/utils/mostSignificantBit.d.ts +2 -0
  79. package/dist/utils/mostSignificantBit.d.ts.map +1 -0
  80. package/dist/utils/nearestUsableTick.d.ts +7 -0
  81. package/dist/utils/nearestUsableTick.d.ts.map +1 -0
  82. package/dist/utils/parseProtocolFees.d.ts +3 -0
  83. package/dist/utils/parseProtocolFees.d.ts.map +1 -0
  84. package/dist/utils/position.d.ts +8 -0
  85. package/dist/utils/position.d.ts.map +1 -0
  86. package/dist/utils/positionMath.d.ts +8 -0
  87. package/dist/utils/positionMath.d.ts.map +1 -0
  88. package/dist/utils/priceTickConversions.d.ts +16 -0
  89. package/dist/utils/priceTickConversions.d.ts.map +1 -0
  90. package/dist/utils/sqrtPriceMath.d.ts +13 -0
  91. package/dist/utils/sqrtPriceMath.d.ts.map +1 -0
  92. package/dist/utils/sqrtRatioX96ToPrice.d.ts +3 -0
  93. package/dist/utils/sqrtRatioX96ToPrice.d.ts.map +1 -0
  94. package/dist/utils/swapMath.d.ts +9 -0
  95. package/dist/utils/swapMath.d.ts.map +1 -0
  96. package/dist/utils/tickLibrary.d.ts +14 -0
  97. package/dist/utils/tickLibrary.d.ts.map +1 -0
  98. package/dist/utils/tickList.d.ts +25 -0
  99. package/dist/utils/tickList.d.ts.map +1 -0
  100. package/dist/utils/tickMath.d.ts +34 -0
  101. package/dist/utils/tickMath.d.ts.map +1 -0
  102. package/package.json +17 -23
package/dist/index.mjs CHANGED
@@ -1,10 +1,7 @@
1
- import { ChainId, JSBI as JSBI$1, MaxUint256, sqrt, Price, Fraction, ZERO as ZERO$1, CurrencyAmount, Percent as Percent$1, TradeType, sortedInsert, validateAndParseAddress, ONE as ONE$1 } from '@pancakeswap/sdk';
2
- import JSBI4 from 'jsbi';
3
- import invariant11 from 'tiny-invariant';
4
- import { JSBI, Percent, Price as Price$1, Fraction as Fraction$1 } from '@pancakeswap/swap-sdk-core';
5
- import { Interface, defaultAbiCoder } from '@ethersproject/abi';
6
- import { getCreate2Address } from '@ethersproject/address';
7
- import { keccak256, pack } from '@ethersproject/solidity';
1
+ import { ChainId, Price, CurrencyAmount, Percent as Percent$1, MaxUint256 as MaxUint256$1, TradeType, Fraction, sortedInsert, validateAndParseAddress, ZERO as ZERO$2, ONE as ONE$1 } from '@pancakeswap/sdk';
2
+ import invariant9 from 'tiny-invariant';
3
+ import { Percent, MaxUint256, sqrt, Price as Price$1, CurrencyAmount as CurrencyAmount$1, Fraction as Fraction$1, ZERO as ZERO$1, TradeType as TradeType$1 } from '@pancakeswap/swap-sdk-core';
4
+ import { keccak256, encodeAbiParameters, parseAbiParameters, encodePacked, encodeFunctionData, toBytes, getAddress, pad, isBytes, slice, concat } from 'viem';
8
5
 
9
6
  // src/entities/pool.ts
10
7
  var FACTORY_ADDRESS = "0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865";
@@ -30,15 +27,22 @@ var TICK_SPACINGS = {
30
27
  [2500 /* MEDIUM */]: 50,
31
28
  [1e4 /* HIGH */]: 200
32
29
  };
33
- var NEGATIVE_ONE = JSBI.BigInt(-1);
34
- var ZERO = JSBI.BigInt(0);
35
- var ONE = JSBI.BigInt(1);
36
- var Q96 = JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(96));
37
- var Q192 = JSBI.exponentiate(Q96, JSBI.BigInt(2));
38
- var MAX_FEE = JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(6));
30
+ var NEGATIVE_ONE = BigInt(-1);
31
+ var ZERO = 0n;
32
+ var ONE = 1n;
33
+ var Q96 = 2n ** 96n;
34
+ var Q192 = Q96 ** 2n;
35
+ var MAX_FEE = 10n ** 6n;
39
36
  var ONE_HUNDRED_PERCENT = new Percent("1");
40
37
  var ZERO_PERCENT = new Percent("0");
41
- var Q128 = JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(128));
38
+ var Q128 = 2n ** 128n;
39
+ function getCreate2Address(from_, salt_, initCodeHash) {
40
+ const from = toBytes(getAddress(from_));
41
+ const salt = pad(isBytes(salt_) ? salt_ : toBytes(salt_), {
42
+ size: 32
43
+ });
44
+ return getAddress(slice(keccak256(concat([toBytes("0xff"), from, salt, toBytes(initCodeHash)])), 12));
45
+ }
42
46
  function computePoolAddress({
43
47
  deployerAddress,
44
48
  tokenA,
@@ -50,12 +54,13 @@ function computePoolAddress({
50
54
  return getCreate2Address(
51
55
  deployerAddress,
52
56
  keccak256(
53
- ["bytes"],
54
- [defaultAbiCoder.encode(["address", "address", "uint24"], [token0.address, token1.address, fee])]
57
+ encodeAbiParameters(parseAbiParameters(["address, address, uint24"]), [token0.address, token1.address, fee])
55
58
  ),
56
- initCodeHashManualOverride != null ? initCodeHashManualOverride : POOL_INIT_CODE_HASH
59
+ initCodeHashManualOverride ?? POOL_INIT_CODE_HASH
57
60
  );
58
61
  }
62
+
63
+ // src/utils/liquidityMath.ts
59
64
  var LiquidityMath = class {
60
65
  /**
61
66
  * Cannot be constructed.
@@ -63,12 +68,14 @@ var LiquidityMath = class {
63
68
  constructor() {
64
69
  }
65
70
  static addDelta(x, y) {
66
- if (JSBI4.lessThan(y, ZERO)) {
67
- return JSBI4.subtract(x, JSBI4.multiply(y, NEGATIVE_ONE));
71
+ if (y < ZERO) {
72
+ return x - y * NEGATIVE_ONE;
68
73
  }
69
- return JSBI4.add(x, y);
74
+ return x + y;
70
75
  }
71
76
  };
77
+
78
+ // src/utils/fullMath.ts
72
79
  var FullMath = class {
73
80
  /**
74
81
  * Cannot be constructed.
@@ -76,21 +83,21 @@ var FullMath = class {
76
83
  constructor() {
77
84
  }
78
85
  static mulDivRoundingUp(a, b, denominator) {
79
- const product = JSBI4.multiply(a, b);
80
- let result = JSBI4.divide(product, denominator);
81
- if (JSBI4.notEqual(JSBI4.remainder(product, denominator), ZERO))
82
- result = JSBI4.add(result, ONE);
86
+ const product = a * b;
87
+ let result = product / denominator;
88
+ if (product % denominator !== ZERO)
89
+ result = result + ONE;
83
90
  return result;
84
91
  }
85
92
  };
86
- var MaxUint160 = JSBI4.subtract(JSBI4.exponentiate(JSBI4.BigInt(2), JSBI4.BigInt(160)), ONE);
93
+ var MaxUint160 = 2n ** 160n - ONE;
87
94
  function multiplyIn256(x, y) {
88
- const product = JSBI4.multiply(x, y);
89
- return JSBI4.bitwiseAnd(product, MaxUint256);
95
+ const product = x * y;
96
+ return product & MaxUint256;
90
97
  }
91
98
  function addIn256(x, y) {
92
- const sum = JSBI4.add(x, y);
93
- return JSBI4.bitwiseAnd(sum, MaxUint256);
99
+ const sum = x + y;
100
+ return sum & MaxUint256;
94
101
  }
95
102
  var SqrtPriceMath = class {
96
103
  /**
@@ -99,59 +106,59 @@ var SqrtPriceMath = class {
99
106
  constructor() {
100
107
  }
101
108
  static getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
102
- if (JSBI4.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
109
+ if (sqrtRatioAX96 > sqrtRatioBX96) {
103
110
  sqrtRatioAX96 = sqrtRatioBX96;
104
111
  sqrtRatioBX96 = sqrtRatioAX96;
105
112
  }
106
- const numerator1 = JSBI4.leftShift(liquidity, JSBI4.BigInt(96));
107
- const numerator2 = JSBI4.subtract(sqrtRatioBX96, sqrtRatioAX96);
108
- return roundUp ? FullMath.mulDivRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), ONE, sqrtRatioAX96) : JSBI4.divide(JSBI4.divide(JSBI4.multiply(numerator1, numerator2), sqrtRatioBX96), sqrtRatioAX96);
113
+ const numerator1 = liquidity << 96n;
114
+ const numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
115
+ return roundUp ? FullMath.mulDivRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), ONE, sqrtRatioAX96) : numerator1 * numerator2 / sqrtRatioBX96 / sqrtRatioAX96;
109
116
  }
110
117
  static getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
111
- if (JSBI4.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
118
+ if (sqrtRatioAX96 > sqrtRatioBX96) {
112
119
  sqrtRatioAX96 = sqrtRatioBX96;
113
120
  sqrtRatioBX96 = sqrtRatioAX96;
114
121
  }
115
- return roundUp ? FullMath.mulDivRoundingUp(liquidity, JSBI4.subtract(sqrtRatioBX96, sqrtRatioAX96), Q96) : JSBI4.divide(JSBI4.multiply(liquidity, JSBI4.subtract(sqrtRatioBX96, sqrtRatioAX96)), Q96);
122
+ return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, Q96) : liquidity * (sqrtRatioBX96 - sqrtRatioAX96) / Q96;
116
123
  }
117
124
  static getNextSqrtPriceFromInput(sqrtPX96, liquidity, amountIn, zeroForOne) {
118
- invariant11(JSBI4.greaterThan(sqrtPX96, ZERO));
119
- invariant11(JSBI4.greaterThan(liquidity, ZERO));
125
+ invariant9(sqrtPX96 > ZERO);
126
+ invariant9(liquidity > ZERO);
120
127
  return zeroForOne ? this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
121
128
  }
122
129
  static getNextSqrtPriceFromOutput(sqrtPX96, liquidity, amountOut, zeroForOne) {
123
- invariant11(JSBI4.greaterThan(sqrtPX96, ZERO));
124
- invariant11(JSBI4.greaterThan(liquidity, ZERO));
130
+ invariant9(sqrtPX96 > ZERO);
131
+ invariant9(liquidity > ZERO);
125
132
  return zeroForOne ? this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
126
133
  }
127
134
  static getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amount, add) {
128
- if (JSBI4.equal(amount, ZERO))
135
+ if (amount === ZERO)
129
136
  return sqrtPX96;
130
- const numerator1 = JSBI4.leftShift(liquidity, JSBI4.BigInt(96));
137
+ const numerator1 = liquidity << 96n;
131
138
  if (add) {
132
139
  const product2 = multiplyIn256(amount, sqrtPX96);
133
- if (JSBI4.equal(JSBI4.divide(product2, amount), sqrtPX96)) {
140
+ if (product2 / amount === sqrtPX96) {
134
141
  const denominator2 = addIn256(numerator1, product2);
135
- if (JSBI4.greaterThanOrEqual(denominator2, numerator1)) {
142
+ if (denominator2 >= numerator1) {
136
143
  return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator2);
137
144
  }
138
145
  }
139
- return FullMath.mulDivRoundingUp(numerator1, ONE, JSBI4.add(JSBI4.divide(numerator1, sqrtPX96), amount));
146
+ return FullMath.mulDivRoundingUp(numerator1, ONE, numerator1 / sqrtPX96 + amount);
140
147
  }
141
148
  const product = multiplyIn256(amount, sqrtPX96);
142
- invariant11(JSBI4.equal(JSBI4.divide(product, amount), sqrtPX96));
143
- invariant11(JSBI4.greaterThan(numerator1, product));
144
- const denominator = JSBI4.subtract(numerator1, product);
149
+ invariant9(product / amount === sqrtPX96);
150
+ invariant9(numerator1 > product);
151
+ const denominator = numerator1 - product;
145
152
  return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator);
146
153
  }
147
154
  static getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amount, add) {
148
155
  if (add) {
149
- const quotient2 = JSBI4.lessThanOrEqual(amount, MaxUint160) ? JSBI4.divide(JSBI4.leftShift(amount, JSBI4.BigInt(96)), liquidity) : JSBI4.divide(JSBI4.multiply(amount, Q96), liquidity);
150
- return JSBI4.add(sqrtPX96, quotient2);
156
+ const quotient2 = amount <= MaxUint160 ? (amount << 96n) / liquidity : amount * Q96 / liquidity;
157
+ return sqrtPX96 + quotient2;
151
158
  }
152
159
  const quotient = FullMath.mulDivRoundingUp(amount, Q96, liquidity);
153
- invariant11(JSBI4.greaterThan(sqrtPX96, quotient));
154
- return JSBI4.subtract(sqrtPX96, quotient);
160
+ invariant9(sqrtPX96 > quotient);
161
+ return sqrtPX96 - quotient;
155
162
  }
156
163
  };
157
164
 
@@ -164,15 +171,12 @@ var SwapMath = class {
164
171
  }
165
172
  static computeSwapStep(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, amountRemaining, feePips) {
166
173
  const returnValues = {};
167
- const zeroForOne = JSBI4.greaterThanOrEqual(sqrtRatioCurrentX96, sqrtRatioTargetX96);
168
- const exactIn = JSBI4.greaterThanOrEqual(amountRemaining, ZERO);
174
+ const zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
175
+ const exactIn = amountRemaining >= ZERO;
169
176
  if (exactIn) {
170
- const amountRemainingLessFee = JSBI4.divide(
171
- JSBI4.multiply(amountRemaining, JSBI4.subtract(MAX_FEE, JSBI4.BigInt(feePips))),
172
- MAX_FEE
173
- );
177
+ const amountRemainingLessFee = amountRemaining * (MAX_FEE - BigInt(feePips)) / MAX_FEE;
174
178
  returnValues.amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
175
- if (JSBI4.greaterThanOrEqual(amountRemainingLessFee, returnValues.amountIn)) {
179
+ if (amountRemainingLessFee >= returnValues.amountIn) {
176
180
  returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
177
181
  } else {
178
182
  returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
@@ -184,18 +188,18 @@ var SwapMath = class {
184
188
  }
185
189
  } else {
186
190
  returnValues.amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
187
- if (JSBI4.greaterThanOrEqual(JSBI4.multiply(amountRemaining, NEGATIVE_ONE), returnValues.amountOut)) {
191
+ if (amountRemaining * NEGATIVE_ONE >= returnValues.amountOut) {
188
192
  returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
189
193
  } else {
190
194
  returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
191
195
  sqrtRatioCurrentX96,
192
196
  liquidity,
193
- JSBI4.multiply(amountRemaining, NEGATIVE_ONE),
197
+ amountRemaining * NEGATIVE_ONE,
194
198
  zeroForOne
195
199
  );
196
200
  }
197
201
  }
198
- const max = JSBI4.equal(sqrtRatioTargetX96, returnValues.sqrtRatioNextX96);
202
+ const max = sqrtRatioTargetX96 === returnValues.sqrtRatioNextX96;
199
203
  if (zeroForOne) {
200
204
  returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount0Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
201
205
  returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount1Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
@@ -203,33 +207,30 @@ var SwapMath = class {
203
207
  returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, true);
204
208
  returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, false);
205
209
  }
206
- if (!exactIn && JSBI4.greaterThan(returnValues.amountOut, JSBI4.multiply(amountRemaining, NEGATIVE_ONE))) {
207
- returnValues.amountOut = JSBI4.multiply(amountRemaining, NEGATIVE_ONE);
210
+ if (!exactIn && returnValues.amountOut > amountRemaining * NEGATIVE_ONE) {
211
+ returnValues.amountOut = amountRemaining * NEGATIVE_ONE;
208
212
  }
209
- if (exactIn && JSBI4.notEqual(returnValues.sqrtRatioNextX96, sqrtRatioTargetX96)) {
210
- returnValues.feeAmount = JSBI4.subtract(amountRemaining, returnValues.amountIn);
213
+ if (exactIn && returnValues.sqrtRatioNextX96 !== sqrtRatioTargetX96) {
214
+ returnValues.feeAmount = amountRemaining - returnValues.amountIn;
211
215
  } else {
212
216
  returnValues.feeAmount = FullMath.mulDivRoundingUp(
213
217
  returnValues.amountIn,
214
- JSBI4.BigInt(feePips),
215
- JSBI4.subtract(MAX_FEE, JSBI4.BigInt(feePips))
218
+ BigInt(feePips),
219
+ MAX_FEE - BigInt(feePips)
216
220
  );
217
221
  }
218
222
  return [returnValues.sqrtRatioNextX96, returnValues.amountIn, returnValues.amountOut, returnValues.feeAmount];
219
223
  }
220
224
  };
221
- var TWO = JSBI4.BigInt(2);
222
- var POWERS_OF_2 = [128, 64, 32, 16, 8, 4, 2, 1].map((pow) => [
223
- pow,
224
- JSBI4.exponentiate(TWO, JSBI4.BigInt(pow))
225
- ]);
225
+ var TWO = 2n;
226
+ var POWERS_OF_2 = [128, 64, 32, 16, 8, 4, 2, 1].map((pow) => [pow, TWO ** BigInt(pow)]);
226
227
  function mostSignificantBit(x) {
227
- invariant11(JSBI4.greaterThan(x, ZERO), "ZERO");
228
- invariant11(JSBI4.lessThanOrEqual(x, MaxUint256), "MAX");
228
+ invariant9(x > ZERO, "ZERO");
229
+ invariant9(x <= MaxUint256, "MAX");
229
230
  let msb = 0;
230
231
  for (const [power, min] of POWERS_OF_2) {
231
- if (JSBI4.greaterThanOrEqual(x, min)) {
232
- x = JSBI4.signedRightShift(x, JSBI4.BigInt(power));
232
+ if (x >= min) {
233
+ x = x >> BigInt(power);
233
234
  msb += power;
234
235
  }
235
236
  }
@@ -238,9 +239,9 @@ function mostSignificantBit(x) {
238
239
 
239
240
  // src/utils/tickMath.ts
240
241
  function mulShift(val, mulBy) {
241
- return JSBI$1.signedRightShift(JSBI$1.multiply(val, JSBI$1.BigInt(mulBy)), JSBI$1.BigInt(128));
242
+ return val * BigInt(mulBy) >> 128n;
242
243
  }
243
- var Q32 = JSBI$1.exponentiate(JSBI$1.BigInt(2), JSBI$1.BigInt(32));
244
+ var Q32 = 2n ** 32n;
244
245
  var _TickMath = class {
245
246
  /**
246
247
  * Cannot be constructed.
@@ -252,9 +253,9 @@ var _TickMath = class {
252
253
  * @param tick the tick for which to compute the sqrt ratio
253
254
  */
254
255
  static getSqrtRatioAtTick(tick) {
255
- invariant11(tick >= _TickMath.MIN_TICK && tick <= _TickMath.MAX_TICK && Number.isInteger(tick), "TICK");
256
+ invariant9(tick >= _TickMath.MIN_TICK && tick <= _TickMath.MAX_TICK && Number.isInteger(tick), "TICK");
256
257
  const absTick = tick < 0 ? tick * -1 : tick;
257
- let ratio = (absTick & 1) != 0 ? JSBI$1.BigInt("0xfffcb933bd6fad37aa2d162d1a594001") : JSBI$1.BigInt("0x100000000000000000000000000000000");
258
+ let ratio = (absTick & 1) != 0 ? BigInt("0xfffcb933bd6fad37aa2d162d1a594001") : BigInt("0x100000000000000000000000000000000");
258
259
  if ((absTick & 2) != 0)
259
260
  ratio = mulShift(ratio, "0xfff97272373d413259a46990580e213a");
260
261
  if ((absTick & 4) != 0)
@@ -294,8 +295,8 @@ var _TickMath = class {
294
295
  if ((absTick & 524288) != 0)
295
296
  ratio = mulShift(ratio, "0x48a170391f7dc42444e8fa2");
296
297
  if (tick > 0)
297
- ratio = JSBI$1.divide(MaxUint256, ratio);
298
- return JSBI$1.greaterThan(JSBI$1.remainder(ratio, Q32), ZERO) ? JSBI$1.add(JSBI$1.divide(ratio, Q32), ONE) : JSBI$1.divide(ratio, Q32);
298
+ ratio = MaxUint256 / ratio;
299
+ return ratio % Q32 > ZERO ? ratio / Q32 + ONE : ratio / Q32;
299
300
  }
300
301
  /**
301
302
  * Returns the tick corresponding to a given sqrt ratio, s.t. #getSqrtRatioAtTick(tick) <= sqrtRatioX96
@@ -303,39 +304,26 @@ var _TickMath = class {
303
304
  * @param sqrtRatioX96 the sqrt ratio as a Q64.96 for which to compute the tick
304
305
  */
305
306
  static getTickAtSqrtRatio(sqrtRatioX96) {
306
- invariant11(
307
- JSBI$1.greaterThanOrEqual(sqrtRatioX96, _TickMath.MIN_SQRT_RATIO) && JSBI$1.lessThan(sqrtRatioX96, _TickMath.MAX_SQRT_RATIO),
308
- "SQRT_RATIO"
309
- );
310
- const sqrtRatioX128 = JSBI$1.leftShift(sqrtRatioX96, JSBI$1.BigInt(32));
307
+ invariant9(sqrtRatioX96 >= _TickMath.MIN_SQRT_RATIO && sqrtRatioX96 < _TickMath.MAX_SQRT_RATIO, "SQRT_RATIO");
308
+ const sqrtRatioX128 = sqrtRatioX96 << 32n;
311
309
  const msb = mostSignificantBit(sqrtRatioX128);
312
310
  let r;
313
- if (JSBI$1.greaterThanOrEqual(JSBI$1.BigInt(msb), JSBI$1.BigInt(128))) {
314
- r = JSBI$1.signedRightShift(sqrtRatioX128, JSBI$1.BigInt(msb - 127));
311
+ if (BigInt(msb) >= 128n) {
312
+ r = sqrtRatioX128 >> BigInt(msb - 127);
315
313
  } else {
316
- r = JSBI$1.leftShift(sqrtRatioX128, JSBI$1.BigInt(127 - msb));
314
+ r = sqrtRatioX128 << BigInt(127 - msb);
317
315
  }
318
- let log_2 = JSBI$1.leftShift(JSBI$1.subtract(JSBI$1.BigInt(msb), JSBI$1.BigInt(128)), JSBI$1.BigInt(64));
316
+ let log_2 = BigInt(msb) - 128n << 64n;
319
317
  for (let i = 0; i < 14; i++) {
320
- r = JSBI$1.signedRightShift(JSBI$1.multiply(r, r), JSBI$1.BigInt(127));
321
- const f = JSBI$1.signedRightShift(r, JSBI$1.BigInt(128));
322
- log_2 = JSBI$1.bitwiseOr(log_2, JSBI$1.leftShift(f, JSBI$1.BigInt(63 - i)));
323
- r = JSBI$1.signedRightShift(r, f);
318
+ r = r * r >> 127n;
319
+ const f = r >> 128n;
320
+ log_2 = log_2 | f << BigInt(63 - i);
321
+ r = r >> f;
324
322
  }
325
- const log_sqrt10001 = JSBI$1.multiply(log_2, JSBI$1.BigInt("255738958999603826347141"));
326
- const tickLow = JSBI$1.toNumber(
327
- JSBI$1.signedRightShift(
328
- JSBI$1.subtract(log_sqrt10001, JSBI$1.BigInt("3402992956809132418596140100660247210")),
329
- JSBI$1.BigInt(128)
330
- )
331
- );
332
- const tickHigh = JSBI$1.toNumber(
333
- JSBI$1.signedRightShift(
334
- JSBI$1.add(log_sqrt10001, JSBI$1.BigInt("291339464771989622907027621153398088495")),
335
- JSBI$1.BigInt(128)
336
- )
337
- );
338
- return tickLow === tickHigh ? tickLow : JSBI$1.lessThanOrEqual(_TickMath.getSqrtRatioAtTick(tickHigh), sqrtRatioX96) ? tickHigh : tickLow;
323
+ const log_sqrt10001 = log_2 * 255738958999603826347141n;
324
+ const tickLow = Number(log_sqrt10001 - 3402992956809132418596140100660247210n >> 128n);
325
+ const tickHigh = Number(log_sqrt10001 + 291339464771989622907027621153398088495n >> 128n);
326
+ return tickLow === tickHigh ? tickLow : _TickMath.getSqrtRatioAtTick(tickHigh) <= sqrtRatioX96 ? tickHigh : tickLow;
339
327
  }
340
328
  };
341
329
  var TickMath = _TickMath;
@@ -351,11 +339,11 @@ TickMath.MAX_TICK = -_TickMath.MIN_TICK;
351
339
  /**
352
340
  * The sqrt ratio corresponding to the minimum tick that could be used on any pool.
353
341
  */
354
- TickMath.MIN_SQRT_RATIO = JSBI$1.BigInt("4295128739");
342
+ TickMath.MIN_SQRT_RATIO = 4295128739n;
355
343
  /**
356
344
  * The sqrt ratio corresponding to the maximum tick that could be used on any pool.
357
345
  */
358
- TickMath.MAX_SQRT_RATIO = JSBI$1.BigInt("1461446703485210103287273052203988822378723970342");
346
+ TickMath.MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342n;
359
347
 
360
348
  // src/entities/tickDataProvider.ts
361
349
  var _NoTickDataProvider = class {
@@ -390,31 +378,25 @@ var TickList = class {
390
378
  constructor() {
391
379
  }
392
380
  static validateList(ticks, tickSpacing) {
393
- invariant11(tickSpacing > 0, "TICK_SPACING_NONZERO");
394
- invariant11(
381
+ invariant9(tickSpacing > 0, "TICK_SPACING_NONZERO");
382
+ invariant9(
395
383
  ticks.every(({ index }) => index % tickSpacing === 0),
396
384
  "TICK_SPACING"
397
385
  );
398
- invariant11(
399
- JSBI4.equal(
400
- ticks.reduce((accumulator, { liquidityNet }) => JSBI4.add(accumulator, liquidityNet), ZERO),
401
- ZERO
402
- ),
403
- "ZERO_NET"
404
- );
405
- invariant11(isSorted(ticks, tickComparator), "SORTED");
386
+ invariant9(ticks.reduce((accumulator, { liquidityNet }) => accumulator + liquidityNet, ZERO) === ZERO, "ZERO_NET");
387
+ invariant9(isSorted(ticks, tickComparator), "SORTED");
406
388
  }
407
389
  static isBelowSmallest(ticks, tick) {
408
- invariant11(ticks.length > 0, "LENGTH");
390
+ invariant9(ticks.length > 0, "LENGTH");
409
391
  return tick < ticks[0].index;
410
392
  }
411
393
  static isAtOrAboveLargest(ticks, tick) {
412
- invariant11(ticks.length > 0, "LENGTH");
394
+ invariant9(ticks.length > 0, "LENGTH");
413
395
  return tick >= ticks[ticks.length - 1].index;
414
396
  }
415
397
  static getTick(ticks, index) {
416
398
  const tick = ticks[this.binarySearch(ticks, index)];
417
- invariant11(tick.index === index, "NOT_CONTAINED");
399
+ invariant9(tick.index === index, "NOT_CONTAINED");
418
400
  return tick;
419
401
  }
420
402
  /**
@@ -424,7 +406,7 @@ var TickList = class {
424
406
  * @private
425
407
  */
426
408
  static binarySearch(ticks, tick) {
427
- invariant11(!this.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
409
+ invariant9(!this.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
428
410
  let l = 0;
429
411
  let r = ticks.length - 1;
430
412
  let i;
@@ -442,14 +424,14 @@ var TickList = class {
442
424
  }
443
425
  static nextInitializedTick(ticks, tick, lte) {
444
426
  if (lte) {
445
- invariant11(!TickList.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
427
+ invariant9(!TickList.isBelowSmallest(ticks, tick), "BELOW_SMALLEST");
446
428
  if (TickList.isAtOrAboveLargest(ticks, tick)) {
447
429
  return ticks[ticks.length - 1];
448
430
  }
449
431
  const index2 = this.binarySearch(ticks, tick);
450
432
  return ticks[index2];
451
433
  }
452
- invariant11(!this.isAtOrAboveLargest(ticks, tick), "AT_OR_ABOVE_LARGEST");
434
+ invariant9(!this.isAtOrAboveLargest(ticks, tick), "AT_OR_ABOVE_LARGEST");
453
435
  if (this.isBelowSmallest(ticks, tick)) {
454
436
  return ticks[0];
455
437
  }
@@ -486,116 +468,273 @@ var TickList = class {
486
468
  return Math.abs(beforeIndex - afterIndex);
487
469
  }
488
470
  };
489
- function toHex(bigintIsh) {
490
- const bigInt = JSBI4.BigInt(bigintIsh);
491
- let hex = bigInt.toString(16);
492
- if (hex.length % 2 !== 0) {
493
- hex = `0${hex}`;
471
+ var Tick = class {
472
+ constructor({ index, liquidityGross, liquidityNet }) {
473
+ invariant9(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK, "TICK");
474
+ this.index = index;
475
+ this.liquidityGross = BigInt(liquidityGross);
476
+ this.liquidityNet = BigInt(liquidityNet);
494
477
  }
495
- return `0x${hex}`;
496
- }
497
- function encodeRouteToPath(route, exactOutput) {
498
- const firstInputToken = route.input.wrapped;
499
- const { path, types } = route.pools.reduce(
500
- ({ inputToken, path: path2, types: types2 }, pool, index) => {
501
- const outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
502
- if (index === 0) {
503
- return {
504
- inputToken: outputToken,
505
- types: ["address", "uint24", "address"],
506
- path: [inputToken.address, pool.fee, outputToken.address]
507
- };
478
+ };
479
+
480
+ // src/entities/tickListDataProvider.ts
481
+ var TickListDataProvider = class {
482
+ constructor(ticks) {
483
+ const ticksMapped = ticks.map((t) => t instanceof Tick ? t : new Tick(t));
484
+ this.ticks = ticksMapped;
485
+ }
486
+ async getTick(tick) {
487
+ return TickList.getTick(this.ticks, tick);
488
+ }
489
+ async nextInitializedTickWithinOneWord(tick, lte, tickSpacing) {
490
+ return TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing);
491
+ }
492
+ };
493
+
494
+ // src/entities/pool.ts
495
+ var NO_TICK_DATA_PROVIDER_DEFAULT = new NoTickDataProvider();
496
+ var Pool = class {
497
+ static getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, deployerAddressOverride) {
498
+ return computePoolAddress({
499
+ deployerAddress: deployerAddressOverride ?? DEPLOYER_ADDRESSES[tokenA.chainId],
500
+ fee,
501
+ tokenA,
502
+ tokenB,
503
+ initCodeHashManualOverride
504
+ });
505
+ }
506
+ /**
507
+ * Construct a pool
508
+ * @param tokenA One of the tokens in the pool
509
+ * @param tokenB The other token in the pool
510
+ * @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
511
+ * @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0
512
+ * @param liquidity The current value of in range liquidity
513
+ * @param tickCurrent The current tick of the pool
514
+ * @param ticks The current state of the pool ticks or a data provider that can return tick data
515
+ */
516
+ constructor(tokenA, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks = NO_TICK_DATA_PROVIDER_DEFAULT) {
517
+ invariant9(Number.isInteger(fee) && fee < 1e6, "FEE");
518
+ [this.token0, this.token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
519
+ this.fee = fee;
520
+ this.sqrtRatioX96 = BigInt(sqrtRatioX96);
521
+ this.liquidity = BigInt(liquidity);
522
+ this.tickCurrent = tickCurrent;
523
+ this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks) : ticks;
524
+ }
525
+ /**
526
+ * Returns true if the token is either token0 or token1
527
+ * @param token The token to check
528
+ * @returns True if token is either token0 or token
529
+ */
530
+ involvesToken(token) {
531
+ return token.equals(this.token0) || token.equals(this.token1);
532
+ }
533
+ /**
534
+ * Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
535
+ */
536
+ get token0Price() {
537
+ return this._token0Price ?? (this._token0Price = new Price(this.token0, this.token1, Q192, this.sqrtRatioX96 * this.sqrtRatioX96));
538
+ }
539
+ /**
540
+ * Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
541
+ */
542
+ get token1Price() {
543
+ return this._token1Price ?? (this._token1Price = new Price(this.token1, this.token0, this.sqrtRatioX96 * this.sqrtRatioX96, Q192));
544
+ }
545
+ /**
546
+ * Return the price of the given token in terms of the other token in the pool.
547
+ * @param token The token to return price of
548
+ * @returns The price of the given token, in terms of the other.
549
+ */
550
+ priceOf(token) {
551
+ invariant9(this.involvesToken(token), "TOKEN");
552
+ return token.equals(this.token0) ? this.token0Price : this.token1Price;
553
+ }
554
+ /**
555
+ * Returns the chain ID of the tokens in the pool.
556
+ */
557
+ get chainId() {
558
+ return this.token0.chainId;
559
+ }
560
+ /**
561
+ * Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
562
+ * @param inputAmount The input amount for which to quote the output amount
563
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
564
+ * @returns The output amount and the pool with updated state
565
+ */
566
+ async getOutputAmount(inputAmount, sqrtPriceLimitX96) {
567
+ invariant9(this.involvesToken(inputAmount.currency), "TOKEN");
568
+ const zeroForOne = inputAmount.currency.equals(this.token0);
569
+ const {
570
+ amountCalculated: outputAmount,
571
+ sqrtRatioX96,
572
+ liquidity,
573
+ tickCurrent
574
+ } = await this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96);
575
+ const outputToken = zeroForOne ? this.token1 : this.token0;
576
+ return [
577
+ CurrencyAmount.fromRawAmount(outputToken, outputAmount * NEGATIVE_ONE),
578
+ new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)
579
+ ];
580
+ }
581
+ /**
582
+ * Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
583
+ * @param outputAmount the output amount for which to quote the input amount
584
+ * @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
585
+ * @returns The input amount and the pool with updated state
586
+ */
587
+ async getInputAmount(outputAmount, sqrtPriceLimitX96) {
588
+ invariant9(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency), "TOKEN");
589
+ const zeroForOne = outputAmount.currency.equals(this.token1);
590
+ const {
591
+ amountSpecifiedRemaining,
592
+ amountCalculated: inputAmount,
593
+ sqrtRatioX96,
594
+ liquidity,
595
+ tickCurrent
596
+ } = await this.swap(zeroForOne, outputAmount.quotient * NEGATIVE_ONE, sqrtPriceLimitX96);
597
+ invariant9(amountSpecifiedRemaining === ZERO, "INSUFICIENT_LIQUIDITY");
598
+ const inputToken = zeroForOne ? this.token0 : this.token1;
599
+ return [
600
+ CurrencyAmount.fromRawAmount(inputToken, inputAmount),
601
+ new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)
602
+ ];
603
+ }
604
+ /**
605
+ * Executes a swap
606
+ * @param zeroForOne Whether the amount in is token0 or token1
607
+ * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
608
+ * @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
609
+ * @returns amountCalculated
610
+ * @returns sqrtRatioX96
611
+ * @returns liquidity
612
+ * @returns tickCurrent
613
+ */
614
+ async swap(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
615
+ if (!sqrtPriceLimitX96)
616
+ sqrtPriceLimitX96 = zeroForOne ? TickMath.MIN_SQRT_RATIO + ONE : TickMath.MAX_SQRT_RATIO - ONE;
617
+ if (zeroForOne) {
618
+ invariant9(sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO, "RATIO_MIN");
619
+ invariant9(sqrtPriceLimitX96 < this.sqrtRatioX96, "RATIO_CURRENT");
620
+ } else {
621
+ invariant9(sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO, "RATIO_MAX");
622
+ invariant9(sqrtPriceLimitX96 > this.sqrtRatioX96, "RATIO_CURRENT");
623
+ }
624
+ const exactInput = amountSpecified >= ZERO;
625
+ const state = {
626
+ amountSpecifiedRemaining: amountSpecified,
627
+ amountCalculated: ZERO,
628
+ sqrtPriceX96: this.sqrtRatioX96,
629
+ tick: this.tickCurrent,
630
+ liquidity: this.liquidity
631
+ };
632
+ while (state.amountSpecifiedRemaining !== ZERO && state.sqrtPriceX96 != sqrtPriceLimitX96) {
633
+ const step = {};
634
+ step.sqrtPriceStartX96 = state.sqrtPriceX96;
635
+ [step.tickNext, step.initialized] = await this.tickDataProvider.nextInitializedTickWithinOneWord(
636
+ state.tick,
637
+ zeroForOne,
638
+ this.tickSpacing
639
+ );
640
+ if (step.tickNext < TickMath.MIN_TICK) {
641
+ step.tickNext = TickMath.MIN_TICK;
642
+ } else if (step.tickNext > TickMath.MAX_TICK) {
643
+ step.tickNext = TickMath.MAX_TICK;
508
644
  }
509
- return {
510
- inputToken: outputToken,
511
- types: [...types2, "uint24", "address"],
512
- path: [...path2, pool.fee, outputToken.address]
513
- };
514
- },
515
- { inputToken: firstInputToken, path: [], types: [] }
516
- );
517
- return exactOutput ? pack(types.reverse(), path.reverse()) : pack(types, path);
518
- }
519
- function encodeSqrtRatioX96(amount1, amount0) {
520
- const numerator = JSBI4.leftShift(JSBI4.BigInt(amount1), JSBI4.BigInt(192));
521
- const denominator = JSBI4.BigInt(amount0);
522
- const ratioX192 = JSBI4.divide(numerator, denominator);
523
- return sqrt(ratioX192);
524
- }
645
+ step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
646
+ [state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.computeSwapStep(
647
+ state.sqrtPriceX96,
648
+ (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96,
649
+ state.liquidity,
650
+ state.amountSpecifiedRemaining,
651
+ this.fee
652
+ );
653
+ if (exactInput) {
654
+ state.amountSpecifiedRemaining = state.amountSpecifiedRemaining - (step.amountIn + step.feeAmount);
655
+ state.amountCalculated = state.amountCalculated - step.amountOut;
656
+ } else {
657
+ state.amountSpecifiedRemaining = state.amountSpecifiedRemaining + step.amountOut;
658
+ state.amountCalculated = state.amountCalculated + (step.amountIn + step.feeAmount);
659
+ }
660
+ if (state.sqrtPriceX96 === step.sqrtPriceNextX96) {
661
+ if (step.initialized) {
662
+ let liquidityNet = BigInt((await this.tickDataProvider.getTick(step.tickNext)).liquidityNet);
663
+ if (zeroForOne)
664
+ liquidityNet = liquidityNet * NEGATIVE_ONE;
665
+ state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
666
+ }
667
+ state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
668
+ } else if (state.sqrtPriceX96 !== step.sqrtPriceStartX96) {
669
+ state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
670
+ }
671
+ }
672
+ return {
673
+ amountSpecifiedRemaining: state.amountSpecifiedRemaining,
674
+ amountCalculated: state.amountCalculated,
675
+ sqrtRatioX96: state.sqrtPriceX96,
676
+ liquidity: state.liquidity,
677
+ tickCurrent: state.tick
678
+ };
679
+ }
680
+ get tickSpacing() {
681
+ return TICK_SPACINGS[this.fee];
682
+ }
683
+ };
684
+
685
+ // src/utils/maxLiquidityForAmounts.ts
525
686
  function maxLiquidityForAmount0Imprecise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
526
- if (JSBI4.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
687
+ if (sqrtRatioAX96 > sqrtRatioBX96) {
527
688
  sqrtRatioAX96 = sqrtRatioBX96;
528
689
  sqrtRatioBX96 = sqrtRatioAX96;
529
690
  }
530
- const intermediate = JSBI4.divide(JSBI4.multiply(sqrtRatioAX96, sqrtRatioBX96), Q96);
531
- return JSBI4.divide(JSBI4.multiply(JSBI4.BigInt(amount0), intermediate), JSBI4.subtract(sqrtRatioBX96, sqrtRatioAX96));
691
+ const intermediate = sqrtRatioAX96 * sqrtRatioBX96 / Q96;
692
+ return BigInt(amount0) * intermediate / (sqrtRatioBX96 - sqrtRatioAX96);
532
693
  }
533
694
  function maxLiquidityForAmount0Precise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
534
- if (JSBI4.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
695
+ if (sqrtRatioAX96 > sqrtRatioBX96) {
535
696
  sqrtRatioAX96 = sqrtRatioBX96;
536
697
  sqrtRatioBX96 = sqrtRatioAX96;
537
698
  }
538
- const numerator = JSBI4.multiply(JSBI4.multiply(JSBI4.BigInt(amount0), sqrtRatioAX96), sqrtRatioBX96);
539
- const denominator = JSBI4.multiply(Q96, JSBI4.subtract(sqrtRatioBX96, sqrtRatioAX96));
540
- return JSBI4.divide(numerator, denominator);
699
+ const numerator = BigInt(amount0) * sqrtRatioAX96 * sqrtRatioBX96;
700
+ const denominator = Q96 * (sqrtRatioBX96 - sqrtRatioAX96);
701
+ return numerator / denominator;
541
702
  }
542
703
  function maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1) {
543
- if (JSBI4.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
704
+ if (sqrtRatioAX96 > sqrtRatioBX96) {
544
705
  sqrtRatioAX96 = sqrtRatioBX96;
545
706
  sqrtRatioBX96 = sqrtRatioAX96;
546
707
  }
547
- return JSBI4.divide(JSBI4.multiply(JSBI4.BigInt(amount1), Q96), JSBI4.subtract(sqrtRatioBX96, sqrtRatioAX96));
708
+ return BigInt(amount1) * Q96 / (sqrtRatioBX96 - sqrtRatioAX96);
548
709
  }
549
710
  function maxLiquidityForAmounts(sqrtRatioCurrentX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision) {
550
- if (JSBI4.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
711
+ if (sqrtRatioAX96 > sqrtRatioBX96) {
551
712
  sqrtRatioAX96 = sqrtRatioBX96;
552
713
  sqrtRatioBX96 = sqrtRatioAX96;
553
714
  }
554
715
  const maxLiquidityForAmount0 = useFullPrecision ? maxLiquidityForAmount0Precise : maxLiquidityForAmount0Imprecise;
555
- if (JSBI4.lessThanOrEqual(sqrtRatioCurrentX96, sqrtRatioAX96)) {
716
+ if (sqrtRatioCurrentX96 <= sqrtRatioAX96) {
556
717
  return maxLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
557
718
  }
558
- if (JSBI4.lessThan(sqrtRatioCurrentX96, sqrtRatioBX96)) {
719
+ if (sqrtRatioCurrentX96 < sqrtRatioBX96) {
559
720
  const liquidity0 = maxLiquidityForAmount0(sqrtRatioCurrentX96, sqrtRatioBX96, amount0);
560
721
  const liquidity1 = maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioCurrentX96, amount1);
561
- return JSBI4.lessThan(liquidity0, liquidity1) ? liquidity0 : liquidity1;
722
+ return liquidity0 < liquidity1 ? liquidity0 : liquidity1;
562
723
  }
563
724
  return maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
564
725
  }
565
- function nearestUsableTick(tick, tickSpacing) {
566
- invariant11(Number.isInteger(tick) && Number.isInteger(tickSpacing), "INTEGERS");
567
- invariant11(tickSpacing > 0, "TICK_SPACING");
568
- invariant11(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK, "TICK_BOUND");
569
- const rounded = Math.round(tick / tickSpacing) * tickSpacing;
570
- if (rounded < TickMath.MIN_TICK)
571
- return rounded + tickSpacing;
572
- if (rounded > TickMath.MAX_TICK)
573
- return rounded - tickSpacing;
574
- return rounded;
726
+ function encodeSqrtRatioX96(amount1, amount0) {
727
+ const numerator = BigInt(amount1) << 192n;
728
+ const denominator = BigInt(amount0);
729
+ const ratioX192 = numerator / denominator;
730
+ return sqrt(ratioX192);
575
731
  }
576
- var PositionLibrary = class {
577
- /**
578
- * Cannot be constructed.
579
- */
580
- constructor() {
581
- }
582
- // replicates the portions of Position#update required to compute unaccounted fees
583
- static getTokensOwed(feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, feeGrowthInside0X128, feeGrowthInside1X128) {
584
- const tokensOwed0 = JSBI$1.divide(
585
- JSBI$1.multiply(subIn256(feeGrowthInside0X128, feeGrowthInside0LastX128), liquidity),
586
- Q128
587
- );
588
- const tokensOwed1 = JSBI$1.divide(
589
- JSBI$1.multiply(subIn256(feeGrowthInside1X128, feeGrowthInside1LastX128), liquidity),
590
- Q128
591
- );
592
- return [tokensOwed0, tokensOwed1];
593
- }
594
- };
732
+
733
+ // src/utils/priceTickConversions.ts
595
734
  function tickToPrice(baseToken, quoteToken, tick) {
596
735
  const sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
597
- const ratioX192 = JSBI4.multiply(sqrtRatioX96, sqrtRatioX96);
598
- return baseToken.sortsBefore(quoteToken) ? new Price(baseToken, quoteToken, Q192, ratioX192) : new Price(baseToken, quoteToken, ratioX192, Q192);
736
+ const ratioX192 = sqrtRatioX96 * sqrtRatioX96;
737
+ return baseToken.sortsBefore(quoteToken) ? new Price$1(baseToken, quoteToken, Q192, ratioX192) : new Price$1(baseToken, quoteToken, ratioX192, Q192);
599
738
  }
600
739
  function priceToClosestTick(price) {
601
740
  const sorted = price.baseCurrency.sortsBefore(price.quoteCurrency);
@@ -611,55 +750,16 @@ function priceToClosestTick(price) {
611
750
  }
612
751
  return tick;
613
752
  }
614
- var Q256 = JSBI4.exponentiate(JSBI4.BigInt(2), JSBI4.BigInt(256));
615
- function subIn256(x, y) {
616
- const difference = JSBI4.subtract(x, y);
617
- if (JSBI4.lessThan(difference, ZERO)) {
618
- return JSBI4.add(Q256, difference);
619
- }
620
- return difference;
621
- }
622
- var TickLibrary = class {
623
- /**
624
- * Cannot be constructed.
625
- */
626
- constructor() {
627
- }
628
- static getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) {
629
- let feeGrowthBelow0X128;
630
- let feeGrowthBelow1X128;
631
- if (tickCurrent >= tickLower) {
632
- feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128;
633
- feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128;
634
- } else {
635
- feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128);
636
- feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128);
637
- }
638
- let feeGrowthAbove0X128;
639
- let feeGrowthAbove1X128;
640
- if (tickCurrent < tickUpper) {
641
- feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128;
642
- feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128;
643
- } else {
644
- feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128);
645
- feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128);
646
- }
647
- return [
648
- subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128),
649
- subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)
650
- ];
651
- }
652
- };
653
-
654
- // src/utils/positionMath.ts
655
- function getToken0Amount(tickCurrent, tickLower, tickUpper, sqrtRatioX96, liquidity) {
656
- if (tickCurrent < tickLower) {
657
- return SqrtPriceMath.getAmount0Delta(
658
- TickMath.getSqrtRatioAtTick(tickLower),
659
- TickMath.getSqrtRatioAtTick(tickUpper),
660
- liquidity,
661
- false
662
- );
753
+
754
+ // src/utils/positionMath.ts
755
+ function getToken0Amount(tickCurrent, tickLower, tickUpper, sqrtRatioX96, liquidity) {
756
+ if (tickCurrent < tickLower) {
757
+ return SqrtPriceMath.getAmount0Delta(
758
+ TickMath.getSqrtRatioAtTick(tickLower),
759
+ TickMath.getSqrtRatioAtTick(tickUpper),
760
+ liquidity,
761
+ false
762
+ );
663
763
  }
664
764
  if (tickCurrent < tickUpper) {
665
765
  return SqrtPriceMath.getAmount0Delta(sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickUpper), liquidity, false);
@@ -684,434 +784,43 @@ var PositionMath = {
684
784
  getToken0Amount,
685
785
  getToken1Amount
686
786
  };
687
- function parseNumberToFraction(num, precision = 6) {
688
- const scalar = 10 ** precision;
689
- return new Fraction$1(JSBI.BigInt(Math.floor(num * scalar)), JSBI.BigInt(scalar));
690
- }
691
-
692
- // src/utils/feeCalculator.ts
693
- var FeeCalculator = {
694
- getEstimatedLPFee,
695
- getLiquidityFromTick,
696
- getLiquidityFromSqrtRatioX96,
697
- getAverageLiquidity,
698
- getLiquidityBySingleAmount,
699
- getDependentAmount,
700
- getLiquidityByAmountsAndPrice,
701
- getAmountsByLiquidityAndPrice,
702
- getAmountsAtNewPrice
703
- };
704
- function getEstimatedLPFeeWithProtocolFee(options) {
705
- try {
706
- return tryGetEstimatedLPFee(options);
707
- } catch (e) {
708
- console.error(e);
709
- return new Fraction(ZERO$1);
710
- }
711
- }
712
- function getEstimatedLPFee({ protocolFee = ZERO_PERCENT, ...rest }) {
713
- try {
714
- const fee = tryGetEstimatedLPFee(rest);
715
- return ONE_HUNDRED_PERCENT.subtract(protocolFee).multiply(fee).asFraction;
716
- } catch (e) {
717
- console.error(e);
718
- return new Fraction(ZERO$1);
719
- }
720
- }
721
- function tryGetEstimatedLPFee({
722
- amount,
723
- currency,
724
- volume24H,
725
- sqrtRatioX96,
726
- tickLower,
727
- tickUpper,
728
- mostActiveLiquidity,
729
- fee,
730
- insidePercentage = ONE_HUNDRED_PERCENT
731
- }) {
732
- invariant11(!Number.isNaN(fee) && fee >= 0, "INVALID_FEE");
733
- const tickCurrent = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
734
- if (tickCurrent < tickLower || tickCurrent > tickUpper) {
735
- return new Fraction(ZERO$1);
736
- }
737
- const liquidity = FeeCalculator.getLiquidityBySingleAmount({ amount, currency, tickUpper, tickLower, sqrtRatioX96 });
738
- return insidePercentage.multiply(parseNumberToFraction(volume24H).multiply(JSBI$1.BigInt(fee)).multiply(liquidity)).divide(JSBI$1.multiply(MAX_FEE, JSBI$1.add(liquidity, mostActiveLiquidity))).asFraction;
739
- }
740
- function getDependentAmount(options) {
741
- const { currency, amount, sqrtRatioX96, tickLower, tickUpper } = options;
742
- const currentTick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
743
- const liquidity = FeeCalculator.getLiquidityBySingleAmount(options);
744
- const isToken0 = currency.wrapped.sortsBefore(amount.currency.wrapped);
745
- const getTokenAmount = isToken0 ? PositionMath.getToken0Amount : PositionMath.getToken1Amount;
746
- return CurrencyAmount.fromRawAmount(
747
- currency,
748
- getTokenAmount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity)
749
- );
750
- }
751
- function getLiquidityBySingleAmount({ amount, currency, ...rest }) {
752
- return getLiquidityByAmountsAndPrice({
753
- amountA: amount,
754
- amountB: CurrencyAmount.fromRawAmount(currency, MaxUint256),
755
- ...rest
756
- });
757
- }
758
- function getLiquidityByAmountsAndPrice({
759
- amountA,
760
- amountB,
761
- tickUpper,
762
- tickLower,
763
- sqrtRatioX96
764
- }) {
765
- const isToken0 = amountA.currency.wrapped.sortsBefore(amountB.currency.wrapped);
766
- const [inputAmount0, inputAmount1] = isToken0 ? [amountA.quotient, amountB.quotient] : [amountB.quotient, amountA.quotient];
767
- const sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
768
- const sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
769
- return maxLiquidityForAmounts(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, inputAmount0, inputAmount1, true);
770
- }
771
- function getAmountsByLiquidityAndPrice(options) {
772
- const { currencyA, currencyB, liquidity, sqrtRatioX96, tickLower, tickUpper } = options;
773
- const currentTick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
774
- const isToken0 = currencyA.wrapped.sortsBefore(currencyB.wrapped);
775
- const adjustedAmount0 = PositionMath.getToken0Amount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity);
776
- const adjustedAmount1 = PositionMath.getToken1Amount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity);
777
- return [
778
- CurrencyAmount.fromRawAmount(currencyA, isToken0 ? adjustedAmount0 : adjustedAmount1),
779
- CurrencyAmount.fromRawAmount(currencyB, isToken0 ? adjustedAmount1 : adjustedAmount0)
780
- ];
781
- }
782
- function getAmountsAtNewPrice({ newSqrtRatioX96, ...rest }) {
783
- const { tickLower, tickUpper, amountA, amountB } = rest;
784
- const liquidity = FeeCalculator.getLiquidityByAmountsAndPrice(rest);
785
- return FeeCalculator.getAmountsByLiquidityAndPrice({
786
- liquidity,
787
- currencyA: amountA.currency,
788
- currencyB: amountB.currency,
789
- tickLower,
790
- tickUpper,
791
- sqrtRatioX96: newSqrtRatioX96
792
- });
793
- }
794
- function getAverageLiquidity(ticks, tickSpacing, tickLower, tickUpper) {
795
- invariant11(tickLower <= tickUpper, "INVALID_TICK_RANGE");
796
- TickList.validateList(ticks, tickSpacing);
797
- if (tickLower === tickUpper) {
798
- return FeeCalculator.getLiquidityFromTick(ticks, tickLower);
799
- }
800
- const lowerOutOfBound = tickLower < ticks[0].index;
801
- let lastTick = lowerOutOfBound ? new Tick({ index: TickMath.MIN_TICK, liquidityNet: ZERO$1, liquidityGross: ZERO$1 }) : TickList.nextInitializedTick(ticks, tickLower, true);
802
- let currentTick = TickList.nextInitializedTick(ticks, tickLower, false);
803
- let currentL = lowerOutOfBound ? ZERO$1 : FeeCalculator.getLiquidityFromTick(ticks, currentTick.index);
804
- let weightedL = ZERO$1;
805
- const getWeightedLFromLastTickTo = (toTick) => JSBI$1.multiply(currentL, JSBI$1.BigInt(toTick - Math.max(lastTick.index, tickLower)));
806
- while (currentTick.index < tickUpper) {
807
- weightedL = JSBI$1.add(weightedL, getWeightedLFromLastTickTo(currentTick.index));
808
- currentL = JSBI$1.add(currentL, currentTick.liquidityNet);
809
- lastTick = currentTick;
810
- if (currentTick.index === ticks[ticks.length - 1].index) {
811
- break;
812
- }
813
- currentTick = TickList.nextInitializedTick(ticks, currentTick.index, false);
814
- }
815
- weightedL = JSBI$1.add(weightedL, getWeightedLFromLastTickTo(tickUpper));
816
- return JSBI$1.divide(weightedL, JSBI$1.BigInt(tickUpper - tickLower));
817
- }
818
- function getLiquidityFromSqrtRatioX96(ticks, sqrtRatioX96) {
819
- const tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
820
- return FeeCalculator.getLiquidityFromTick(ticks, tick);
821
- }
822
- function getLiquidityFromTick(ticks, tick) {
823
- var _a;
824
- let liquidity = ZERO$1;
825
- if (!(ticks == null ? void 0 : ticks.length))
826
- return liquidity;
827
- if (tick < ticks[0].index || tick > ticks[ticks.length - 1].index) {
828
- return liquidity;
829
- }
830
- for (let i = 0; i < ticks.length - 1; ++i) {
831
- liquidity = JSBI$1.add(liquidity, ticks[i].liquidityNet);
832
- const lowerTick = ticks[i].index;
833
- const upperTick = (_a = ticks[i + 1]) == null ? void 0 : _a.index;
834
- if (lowerTick <= tick && tick <= upperTick) {
835
- break;
836
- }
837
- }
838
- return liquidity;
839
- }
840
- var FEE_BASE = JSBI$1.exponentiate(JSBI$1.BigInt(10), JSBI$1.BigInt(4));
841
- function parseProtocolFees(feeProtocol) {
842
- const packed = Number(feeProtocol);
843
- if (Number.isNaN(packed)) {
844
- throw new Error(`Invalid fee protocol ${feeProtocol}`);
845
- }
846
- const token0ProtocolFee = packed % 2 ** 16;
847
- const token1ProtocolFee = packed >> 16;
848
- return [new Percent$1(token0ProtocolFee, FEE_BASE), new Percent$1(token1ProtocolFee, FEE_BASE)];
849
- }
850
-
851
- // src/entities/tick.ts
852
- var Tick = class {
853
- constructor({ index, liquidityGross, liquidityNet }) {
854
- invariant11(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK, "TICK");
855
- this.index = index;
856
- this.liquidityGross = JSBI4.BigInt(liquidityGross);
857
- this.liquidityNet = JSBI4.BigInt(liquidityNet);
858
- }
859
- };
860
-
861
- // src/entities/tickListDataProvider.ts
862
- var TickListDataProvider = class {
863
- constructor(ticks) {
864
- const ticksMapped = ticks.map((t) => t instanceof Tick ? t : new Tick(t));
865
- this.ticks = ticksMapped;
866
- }
867
- async getTick(tick) {
868
- return TickList.getTick(this.ticks, tick);
869
- }
870
- async nextInitializedTickWithinOneWord(tick, lte, tickSpacing) {
871
- return TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing);
872
- }
873
- };
874
787
 
875
- // src/entities/pool.ts
876
- var NO_TICK_DATA_PROVIDER_DEFAULT = new NoTickDataProvider();
877
- var Pool = class {
878
- static getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, deployerAddressOverride) {
879
- return computePoolAddress({
880
- deployerAddress: deployerAddressOverride != null ? deployerAddressOverride : DEPLOYER_ADDRESSES[tokenA.chainId],
881
- fee,
882
- tokenA,
883
- tokenB,
884
- initCodeHashManualOverride
885
- });
886
- }
788
+ // src/entities/position.ts
789
+ var Position = class {
887
790
  /**
888
- * Construct a pool
889
- * @param tokenA One of the tokens in the pool
890
- * @param tokenB The other token in the pool
891
- * @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
892
- * @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0
893
- * @param liquidity The current value of in range liquidity
894
- * @param tickCurrent The current tick of the pool
895
- * @param ticks The current state of the pool ticks or a data provider that can return tick data
791
+ * Constructs a position for a given pool with the given liquidity
792
+ * @param pool For which pool the liquidity is assigned
793
+ * @param liquidity The amount of liquidity that is in the position
794
+ * @param tickLower The lower tick of the position
795
+ * @param tickUpper The upper tick of the position
896
796
  */
897
- constructor(tokenA, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks = NO_TICK_DATA_PROVIDER_DEFAULT) {
898
- invariant11(Number.isInteger(fee) && fee < 1e6, "FEE");
899
- [this.token0, this.token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
900
- this.fee = fee;
901
- this.sqrtRatioX96 = JSBI4.BigInt(sqrtRatioX96);
902
- this.liquidity = JSBI4.BigInt(liquidity);
903
- this.tickCurrent = tickCurrent;
904
- this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks) : ticks;
797
+ constructor({ pool, liquidity, tickLower, tickUpper }) {
798
+ // cached resuts for the getters
799
+ this._token0Amount = null;
800
+ this._token1Amount = null;
801
+ this._mintAmounts = null;
802
+ invariant9(tickLower < tickUpper, "TICK_ORDER");
803
+ invariant9(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0, "TICK_LOWER");
804
+ invariant9(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0, "TICK_UPPER");
805
+ this.pool = pool;
806
+ this.tickLower = tickLower;
807
+ this.tickUpper = tickUpper;
808
+ this.liquidity = BigInt(liquidity);
905
809
  }
906
810
  /**
907
- * Returns true if the token is either token0 or token1
908
- * @param token The token to check
909
- * @returns True if token is either token0 or token
811
+ * Returns the price of token0 at the lower tick
910
812
  */
911
- involvesToken(token) {
912
- return token.equals(this.token0) || token.equals(this.token1);
813
+ get token0PriceLower() {
814
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickLower);
913
815
  }
914
816
  /**
915
- * Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
817
+ * Returns the price of token0 at the upper tick
916
818
  */
917
- get token0Price() {
918
- var _a;
919
- return (_a = this._token0Price) != null ? _a : this._token0Price = new Price(
920
- this.token0,
921
- this.token1,
922
- Q192,
923
- JSBI4.multiply(this.sqrtRatioX96, this.sqrtRatioX96)
924
- );
819
+ get token0PriceUpper() {
820
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickUpper);
925
821
  }
926
822
  /**
927
- * Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
928
- */
929
- get token1Price() {
930
- var _a;
931
- return (_a = this._token1Price) != null ? _a : this._token1Price = new Price(
932
- this.token1,
933
- this.token0,
934
- JSBI4.multiply(this.sqrtRatioX96, this.sqrtRatioX96),
935
- Q192
936
- );
937
- }
938
- /**
939
- * Return the price of the given token in terms of the other token in the pool.
940
- * @param token The token to return price of
941
- * @returns The price of the given token, in terms of the other.
942
- */
943
- priceOf(token) {
944
- invariant11(this.involvesToken(token), "TOKEN");
945
- return token.equals(this.token0) ? this.token0Price : this.token1Price;
946
- }
947
- /**
948
- * Returns the chain ID of the tokens in the pool.
949
- */
950
- get chainId() {
951
- return this.token0.chainId;
952
- }
953
- /**
954
- * Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
955
- * @param inputAmount The input amount for which to quote the output amount
956
- * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
957
- * @returns The output amount and the pool with updated state
958
- */
959
- async getOutputAmount(inputAmount, sqrtPriceLimitX96) {
960
- invariant11(this.involvesToken(inputAmount.currency), "TOKEN");
961
- const zeroForOne = inputAmount.currency.equals(this.token0);
962
- const {
963
- amountCalculated: outputAmount,
964
- sqrtRatioX96,
965
- liquidity,
966
- tickCurrent
967
- } = await this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96);
968
- const outputToken = zeroForOne ? this.token1 : this.token0;
969
- return [
970
- CurrencyAmount.fromRawAmount(outputToken, JSBI4.multiply(outputAmount, NEGATIVE_ONE)),
971
- new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)
972
- ];
973
- }
974
- /**
975
- * Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
976
- * @param outputAmount the output amount for which to quote the input amount
977
- * @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
978
- * @returns The input amount and the pool with updated state
979
- */
980
- async getInputAmount(outputAmount, sqrtPriceLimitX96) {
981
- invariant11(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency), "TOKEN");
982
- const zeroForOne = outputAmount.currency.equals(this.token1);
983
- const {
984
- amountSpecifiedRemaining,
985
- amountCalculated: inputAmount,
986
- sqrtRatioX96,
987
- liquidity,
988
- tickCurrent
989
- } = await this.swap(zeroForOne, JSBI4.multiply(outputAmount.quotient, NEGATIVE_ONE), sqrtPriceLimitX96);
990
- invariant11(JSBI4.equal(amountSpecifiedRemaining, ZERO), "INSUFICIENT_LIQUIDITY");
991
- const inputToken = zeroForOne ? this.token0 : this.token1;
992
- return [
993
- CurrencyAmount.fromRawAmount(inputToken, inputAmount),
994
- new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)
995
- ];
996
- }
997
- /**
998
- * Executes a swap
999
- * @param zeroForOne Whether the amount in is token0 or token1
1000
- * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
1001
- * @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
1002
- * @returns amountCalculated
1003
- * @returns sqrtRatioX96
1004
- * @returns liquidity
1005
- * @returns tickCurrent
1006
- */
1007
- async swap(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
1008
- if (!sqrtPriceLimitX96)
1009
- sqrtPriceLimitX96 = zeroForOne ? JSBI4.add(TickMath.MIN_SQRT_RATIO, ONE) : JSBI4.subtract(TickMath.MAX_SQRT_RATIO, ONE);
1010
- if (zeroForOne) {
1011
- invariant11(JSBI4.greaterThan(sqrtPriceLimitX96, TickMath.MIN_SQRT_RATIO), "RATIO_MIN");
1012
- invariant11(JSBI4.lessThan(sqrtPriceLimitX96, this.sqrtRatioX96), "RATIO_CURRENT");
1013
- } else {
1014
- invariant11(JSBI4.lessThan(sqrtPriceLimitX96, TickMath.MAX_SQRT_RATIO), "RATIO_MAX");
1015
- invariant11(JSBI4.greaterThan(sqrtPriceLimitX96, this.sqrtRatioX96), "RATIO_CURRENT");
1016
- }
1017
- const exactInput = JSBI4.greaterThanOrEqual(amountSpecified, ZERO);
1018
- const state = {
1019
- amountSpecifiedRemaining: amountSpecified,
1020
- amountCalculated: ZERO,
1021
- sqrtPriceX96: this.sqrtRatioX96,
1022
- tick: this.tickCurrent,
1023
- liquidity: this.liquidity
1024
- };
1025
- while (JSBI4.notEqual(state.amountSpecifiedRemaining, ZERO) && state.sqrtPriceX96 != sqrtPriceLimitX96) {
1026
- const step = {};
1027
- step.sqrtPriceStartX96 = state.sqrtPriceX96;
1028
- [step.tickNext, step.initialized] = await this.tickDataProvider.nextInitializedTickWithinOneWord(
1029
- state.tick,
1030
- zeroForOne,
1031
- this.tickSpacing
1032
- );
1033
- if (step.tickNext < TickMath.MIN_TICK) {
1034
- step.tickNext = TickMath.MIN_TICK;
1035
- } else if (step.tickNext > TickMath.MAX_TICK) {
1036
- step.tickNext = TickMath.MAX_TICK;
1037
- }
1038
- step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
1039
- [state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.computeSwapStep(
1040
- state.sqrtPriceX96,
1041
- (zeroForOne ? JSBI4.lessThan(step.sqrtPriceNextX96, sqrtPriceLimitX96) : JSBI4.greaterThan(step.sqrtPriceNextX96, sqrtPriceLimitX96)) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96,
1042
- state.liquidity,
1043
- state.amountSpecifiedRemaining,
1044
- this.fee
1045
- );
1046
- if (exactInput) {
1047
- state.amountSpecifiedRemaining = JSBI4.subtract(
1048
- state.amountSpecifiedRemaining,
1049
- JSBI4.add(step.amountIn, step.feeAmount)
1050
- );
1051
- state.amountCalculated = JSBI4.subtract(state.amountCalculated, step.amountOut);
1052
- } else {
1053
- state.amountSpecifiedRemaining = JSBI4.add(state.amountSpecifiedRemaining, step.amountOut);
1054
- state.amountCalculated = JSBI4.add(state.amountCalculated, JSBI4.add(step.amountIn, step.feeAmount));
1055
- }
1056
- if (JSBI4.equal(state.sqrtPriceX96, step.sqrtPriceNextX96)) {
1057
- if (step.initialized) {
1058
- let liquidityNet = JSBI4.BigInt((await this.tickDataProvider.getTick(step.tickNext)).liquidityNet);
1059
- if (zeroForOne)
1060
- liquidityNet = JSBI4.multiply(liquidityNet, NEGATIVE_ONE);
1061
- state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
1062
- }
1063
- state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
1064
- } else if (JSBI4.notEqual(state.sqrtPriceX96, step.sqrtPriceStartX96)) {
1065
- state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
1066
- }
1067
- }
1068
- return {
1069
- amountSpecifiedRemaining: state.amountSpecifiedRemaining,
1070
- amountCalculated: state.amountCalculated,
1071
- sqrtRatioX96: state.sqrtPriceX96,
1072
- liquidity: state.liquidity,
1073
- tickCurrent: state.tick
1074
- };
1075
- }
1076
- get tickSpacing() {
1077
- return TICK_SPACINGS[this.fee];
1078
- }
1079
- };
1080
- var Position = class {
1081
- /**
1082
- * Constructs a position for a given pool with the given liquidity
1083
- * @param pool For which pool the liquidity is assigned
1084
- * @param liquidity The amount of liquidity that is in the position
1085
- * @param tickLower The lower tick of the position
1086
- * @param tickUpper The upper tick of the position
1087
- */
1088
- constructor({ pool, liquidity, tickLower, tickUpper }) {
1089
- // cached resuts for the getters
1090
- this._token0Amount = null;
1091
- this._token1Amount = null;
1092
- this._mintAmounts = null;
1093
- invariant11(tickLower < tickUpper, "TICK_ORDER");
1094
- invariant11(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0, "TICK_LOWER");
1095
- invariant11(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0, "TICK_UPPER");
1096
- this.pool = pool;
1097
- this.tickLower = tickLower;
1098
- this.tickUpper = tickUpper;
1099
- this.liquidity = JSBI4.BigInt(liquidity);
1100
- }
1101
- /**
1102
- * Returns the price of token0 at the lower tick
1103
- */
1104
- get token0PriceLower() {
1105
- return tickToPrice(this.pool.token0, this.pool.token1, this.tickLower);
1106
- }
1107
- /**
1108
- * Returns the price of token0 at the upper tick
1109
- */
1110
- get token0PriceUpper() {
1111
- return tickToPrice(this.pool.token0, this.pool.token1, this.tickUpper);
1112
- }
1113
- /**
1114
- * Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
823
+ * Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
1115
824
  */
1116
825
  get amount0() {
1117
826
  if (this._token0Amount === null) {
@@ -1155,12 +864,12 @@ var Position = class {
1155
864
  const priceLower = this.pool.token0Price.asFraction.multiply(new Percent$1(1).subtract(slippageTolerance));
1156
865
  const priceUpper = this.pool.token0Price.asFraction.multiply(slippageTolerance.add(1));
1157
866
  let sqrtRatioX96Lower = encodeSqrtRatioX96(priceLower.numerator, priceLower.denominator);
1158
- if (JSBI4.lessThanOrEqual(sqrtRatioX96Lower, TickMath.MIN_SQRT_RATIO)) {
1159
- sqrtRatioX96Lower = JSBI4.add(TickMath.MIN_SQRT_RATIO, JSBI4.BigInt(1));
867
+ if (sqrtRatioX96Lower <= TickMath.MIN_SQRT_RATIO) {
868
+ sqrtRatioX96Lower = TickMath.MIN_SQRT_RATIO + 1n;
1160
869
  }
1161
870
  let sqrtRatioX96Upper = encodeSqrtRatioX96(priceUpper.numerator, priceUpper.denominator);
1162
- if (JSBI4.greaterThanOrEqual(sqrtRatioX96Upper, TickMath.MAX_SQRT_RATIO)) {
1163
- sqrtRatioX96Upper = JSBI4.subtract(TickMath.MAX_SQRT_RATIO, JSBI4.BigInt(1));
871
+ if (sqrtRatioX96Upper >= TickMath.MAX_SQRT_RATIO) {
872
+ sqrtRatioX96Upper = TickMath.MAX_SQRT_RATIO - 1n;
1164
873
  }
1165
874
  return {
1166
875
  sqrtRatioX96Lower,
@@ -1349,7 +1058,7 @@ var Position = class {
1349
1058
  amount0,
1350
1059
  useFullPrecision
1351
1060
  }) {
1352
- return Position.fromAmounts({ pool, tickLower, tickUpper, amount0, amount1: MaxUint256, useFullPrecision });
1061
+ return Position.fromAmounts({ pool, tickLower, tickUpper, amount0, amount1: MaxUint256$1, useFullPrecision });
1353
1062
  }
1354
1063
  /**
1355
1064
  * Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
@@ -1365,7 +1074,7 @@ var Position = class {
1365
1074
  tickUpper,
1366
1075
  amount1
1367
1076
  }) {
1368
- return Position.fromAmounts({ pool, tickLower, tickUpper, amount0: MaxUint256, amount1, useFullPrecision: true });
1077
+ return Position.fromAmounts({ pool, tickLower, tickUpper, amount0: MaxUint256$1, amount1, useFullPrecision: true });
1369
1078
  }
1370
1079
  };
1371
1080
  var Route = class {
@@ -1377,24 +1086,24 @@ var Route = class {
1377
1086
  */
1378
1087
  constructor(pools, input, output) {
1379
1088
  this._midPrice = null;
1380
- invariant11(pools.length > 0, "POOLS");
1089
+ invariant9(pools.length > 0, "POOLS");
1381
1090
  const { chainId } = pools[0];
1382
1091
  const allOnSameChain = pools.every((pool) => pool.chainId === chainId);
1383
- invariant11(allOnSameChain, "CHAIN_IDS");
1092
+ invariant9(allOnSameChain, "CHAIN_IDS");
1384
1093
  const wrappedInput = input.wrapped;
1385
- invariant11(pools[0].involvesToken(wrappedInput), "INPUT");
1386
- invariant11(pools[pools.length - 1].involvesToken(output.wrapped), "OUTPUT");
1094
+ invariant9(pools[0].involvesToken(wrappedInput), "INPUT");
1095
+ invariant9(pools[pools.length - 1].involvesToken(output.wrapped), "OUTPUT");
1387
1096
  const tokenPath = [wrappedInput];
1388
1097
  for (const [i, pool] of pools.entries()) {
1389
1098
  const currentInputToken = tokenPath[i];
1390
- invariant11(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1), "PATH");
1099
+ invariant9(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1), "PATH");
1391
1100
  const nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0;
1392
1101
  tokenPath.push(nextToken);
1393
1102
  }
1394
1103
  this.pools = pools;
1395
1104
  this.tokenPath = tokenPath;
1396
1105
  this.input = input;
1397
- this.output = output != null ? output : tokenPath[tokenPath.length - 1];
1106
+ this.output = output ?? tokenPath[tokenPath.length - 1];
1398
1107
  }
1399
1108
  get chainId() {
1400
1109
  return this.pools[0].chainId;
@@ -1427,8 +1136,8 @@ var Route = class {
1427
1136
  }
1428
1137
  };
1429
1138
  function tradeComparator(a, b) {
1430
- invariant11(a.inputAmount.currency.equals(b.inputAmount.currency), "INPUT_CURRENCY");
1431
- invariant11(a.outputAmount.currency.equals(b.outputAmount.currency), "OUTPUT_CURRENCY");
1139
+ invariant9(a.inputAmount.currency.equals(b.inputAmount.currency), "INPUT_CURRENCY");
1140
+ invariant9(a.outputAmount.currency.equals(b.outputAmount.currency), "OUTPUT_CURRENCY");
1432
1141
  if (a.outputAmount.equalTo(b.outputAmount)) {
1433
1142
  if (a.inputAmount.equalTo(b.inputAmount)) {
1434
1143
  const aHops = a.swaps.reduce((total, cur) => total + cur.route.tokenPath.length, 0);
@@ -1454,7 +1163,7 @@ var Trade = class {
1454
1163
  * i.e. which pools the trade goes through.
1455
1164
  */
1456
1165
  get route() {
1457
- invariant11(this.swaps.length == 1, "MULTIPLE_ROUTES");
1166
+ invariant9(this.swaps.length == 1, "MULTIPLE_ROUTES");
1458
1167
  return this.swaps[0].route;
1459
1168
  }
1460
1169
  /**
@@ -1485,13 +1194,12 @@ var Trade = class {
1485
1194
  * The price expressed in terms of output amount/input amount.
1486
1195
  */
1487
1196
  get executionPrice() {
1488
- var _a;
1489
- return (_a = this._executionPrice) != null ? _a : this._executionPrice = new Price(
1197
+ return this._executionPrice ?? (this._executionPrice = new Price(
1490
1198
  this.inputAmount.currency,
1491
1199
  this.outputAmount.currency,
1492
1200
  this.inputAmount.quotient,
1493
1201
  this.outputAmount.quotient
1494
- );
1202
+ ));
1495
1203
  }
1496
1204
  /**
1497
1205
  * Returns the percent difference between the route's mid price and the price impact
@@ -1546,7 +1254,7 @@ var Trade = class {
1546
1254
  let inputAmount;
1547
1255
  let outputAmount;
1548
1256
  if (tradeType === TradeType.EXACT_INPUT) {
1549
- invariant11(amount.currency.equals(route.input), "INPUT");
1257
+ invariant9(amount.currency.equals(route.input), "INPUT");
1550
1258
  amounts[0] = amount.wrapped;
1551
1259
  for (let i = 0; i < route.tokenPath.length - 1; i++) {
1552
1260
  const pool = route.pools[i];
@@ -1560,7 +1268,7 @@ var Trade = class {
1560
1268
  amounts[amounts.length - 1].denominator
1561
1269
  );
1562
1270
  } else {
1563
- invariant11(amount.currency.equals(route.output), "OUTPUT");
1271
+ invariant9(amount.currency.equals(route.output), "OUTPUT");
1564
1272
  amounts[amounts.length - 1] = amount.wrapped;
1565
1273
  for (let i = route.tokenPath.length - 1; i > 0; i--) {
1566
1274
  const pool = route.pools[i - 1];
@@ -1592,7 +1300,7 @@ var Trade = class {
1592
1300
  let inputAmount;
1593
1301
  let outputAmount;
1594
1302
  if (tradeType === TradeType.EXACT_INPUT) {
1595
- invariant11(amount.currency.equals(route.input), "INPUT");
1303
+ invariant9(amount.currency.equals(route.input), "INPUT");
1596
1304
  inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1597
1305
  amounts[0] = CurrencyAmount.fromFractionalAmount(route.input.wrapped, amount.numerator, amount.denominator);
1598
1306
  for (let i = 0; i < route.tokenPath.length - 1; i++) {
@@ -1606,7 +1314,7 @@ var Trade = class {
1606
1314
  amounts[amounts.length - 1].denominator
1607
1315
  );
1608
1316
  } else {
1609
- invariant11(amount.currency.equals(route.output), "OUTPUT");
1317
+ invariant9(amount.currency.equals(route.output), "OUTPUT");
1610
1318
  outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1611
1319
  amounts[amounts.length - 1] = CurrencyAmount.fromFractionalAmount(
1612
1320
  route.output.wrapped,
@@ -1671,11 +1379,11 @@ var Trade = class {
1671
1379
  }) {
1672
1380
  const inputCurrency = routes[0].inputAmount.currency;
1673
1381
  const outputCurrency = routes[0].outputAmount.currency;
1674
- invariant11(
1382
+ invariant9(
1675
1383
  routes.every(({ route }) => inputCurrency.wrapped.equals(route.input.wrapped)),
1676
1384
  "INPUT_CURRENCY_MATCH"
1677
1385
  );
1678
- invariant11(
1386
+ invariant9(
1679
1387
  routes.every(({ route }) => outputCurrency.wrapped.equals(route.output.wrapped)),
1680
1388
  "OUTPUT_CURRENCY_MATCH"
1681
1389
  );
@@ -1686,7 +1394,7 @@ var Trade = class {
1686
1394
  poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, pool.fee));
1687
1395
  }
1688
1396
  }
1689
- invariant11(numPools == poolAddressSet.size, "POOLS_DUPLICATED");
1397
+ invariant9(numPools == poolAddressSet.size, "POOLS_DUPLICATED");
1690
1398
  this.swaps = routes;
1691
1399
  this.tradeType = tradeType;
1692
1400
  }
@@ -1696,169 +1404,459 @@ var Trade = class {
1696
1404
  * @returns The amount out
1697
1405
  */
1698
1406
  minimumAmountOut(slippageTolerance, amountOut = this.outputAmount) {
1699
- invariant11(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1407
+ invariant9(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1700
1408
  if (this.tradeType === TradeType.EXACT_OUTPUT) {
1701
1409
  return amountOut;
1702
1410
  }
1703
1411
  const slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
1704
1412
  return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
1705
1413
  }
1706
- /**
1707
- * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
1708
- * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
1709
- * @returns The amount in
1710
- */
1711
- maximumAmountIn(slippageTolerance, amountIn = this.inputAmount) {
1712
- invariant11(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1713
- if (this.tradeType === TradeType.EXACT_INPUT) {
1714
- return amountIn;
1414
+ /**
1415
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
1416
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
1417
+ * @returns The amount in
1418
+ */
1419
+ maximumAmountIn(slippageTolerance, amountIn = this.inputAmount) {
1420
+ invariant9(!slippageTolerance.lessThan(ZERO), "SLIPPAGE_TOLERANCE");
1421
+ if (this.tradeType === TradeType.EXACT_INPUT) {
1422
+ return amountIn;
1423
+ }
1424
+ const slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
1425
+ return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
1426
+ }
1427
+ /**
1428
+ * Return the execution price after accounting for slippage tolerance
1429
+ * @param slippageTolerance the allowed tolerated slippage
1430
+ * @returns The execution price
1431
+ */
1432
+ worstExecutionPrice(slippageTolerance) {
1433
+ return new Price(
1434
+ this.inputAmount.currency,
1435
+ this.outputAmount.currency,
1436
+ this.maximumAmountIn(slippageTolerance).quotient,
1437
+ this.minimumAmountOut(slippageTolerance).quotient
1438
+ );
1439
+ }
1440
+ /**
1441
+ * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
1442
+ * amount to an output token, making at most `maxHops` hops.
1443
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
1444
+ * the amount in among multiple routes.
1445
+ * @param pools the pools to consider in finding the best trade
1446
+ * @param nextAmountIn exact amount of input currency to spend
1447
+ * @param currencyOut the desired currency out
1448
+ * @param maxNumResults maximum number of results to return
1449
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1450
+ * @param currentPools used in recursion; the current list of pools
1451
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
1452
+ * @param bestTrades used in recursion; the current list of best trades
1453
+ * @returns The exact in trade
1454
+ */
1455
+ static async bestTradeExactIn(pools, currencyAmountIn, currencyOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountIn = currencyAmountIn, bestTrades = []) {
1456
+ invariant9(pools.length > 0, "POOLS");
1457
+ invariant9(maxHops > 0, "MAX_HOPS");
1458
+ invariant9(currencyAmountIn === nextAmountIn || currentPools.length > 0, "INVALID_RECURSION");
1459
+ const amountIn = nextAmountIn.wrapped;
1460
+ const tokenOut = currencyOut.wrapped;
1461
+ for (let i = 0; i < pools.length; i++) {
1462
+ const pool = pools[i];
1463
+ if (!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency))
1464
+ continue;
1465
+ let amountOut;
1466
+ try {
1467
+ const [result] = await pool.getOutputAmount(amountIn);
1468
+ amountOut = result;
1469
+ } catch (error) {
1470
+ if (error.isInsufficientInputAmountError) {
1471
+ continue;
1472
+ }
1473
+ throw error;
1474
+ }
1475
+ if (amountOut.currency.isToken && amountOut.currency.equals(tokenOut)) {
1476
+ sortedInsert(
1477
+ bestTrades,
1478
+ await Trade.fromRoute(
1479
+ new Route([...currentPools, pool], currencyAmountIn.currency, currencyOut),
1480
+ currencyAmountIn,
1481
+ TradeType.EXACT_INPUT
1482
+ ),
1483
+ maxNumResults,
1484
+ tradeComparator
1485
+ );
1486
+ } else if (maxHops > 1 && pools.length > 1) {
1487
+ const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1488
+ await Trade.bestTradeExactIn(
1489
+ poolsExcludingThisPool,
1490
+ currencyAmountIn,
1491
+ currencyOut,
1492
+ {
1493
+ maxNumResults,
1494
+ maxHops: maxHops - 1
1495
+ },
1496
+ [...currentPools, pool],
1497
+ amountOut,
1498
+ bestTrades
1499
+ );
1500
+ }
1501
+ }
1502
+ return bestTrades;
1503
+ }
1504
+ /**
1505
+ * similar to the above method but instead targets a fixed output amount
1506
+ * given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
1507
+ * to an output token amount, making at most `maxHops` hops
1508
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
1509
+ * the amount in among multiple routes.
1510
+ * @param pools the pools to consider in finding the best trade
1511
+ * @param currencyIn the currency to spend
1512
+ * @param currencyAmountOut the desired currency amount out
1513
+ * @param nextAmountOut the exact amount of currency out
1514
+ * @param maxNumResults maximum number of results to return
1515
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1516
+ * @param currentPools used in recursion; the current list of pools
1517
+ * @param bestTrades used in recursion; the current list of best trades
1518
+ * @returns The exact out trade
1519
+ */
1520
+ static async bestTradeExactOut(pools, currencyIn, currencyAmountOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountOut = currencyAmountOut, bestTrades = []) {
1521
+ invariant9(pools.length > 0, "POOLS");
1522
+ invariant9(maxHops > 0, "MAX_HOPS");
1523
+ invariant9(currencyAmountOut === nextAmountOut || currentPools.length > 0, "INVALID_RECURSION");
1524
+ const amountOut = nextAmountOut.wrapped;
1525
+ const tokenIn = currencyIn.wrapped;
1526
+ for (let i = 0; i < pools.length; i++) {
1527
+ const pool = pools[i];
1528
+ if (!pool.token0.equals(amountOut.currency) && !pool.token1.equals(amountOut.currency))
1529
+ continue;
1530
+ let amountIn;
1531
+ try {
1532
+ const [result] = await pool.getInputAmount(amountOut);
1533
+ amountIn = result;
1534
+ } catch (error) {
1535
+ if (error.isInsufficientReservesError) {
1536
+ continue;
1537
+ }
1538
+ throw error;
1539
+ }
1540
+ if (amountIn.currency.equals(tokenIn)) {
1541
+ sortedInsert(
1542
+ bestTrades,
1543
+ await Trade.fromRoute(
1544
+ new Route([pool, ...currentPools], currencyIn, currencyAmountOut.currency),
1545
+ currencyAmountOut,
1546
+ TradeType.EXACT_OUTPUT
1547
+ ),
1548
+ maxNumResults,
1549
+ tradeComparator
1550
+ );
1551
+ } else if (maxHops > 1 && pools.length > 1) {
1552
+ const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1553
+ await Trade.bestTradeExactOut(
1554
+ poolsExcludingThisPool,
1555
+ currencyIn,
1556
+ currencyAmountOut,
1557
+ {
1558
+ maxNumResults,
1559
+ maxHops: maxHops - 1
1560
+ },
1561
+ [pool, ...currentPools],
1562
+ amountIn,
1563
+ bestTrades
1564
+ );
1565
+ }
1566
+ }
1567
+ return bestTrades;
1568
+ }
1569
+ };
1570
+
1571
+ // src/utils/calldata.ts
1572
+ function toHex(bigintIsh) {
1573
+ const bigInt = BigInt(bigintIsh);
1574
+ let hex = bigInt.toString(16);
1575
+ if (hex.length % 2 !== 0) {
1576
+ hex = `0${hex}`;
1577
+ }
1578
+ return `0x${hex}`;
1579
+ }
1580
+ function encodeRouteToPath(route, exactOutput) {
1581
+ const firstInputToken = route.input.wrapped;
1582
+ const { path, types } = route.pools.reduce(
1583
+ ({ inputToken, path: path2, types: types2 }, pool, index) => {
1584
+ const outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
1585
+ if (index === 0) {
1586
+ return {
1587
+ inputToken: outputToken,
1588
+ types: ["address", "uint24", "address"],
1589
+ path: [inputToken.address, pool.fee, outputToken.address]
1590
+ };
1591
+ }
1592
+ return {
1593
+ inputToken: outputToken,
1594
+ types: [...types2, "uint24", "address"],
1595
+ path: [...path2, pool.fee, outputToken.address]
1596
+ };
1597
+ },
1598
+ { inputToken: firstInputToken, path: [], types: [] }
1599
+ );
1600
+ return exactOutput ? encodePacked(types.reverse(), path.reverse()) : encodePacked(types, path);
1601
+ }
1602
+ function nearestUsableTick(tick, tickSpacing) {
1603
+ invariant9(Number.isInteger(tick) && Number.isInteger(tickSpacing), "INTEGERS");
1604
+ invariant9(tickSpacing > 0, "TICK_SPACING");
1605
+ invariant9(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK, "TICK_BOUND");
1606
+ const rounded = Math.round(tick / tickSpacing) * tickSpacing;
1607
+ if (rounded < TickMath.MIN_TICK)
1608
+ return rounded + tickSpacing;
1609
+ if (rounded > TickMath.MAX_TICK)
1610
+ return rounded - tickSpacing;
1611
+ return rounded;
1612
+ }
1613
+
1614
+ // src/utils/position.ts
1615
+ var PositionLibrary = class {
1616
+ /**
1617
+ * Cannot be constructed.
1618
+ */
1619
+ constructor() {
1620
+ }
1621
+ // replicates the portions of Position#update required to compute unaccounted fees
1622
+ static getTokensOwed(feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, feeGrowthInside0X128, feeGrowthInside1X128) {
1623
+ const tokensOwed0 = subIn256(feeGrowthInside0X128, feeGrowthInside0LastX128) * liquidity / Q128;
1624
+ const tokensOwed1 = subIn256(feeGrowthInside1X128, feeGrowthInside1LastX128) * liquidity / Q128;
1625
+ return [tokensOwed0, tokensOwed1];
1626
+ }
1627
+ };
1628
+
1629
+ // src/utils/tickLibrary.ts
1630
+ var Q256 = 2n ** 256n;
1631
+ function subIn256(x, y) {
1632
+ const difference = x - y;
1633
+ if (difference < ZERO) {
1634
+ return Q256 + difference;
1635
+ }
1636
+ return difference;
1637
+ }
1638
+ var TickLibrary = class {
1639
+ /**
1640
+ * Cannot be constructed.
1641
+ */
1642
+ constructor() {
1643
+ }
1644
+ static getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) {
1645
+ let feeGrowthBelow0X128;
1646
+ let feeGrowthBelow1X128;
1647
+ if (tickCurrent >= tickLower) {
1648
+ feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128;
1649
+ feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128;
1650
+ } else {
1651
+ feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128);
1652
+ feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128);
1653
+ }
1654
+ let feeGrowthAbove0X128;
1655
+ let feeGrowthAbove1X128;
1656
+ if (tickCurrent < tickUpper) {
1657
+ feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128;
1658
+ feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128;
1659
+ } else {
1660
+ feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128);
1661
+ feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128);
1662
+ }
1663
+ return [
1664
+ subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128),
1665
+ subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)
1666
+ ];
1667
+ }
1668
+ };
1669
+ function parseNumberToFraction(num, precision = 6) {
1670
+ if (Number.isNaN(num) || !Number.isFinite(num)) {
1671
+ return void 0;
1672
+ }
1673
+ const scalar = 10 ** precision;
1674
+ return new Fraction$1(BigInt(Math.floor(num * scalar)), BigInt(scalar));
1675
+ }
1676
+
1677
+ // src/utils/feeCalculator.ts
1678
+ var FeeCalculator = {
1679
+ getEstimatedLPFee,
1680
+ getEstimatedLPFeeByAmounts,
1681
+ getLiquidityFromTick,
1682
+ getLiquidityFromSqrtRatioX96,
1683
+ getAverageLiquidity,
1684
+ getLiquidityBySingleAmount,
1685
+ getDependentAmount,
1686
+ getLiquidityByAmountsAndPrice,
1687
+ getAmountsByLiquidityAndPrice,
1688
+ getAmountsAtNewPrice
1689
+ };
1690
+ function getEstimatedLPFeeWithProtocolFee({ amount, currency, ...rest }) {
1691
+ return getEstimatedLPFeeByAmountsWithProtocolFee({
1692
+ ...rest,
1693
+ amountA: amount,
1694
+ amountB: CurrencyAmount$1.fromRawAmount(currency, MaxUint256)
1695
+ });
1696
+ }
1697
+ function getEstimatedLPFee({ amount, currency, ...rest }) {
1698
+ return getEstimatedLPFeeByAmounts({
1699
+ ...rest,
1700
+ amountA: amount,
1701
+ amountB: CurrencyAmount$1.fromRawAmount(currency, MaxUint256)
1702
+ });
1703
+ }
1704
+ function getEstimatedLPFeeByAmountsWithProtocolFee(options) {
1705
+ try {
1706
+ return tryGetEstimatedLPFeeByAmounts(options);
1707
+ } catch (e) {
1708
+ console.error(e);
1709
+ return new Fraction$1(ZERO$1);
1710
+ }
1711
+ }
1712
+ function getEstimatedLPFeeByAmounts({ protocolFee = ZERO_PERCENT, ...rest }) {
1713
+ try {
1714
+ const fee = tryGetEstimatedLPFeeByAmounts(rest);
1715
+ return ONE_HUNDRED_PERCENT.subtract(protocolFee).multiply(fee).asFraction;
1716
+ } catch (e) {
1717
+ console.error(e);
1718
+ return new Fraction$1(ZERO$1);
1719
+ }
1720
+ }
1721
+ function tryGetEstimatedLPFeeByAmounts({
1722
+ amountA,
1723
+ amountB,
1724
+ volume24H,
1725
+ sqrtRatioX96,
1726
+ tickLower,
1727
+ tickUpper,
1728
+ mostActiveLiquidity,
1729
+ fee,
1730
+ insidePercentage = ONE_HUNDRED_PERCENT
1731
+ }) {
1732
+ invariant9(!Number.isNaN(fee) && fee >= 0, "INVALID_FEE");
1733
+ const tickCurrent = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1734
+ if (tickCurrent < tickLower || tickCurrent > tickUpper) {
1735
+ return new Fraction$1(ZERO$1);
1736
+ }
1737
+ const liquidity = FeeCalculator.getLiquidityByAmountsAndPrice({
1738
+ amountA,
1739
+ amountB,
1740
+ tickUpper,
1741
+ tickLower,
1742
+ sqrtRatioX96
1743
+ });
1744
+ const volumeInFraction = parseNumberToFraction(volume24H) || new Fraction$1(ZERO$1);
1745
+ return insidePercentage.multiply(volumeInFraction.multiply(BigInt(fee)).multiply(liquidity)).divide(MAX_FEE * (liquidity + mostActiveLiquidity)).asFraction;
1746
+ }
1747
+ function getDependentAmount(options) {
1748
+ const { currency, amount, sqrtRatioX96, tickLower, tickUpper } = options;
1749
+ const currentTick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1750
+ const liquidity = FeeCalculator.getLiquidityBySingleAmount(options);
1751
+ const isToken0 = currency.wrapped.sortsBefore(amount.currency.wrapped);
1752
+ const getTokenAmount = isToken0 ? PositionMath.getToken0Amount : PositionMath.getToken1Amount;
1753
+ return CurrencyAmount$1.fromRawAmount(
1754
+ currency,
1755
+ getTokenAmount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity)
1756
+ );
1757
+ }
1758
+ function getLiquidityBySingleAmount({ amount, currency, ...rest }) {
1759
+ return getLiquidityByAmountsAndPrice({
1760
+ amountA: amount,
1761
+ amountB: CurrencyAmount$1.fromRawAmount(currency, MaxUint256),
1762
+ ...rest
1763
+ });
1764
+ }
1765
+ function getLiquidityByAmountsAndPrice({
1766
+ amountA,
1767
+ amountB,
1768
+ tickUpper,
1769
+ tickLower,
1770
+ sqrtRatioX96
1771
+ }) {
1772
+ const isToken0 = amountA.currency.wrapped.address !== amountB.currency.wrapped.address ? amountA.currency.wrapped.sortsBefore(amountB.currency.wrapped) : true;
1773
+ const [inputAmount0, inputAmount1] = isToken0 ? [amountA.quotient, amountB.quotient] : [amountB.quotient, amountA.quotient];
1774
+ const sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
1775
+ const sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
1776
+ return maxLiquidityForAmounts(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, inputAmount0, inputAmount1, true);
1777
+ }
1778
+ function getAmountsByLiquidityAndPrice(options) {
1779
+ const { currencyA, currencyB, liquidity, sqrtRatioX96, tickLower, tickUpper } = options;
1780
+ const currentTick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1781
+ const isToken0 = currencyA.wrapped.sortsBefore(currencyB.wrapped);
1782
+ const adjustedAmount0 = PositionMath.getToken0Amount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity);
1783
+ const adjustedAmount1 = PositionMath.getToken1Amount(currentTick, tickLower, tickUpper, sqrtRatioX96, liquidity);
1784
+ return [
1785
+ CurrencyAmount$1.fromRawAmount(currencyA, isToken0 ? adjustedAmount0 : adjustedAmount1),
1786
+ CurrencyAmount$1.fromRawAmount(currencyB, isToken0 ? adjustedAmount1 : adjustedAmount0)
1787
+ ];
1788
+ }
1789
+ function getAmountsAtNewPrice({ newSqrtRatioX96, ...rest }) {
1790
+ const { tickLower, tickUpper, amountA, amountB } = rest;
1791
+ const liquidity = FeeCalculator.getLiquidityByAmountsAndPrice(rest);
1792
+ return FeeCalculator.getAmountsByLiquidityAndPrice({
1793
+ liquidity,
1794
+ currencyA: amountA.currency,
1795
+ currencyB: amountB.currency,
1796
+ tickLower,
1797
+ tickUpper,
1798
+ sqrtRatioX96: newSqrtRatioX96
1799
+ });
1800
+ }
1801
+ function getAverageLiquidity(ticks, tickSpacing, tickLower, tickUpper) {
1802
+ invariant9(tickLower <= tickUpper, "INVALID_TICK_RANGE");
1803
+ TickList.validateList(ticks, tickSpacing);
1804
+ if (tickLower === tickUpper) {
1805
+ return FeeCalculator.getLiquidityFromTick(ticks, tickLower);
1806
+ }
1807
+ const lowerOutOfBound = tickLower < ticks[0].index;
1808
+ let lastTick = lowerOutOfBound ? new Tick({ index: TickMath.MIN_TICK, liquidityNet: ZERO$1, liquidityGross: ZERO$1 }) : TickList.nextInitializedTick(ticks, tickLower, true);
1809
+ let currentTick = TickList.nextInitializedTick(ticks, tickLower, false);
1810
+ let currentL = lowerOutOfBound ? ZERO$1 : FeeCalculator.getLiquidityFromTick(ticks, currentTick.index);
1811
+ let weightedL = ZERO$1;
1812
+ const getWeightedLFromLastTickTo = (toTick) => currentL * BigInt(toTick - Math.max(lastTick.index, tickLower));
1813
+ while (currentTick.index < tickUpper) {
1814
+ weightedL += getWeightedLFromLastTickTo(currentTick.index);
1815
+ currentL += currentTick.liquidityNet;
1816
+ lastTick = currentTick;
1817
+ if (currentTick.index === ticks[ticks.length - 1].index) {
1818
+ break;
1715
1819
  }
1716
- const slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
1717
- return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
1820
+ currentTick = TickList.nextInitializedTick(ticks, currentTick.index, false);
1718
1821
  }
1719
- /**
1720
- * Return the execution price after accounting for slippage tolerance
1721
- * @param slippageTolerance the allowed tolerated slippage
1722
- * @returns The execution price
1723
- */
1724
- worstExecutionPrice(slippageTolerance) {
1725
- return new Price(
1726
- this.inputAmount.currency,
1727
- this.outputAmount.currency,
1728
- this.maximumAmountIn(slippageTolerance).quotient,
1729
- this.minimumAmountOut(slippageTolerance).quotient
1730
- );
1822
+ weightedL += getWeightedLFromLastTickTo(tickUpper);
1823
+ return weightedL / BigInt(tickUpper - tickLower);
1824
+ }
1825
+ function getLiquidityFromSqrtRatioX96(ticks, sqrtRatioX96) {
1826
+ const tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1827
+ return FeeCalculator.getLiquidityFromTick(ticks, tick);
1828
+ }
1829
+ function getLiquidityFromTick(ticks, tick) {
1830
+ let liquidity = ZERO$1;
1831
+ if (!ticks?.length)
1832
+ return liquidity;
1833
+ if (tick < ticks[0].index || tick > ticks[ticks.length - 1].index) {
1834
+ return liquidity;
1731
1835
  }
1732
- /**
1733
- * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
1734
- * amount to an output token, making at most `maxHops` hops.
1735
- * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
1736
- * the amount in among multiple routes.
1737
- * @param pools the pools to consider in finding the best trade
1738
- * @param nextAmountIn exact amount of input currency to spend
1739
- * @param currencyOut the desired currency out
1740
- * @param maxNumResults maximum number of results to return
1741
- * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1742
- * @param currentPools used in recursion; the current list of pools
1743
- * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
1744
- * @param bestTrades used in recursion; the current list of best trades
1745
- * @returns The exact in trade
1746
- */
1747
- static async bestTradeExactIn(pools, currencyAmountIn, currencyOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountIn = currencyAmountIn, bestTrades = []) {
1748
- invariant11(pools.length > 0, "POOLS");
1749
- invariant11(maxHops > 0, "MAX_HOPS");
1750
- invariant11(currencyAmountIn === nextAmountIn || currentPools.length > 0, "INVALID_RECURSION");
1751
- const amountIn = nextAmountIn.wrapped;
1752
- const tokenOut = currencyOut.wrapped;
1753
- for (let i = 0; i < pools.length; i++) {
1754
- const pool = pools[i];
1755
- if (!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency))
1756
- continue;
1757
- let amountOut;
1758
- try {
1759
- const [result] = await pool.getOutputAmount(amountIn);
1760
- amountOut = result;
1761
- } catch (error) {
1762
- if (error.isInsufficientInputAmountError) {
1763
- continue;
1764
- }
1765
- throw error;
1766
- }
1767
- if (amountOut.currency.isToken && amountOut.currency.equals(tokenOut)) {
1768
- sortedInsert(
1769
- bestTrades,
1770
- await Trade.fromRoute(
1771
- new Route([...currentPools, pool], currencyAmountIn.currency, currencyOut),
1772
- currencyAmountIn,
1773
- TradeType.EXACT_INPUT
1774
- ),
1775
- maxNumResults,
1776
- tradeComparator
1777
- );
1778
- } else if (maxHops > 1 && pools.length > 1) {
1779
- const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1780
- await Trade.bestTradeExactIn(
1781
- poolsExcludingThisPool,
1782
- currencyAmountIn,
1783
- currencyOut,
1784
- {
1785
- maxNumResults,
1786
- maxHops: maxHops - 1
1787
- },
1788
- [...currentPools, pool],
1789
- amountOut,
1790
- bestTrades
1791
- );
1792
- }
1836
+ for (let i = 0; i < ticks.length - 1; ++i) {
1837
+ liquidity += ticks[i].liquidityNet;
1838
+ const lowerTick = ticks[i].index;
1839
+ const upperTick = ticks[i + 1]?.index;
1840
+ if (lowerTick <= tick && tick <= upperTick) {
1841
+ break;
1793
1842
  }
1794
- return bestTrades;
1795
1843
  }
1796
- /**
1797
- * similar to the above method but instead targets a fixed output amount
1798
- * given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
1799
- * to an output token amount, making at most `maxHops` hops
1800
- * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
1801
- * the amount in among multiple routes.
1802
- * @param pools the pools to consider in finding the best trade
1803
- * @param currencyIn the currency to spend
1804
- * @param currencyAmountOut the desired currency amount out
1805
- * @param nextAmountOut the exact amount of currency out
1806
- * @param maxNumResults maximum number of results to return
1807
- * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1808
- * @param currentPools used in recursion; the current list of pools
1809
- * @param bestTrades used in recursion; the current list of best trades
1810
- * @returns The exact out trade
1811
- */
1812
- static async bestTradeExactOut(pools, currencyIn, currencyAmountOut, { maxNumResults = 3, maxHops = 3 } = {}, currentPools = [], nextAmountOut = currencyAmountOut, bestTrades = []) {
1813
- invariant11(pools.length > 0, "POOLS");
1814
- invariant11(maxHops > 0, "MAX_HOPS");
1815
- invariant11(currencyAmountOut === nextAmountOut || currentPools.length > 0, "INVALID_RECURSION");
1816
- const amountOut = nextAmountOut.wrapped;
1817
- const tokenIn = currencyIn.wrapped;
1818
- for (let i = 0; i < pools.length; i++) {
1819
- const pool = pools[i];
1820
- if (!pool.token0.equals(amountOut.currency) && !pool.token1.equals(amountOut.currency))
1821
- continue;
1822
- let amountIn;
1823
- try {
1824
- const [result] = await pool.getInputAmount(amountOut);
1825
- amountIn = result;
1826
- } catch (error) {
1827
- if (error.isInsufficientReservesError) {
1828
- continue;
1829
- }
1830
- throw error;
1831
- }
1832
- if (amountIn.currency.equals(tokenIn)) {
1833
- sortedInsert(
1834
- bestTrades,
1835
- await Trade.fromRoute(
1836
- new Route([pool, ...currentPools], currencyIn, currencyAmountOut.currency),
1837
- currencyAmountOut,
1838
- TradeType.EXACT_OUTPUT
1839
- ),
1840
- maxNumResults,
1841
- tradeComparator
1842
- );
1843
- } else if (maxHops > 1 && pools.length > 1) {
1844
- const poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length));
1845
- await Trade.bestTradeExactOut(
1846
- poolsExcludingThisPool,
1847
- currencyIn,
1848
- currencyAmountOut,
1849
- {
1850
- maxNumResults,
1851
- maxHops: maxHops - 1
1852
- },
1853
- [pool, ...currentPools],
1854
- amountIn,
1855
- bestTrades
1856
- );
1857
- }
1858
- }
1859
- return bestTrades;
1844
+ return liquidity;
1845
+ }
1846
+ var FEE_BASE = 10n ** 4n;
1847
+ function parseProtocolFees(feeProtocol) {
1848
+ const packed = Number(feeProtocol);
1849
+ if (Number.isNaN(packed)) {
1850
+ throw new Error(`Invalid fee protocol ${feeProtocol}`);
1860
1851
  }
1861
- };
1852
+ const token0ProtocolFee = packed % 2 ** 16;
1853
+ const token1ProtocolFee = packed >> 16;
1854
+ return [new Percent(token0ProtocolFee, FEE_BASE), new Percent(token1ProtocolFee, FEE_BASE)];
1855
+ }
1856
+ function sqrtRatioX96ToPrice(sqrtRatioX96, currencyA, currencyB) {
1857
+ const ratioX192 = sqrtRatioX96 * sqrtRatioX96;
1858
+ return currencyA.wrapped.sortsBefore(currencyB.wrapped) ? new Price$1(currencyA.wrapped, currencyB.wrapped, Q192, ratioX192) : new Price$1(currencyA.wrapped, currencyB.wrapped, ratioX192, Q192);
1859
+ }
1862
1860
  var IMulticall = [
1863
1861
  {
1864
1862
  inputs: [
@@ -1890,14 +1888,14 @@ var _Multicall = class {
1890
1888
  if (!Array.isArray(calldatas)) {
1891
1889
  calldatas = [calldatas];
1892
1890
  }
1893
- return calldatas.length === 1 ? calldatas[0] : _Multicall.INTERFACE.encodeFunctionData("multicall", [calldatas]);
1891
+ return calldatas.length === 1 ? calldatas[0] : encodeFunctionData({ abi: _Multicall.ABI, functionName: "multicall", args: [calldatas] });
1894
1892
  }
1895
1893
  };
1896
1894
  var Multicall = _Multicall;
1897
- Multicall.INTERFACE = new Interface(IMulticall);
1895
+ Multicall.ABI = IMulticall;
1898
1896
 
1899
- // src/abi/NonfungiblePositionManager.json
1900
- var NonfungiblePositionManager_default = [
1897
+ // src/abi/NonfungiblePositionManager.ts
1898
+ var nonfungiblePositionManagerABI = [
1901
1899
  {
1902
1900
  inputs: [
1903
1901
  { internalType: "address", name: "_deployer", type: "address" },
@@ -2403,8 +2401,8 @@ var NonfungiblePositionManager_default = [
2403
2401
  { stateMutability: "payable", type: "receive" }
2404
2402
  ];
2405
2403
 
2406
- // src/abi/SelfPermit.json
2407
- var SelfPermit_default = [
2404
+ // src/abi/SelfPermit.ts
2405
+ var selfPermitABI = [
2408
2406
  {
2409
2407
  inputs: [
2410
2408
  {
@@ -2570,28 +2568,22 @@ var _SelfPermit = class {
2570
2568
  constructor() {
2571
2569
  }
2572
2570
  static encodePermit(token, options) {
2573
- return isAllowedPermit(options) ? _SelfPermit.INTERFACE.encodeFunctionData("selfPermitAllowed", [
2574
- token.address,
2575
- toHex(options.nonce),
2576
- toHex(options.expiry),
2577
- options.v,
2578
- options.r,
2579
- options.s
2580
- ]) : _SelfPermit.INTERFACE.encodeFunctionData("selfPermit", [
2581
- token.address,
2582
- toHex(options.amount),
2583
- toHex(options.deadline),
2584
- options.v,
2585
- options.r,
2586
- options.s
2587
- ]);
2571
+ return isAllowedPermit(options) ? encodeFunctionData({
2572
+ abi: _SelfPermit.ABI,
2573
+ functionName: "selfPermitAllowed",
2574
+ args: [token.address, BigInt(options.nonce), BigInt(options.expiry), options.v, options.r, options.s]
2575
+ }) : encodeFunctionData({
2576
+ abi: _SelfPermit.ABI,
2577
+ functionName: "selfPermit",
2578
+ args: [token.address, BigInt(options.amount), BigInt(options.deadline), options.v, options.r, options.s]
2579
+ });
2588
2580
  }
2589
2581
  };
2590
2582
  var SelfPermit = _SelfPermit;
2591
- SelfPermit.INTERFACE = new Interface(SelfPermit_default);
2583
+ SelfPermit.ABI = selfPermitABI;
2592
2584
 
2593
- // src/abi/IPeripheryPaymentsWithFee.json
2594
- var IPeripheryPaymentsWithFee_default = [
2585
+ // src/abi/PeripheryPaymentsWithFee.ts
2586
+ var peripheryPaymentsWithFeeABI = [
2595
2587
  {
2596
2588
  inputs: [],
2597
2589
  name: "refundETH",
@@ -2711,46 +2703,47 @@ var _Payments = class {
2711
2703
  constructor() {
2712
2704
  }
2713
2705
  static encodeFeeBips(fee) {
2714
- return toHex(fee.multiply(1e4).quotient);
2706
+ return fee.multiply(1e4).quotient;
2715
2707
  }
2716
2708
  static encodeUnwrapWETH9(amountMinimum, recipient, feeOptions) {
2717
2709
  recipient = validateAndParseAddress(recipient);
2718
2710
  if (feeOptions) {
2719
2711
  const feeBips = this.encodeFeeBips(feeOptions.fee);
2720
2712
  const feeRecipient = validateAndParseAddress(feeOptions.recipient);
2721
- return _Payments.INTERFACE.encodeFunctionData("unwrapWETH9WithFee", [
2722
- toHex(amountMinimum),
2723
- recipient,
2724
- feeBips,
2725
- feeRecipient
2726
- ]);
2713
+ return encodeFunctionData({
2714
+ abi: _Payments.ABI,
2715
+ functionName: "unwrapWETH9WithFee",
2716
+ args: [amountMinimum, recipient, feeBips, feeRecipient]
2717
+ });
2727
2718
  }
2728
- return _Payments.INTERFACE.encodeFunctionData("unwrapWETH9", [toHex(amountMinimum), recipient]);
2719
+ return encodeFunctionData({ abi: _Payments.ABI, functionName: "unwrapWETH9", args: [amountMinimum, recipient] });
2729
2720
  }
2730
2721
  static encodeSweepToken(token, amountMinimum, recipient, feeOptions) {
2731
2722
  recipient = validateAndParseAddress(recipient);
2732
2723
  if (feeOptions) {
2733
2724
  const feeBips = this.encodeFeeBips(feeOptions.fee);
2734
2725
  const feeRecipient = validateAndParseAddress(feeOptions.recipient);
2735
- return _Payments.INTERFACE.encodeFunctionData("sweepTokenWithFee", [
2736
- token.address,
2737
- toHex(amountMinimum),
2738
- recipient,
2739
- feeBips,
2740
- feeRecipient
2741
- ]);
2726
+ return encodeFunctionData({
2727
+ abi: _Payments.ABI,
2728
+ functionName: "sweepTokenWithFee",
2729
+ args: [token.address, amountMinimum, recipient, feeBips, feeRecipient]
2730
+ });
2742
2731
  }
2743
- return _Payments.INTERFACE.encodeFunctionData("sweepToken", [token.address, toHex(amountMinimum), recipient]);
2732
+ return encodeFunctionData({
2733
+ abi: _Payments.ABI,
2734
+ functionName: "sweepToken",
2735
+ args: [token.address, amountMinimum, recipient]
2736
+ });
2744
2737
  }
2745
2738
  static encodeRefundETH() {
2746
- return _Payments.INTERFACE.encodeFunctionData("refundETH");
2739
+ return encodeFunctionData({ abi: _Payments.ABI, functionName: "refundETH" });
2747
2740
  }
2748
2741
  };
2749
2742
  var Payments = _Payments;
2750
- Payments.INTERFACE = new Interface(IPeripheryPaymentsWithFee_default);
2743
+ Payments.ABI = peripheryPaymentsWithFeeABI;
2751
2744
 
2752
2745
  // src/nonfungiblePositionManager.ts
2753
- var MaxUint128 = toHex(JSBI4.subtract(JSBI4.exponentiate(JSBI4.BigInt(2), JSBI4.BigInt(128)), JSBI4.BigInt(1)));
2746
+ var MaxUint128 = 2n ** 128n - 1n;
2754
2747
  function isMint(options) {
2755
2748
  return Object.keys(options).some((k) => k === "recipient");
2756
2749
  }
@@ -2762,12 +2755,11 @@ var _NonfungiblePositionManager = class {
2762
2755
  constructor() {
2763
2756
  }
2764
2757
  static encodeCreate(pool) {
2765
- return _NonfungiblePositionManager.INTERFACE.encodeFunctionData("createAndInitializePoolIfNecessary", [
2766
- pool.token0.address,
2767
- pool.token1.address,
2768
- pool.fee,
2769
- toHex(pool.sqrtRatioX96)
2770
- ]);
2758
+ return encodeFunctionData({
2759
+ abi: _NonfungiblePositionManager.ABI,
2760
+ functionName: "createAndInitializePoolIfNecessary",
2761
+ args: [pool.token0.address, pool.token1.address, pool.fee, pool.sqrtRatioX96]
2762
+ });
2771
2763
  }
2772
2764
  static createCallParameters(pool) {
2773
2765
  return {
@@ -2776,13 +2768,13 @@ var _NonfungiblePositionManager = class {
2776
2768
  };
2777
2769
  }
2778
2770
  static addCallParameters(position, options) {
2779
- invariant11(JSBI4.greaterThan(position.liquidity, ZERO), "ZERO_LIQUIDITY");
2771
+ invariant9(position.liquidity > ZERO, "ZERO_LIQUIDITY");
2780
2772
  const calldatas = [];
2781
2773
  const { amount0: amount0Desired, amount1: amount1Desired } = position.mintAmounts;
2782
2774
  const minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
2783
- const amount0Min = toHex(minimumAmounts.amount0);
2784
- const amount1Min = toHex(minimumAmounts.amount1);
2785
- const deadline = toHex(options.deadline);
2775
+ const amount0Min = minimumAmounts.amount0;
2776
+ const amount1Min = minimumAmounts.amount1;
2777
+ const deadline = BigInt(options.deadline);
2786
2778
  if (isMint(options) && options.createPool) {
2787
2779
  calldatas.push(this.encodeCreate(position.pool));
2788
2780
  }
@@ -2795,42 +2787,50 @@ var _NonfungiblePositionManager = class {
2795
2787
  if (isMint(options)) {
2796
2788
  const recipient = validateAndParseAddress(options.recipient);
2797
2789
  calldatas.push(
2798
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("mint", [
2799
- {
2800
- token0: position.pool.token0.address,
2801
- token1: position.pool.token1.address,
2802
- fee: position.pool.fee,
2803
- tickLower: position.tickLower,
2804
- tickUpper: position.tickUpper,
2805
- amount0Desired: toHex(amount0Desired),
2806
- amount1Desired: toHex(amount1Desired),
2807
- amount0Min,
2808
- amount1Min,
2809
- recipient,
2810
- deadline
2811
- }
2812
- ])
2790
+ encodeFunctionData({
2791
+ abi: _NonfungiblePositionManager.ABI,
2792
+ functionName: "mint",
2793
+ args: [
2794
+ {
2795
+ token0: position.pool.token0.address,
2796
+ token1: position.pool.token1.address,
2797
+ fee: position.pool.fee,
2798
+ tickLower: position.tickLower,
2799
+ tickUpper: position.tickUpper,
2800
+ amount0Desired,
2801
+ amount1Desired,
2802
+ amount0Min,
2803
+ amount1Min,
2804
+ recipient,
2805
+ deadline
2806
+ }
2807
+ ]
2808
+ })
2813
2809
  );
2814
2810
  } else {
2815
2811
  calldatas.push(
2816
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("increaseLiquidity", [
2817
- {
2818
- tokenId: toHex(options.tokenId),
2819
- amount0Desired: toHex(amount0Desired),
2820
- amount1Desired: toHex(amount1Desired),
2821
- amount0Min,
2822
- amount1Min,
2823
- deadline
2824
- }
2825
- ])
2812
+ encodeFunctionData({
2813
+ abi: _NonfungiblePositionManager.ABI,
2814
+ functionName: "increaseLiquidity",
2815
+ args: [
2816
+ {
2817
+ tokenId: BigInt(options.tokenId),
2818
+ amount0Desired,
2819
+ amount1Desired,
2820
+ amount0Min,
2821
+ amount1Min,
2822
+ deadline
2823
+ }
2824
+ ]
2825
+ })
2826
2826
  );
2827
2827
  }
2828
2828
  let value = toHex(0);
2829
2829
  if (options.useNative) {
2830
2830
  const { wrapped } = options.useNative;
2831
- invariant11(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
2831
+ invariant9(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
2832
2832
  const wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired;
2833
- if (JSBI4.greaterThan(wrappedValue, ZERO)) {
2833
+ if (wrappedValue > ZERO) {
2834
2834
  calldatas.push(Payments.encodeRefundETH());
2835
2835
  }
2836
2836
  value = toHex(wrappedValue);
@@ -2842,18 +2842,22 @@ var _NonfungiblePositionManager = class {
2842
2842
  }
2843
2843
  static encodeCollect(options) {
2844
2844
  const calldatas = [];
2845
- const tokenId = toHex(options.tokenId);
2845
+ const tokenId = BigInt(options.tokenId);
2846
2846
  const involvesETH = options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative;
2847
2847
  const recipient = validateAndParseAddress(options.recipient);
2848
2848
  calldatas.push(
2849
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("collect", [
2850
- {
2851
- tokenId,
2852
- recipient: involvesETH ? ADDRESS_ZERO : recipient,
2853
- amount0Max: MaxUint128,
2854
- amount1Max: MaxUint128
2855
- }
2856
- ])
2849
+ encodeFunctionData({
2850
+ abi: _NonfungiblePositionManager.ABI,
2851
+ functionName: "collect",
2852
+ args: [
2853
+ {
2854
+ tokenId,
2855
+ recipient: involvesETH ? ADDRESS_ZERO : recipient,
2856
+ amount0Max: MaxUint128,
2857
+ amount1Max: MaxUint128
2858
+ }
2859
+ ]
2860
+ })
2857
2861
  );
2858
2862
  if (involvesETH) {
2859
2863
  const ethAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed0.quotient : options.expectedCurrencyOwed1.quotient;
@@ -2879,40 +2883,48 @@ var _NonfungiblePositionManager = class {
2879
2883
  */
2880
2884
  static removeCallParameters(position, options) {
2881
2885
  const calldatas = [];
2882
- const deadline = toHex(options.deadline);
2883
- const tokenId = toHex(options.tokenId);
2886
+ const deadline = BigInt(options.deadline);
2887
+ const tokenId = BigInt(options.tokenId);
2884
2888
  const partialPosition = new Position({
2885
2889
  pool: position.pool,
2886
2890
  liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
2887
2891
  tickLower: position.tickLower,
2888
2892
  tickUpper: position.tickUpper
2889
2893
  });
2890
- invariant11(JSBI4.greaterThan(partialPosition.liquidity, ZERO), "ZERO_LIQUIDITY");
2894
+ invariant9(partialPosition.liquidity > ZERO, "ZERO_LIQUIDITY");
2891
2895
  const { amount0: amount0Min, amount1: amount1Min } = partialPosition.burnAmountsWithSlippage(
2892
2896
  options.slippageTolerance
2893
2897
  );
2894
2898
  if (options.permit) {
2895
2899
  calldatas.push(
2896
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("permit", [
2897
- validateAndParseAddress(options.permit.spender),
2898
- tokenId,
2899
- toHex(options.permit.deadline),
2900
- options.permit.v,
2901
- options.permit.r,
2902
- options.permit.s
2903
- ])
2900
+ encodeFunctionData({
2901
+ abi: _NonfungiblePositionManager.ABI,
2902
+ functionName: "permit",
2903
+ args: [
2904
+ validateAndParseAddress(options.permit.spender),
2905
+ tokenId,
2906
+ BigInt(options.permit.deadline),
2907
+ options.permit.v,
2908
+ options.permit.r,
2909
+ options.permit.s
2910
+ ]
2911
+ })
2904
2912
  );
2905
2913
  }
2906
2914
  calldatas.push(
2907
- _NonfungiblePositionManager.INTERFACE.encodeFunctionData("decreaseLiquidity", [
2908
- {
2909
- tokenId,
2910
- liquidity: toHex(partialPosition.liquidity),
2911
- amount0Min: toHex(amount0Min),
2912
- amount1Min: toHex(amount1Min),
2913
- deadline
2914
- }
2915
- ])
2915
+ encodeFunctionData({
2916
+ abi: _NonfungiblePositionManager.ABI,
2917
+ functionName: "decreaseLiquidity",
2918
+ args: [
2919
+ {
2920
+ tokenId,
2921
+ liquidity: partialPosition.liquidity,
2922
+ amount0Min,
2923
+ amount1Min,
2924
+ deadline
2925
+ }
2926
+ ]
2927
+ })
2916
2928
  );
2917
2929
  const { expectedCurrencyOwed0, expectedCurrencyOwed1, ...rest } = options.collectOptions;
2918
2930
  calldatas.push(
@@ -2930,10 +2942,12 @@ var _NonfungiblePositionManager = class {
2930
2942
  );
2931
2943
  if (options.liquidityPercentage.equalTo(ONE)) {
2932
2944
  if (options.burnToken) {
2933
- calldatas.push(_NonfungiblePositionManager.INTERFACE.encodeFunctionData("burn", [tokenId]));
2945
+ calldatas.push(
2946
+ encodeFunctionData({ abi: _NonfungiblePositionManager.ABI, functionName: "burn", args: [tokenId] })
2947
+ );
2934
2948
  }
2935
2949
  } else {
2936
- invariant11(options.burnToken !== true, "CANNOT_BURN");
2950
+ invariant9(options.burnToken !== true, "CANNOT_BURN");
2937
2951
  }
2938
2952
  return {
2939
2953
  calldata: Multicall.encodeMulticall(calldatas),
@@ -2945,16 +2959,17 @@ var _NonfungiblePositionManager = class {
2945
2959
  const sender = validateAndParseAddress(options.sender);
2946
2960
  let calldata;
2947
2961
  if (options.data) {
2948
- calldata = _NonfungiblePositionManager.INTERFACE.encodeFunctionData(
2949
- "safeTransferFrom(address,address,uint256,bytes)",
2950
- [sender, recipient, toHex(options.tokenId), options.data]
2951
- );
2962
+ calldata = encodeFunctionData({
2963
+ abi: _NonfungiblePositionManager.ABI,
2964
+ functionName: "safeTransferFrom",
2965
+ args: [sender, recipient, BigInt(options.tokenId), options.data]
2966
+ });
2952
2967
  } else {
2953
- calldata = _NonfungiblePositionManager.INTERFACE.encodeFunctionData("safeTransferFrom(address,address,uint256)", [
2954
- sender,
2955
- recipient,
2956
- toHex(options.tokenId)
2957
- ]);
2968
+ calldata = encodeFunctionData({
2969
+ abi: _NonfungiblePositionManager.ABI,
2970
+ functionName: "safeTransferFrom",
2971
+ args: [sender, recipient, BigInt(options.tokenId)]
2972
+ });
2958
2973
  }
2959
2974
  return {
2960
2975
  calldata,
@@ -2963,10 +2978,10 @@ var _NonfungiblePositionManager = class {
2963
2978
  }
2964
2979
  };
2965
2980
  var NonfungiblePositionManager = _NonfungiblePositionManager;
2966
- NonfungiblePositionManager.INTERFACE = new Interface(NonfungiblePositionManager_default);
2981
+ NonfungiblePositionManager.ABI = nonfungiblePositionManagerABI;
2967
2982
 
2968
- // src/abi/Quoter.json
2969
- var Quoter_default = [
2983
+ // src/abi/Quoter.ts
2984
+ var quoterABI = [
2970
2985
  {
2971
2986
  inputs: [
2972
2987
  {
@@ -3178,8 +3193,8 @@ var Quoter_default = [
3178
3193
  }
3179
3194
  ];
3180
3195
 
3181
- // src/abi/QuoterV2.json
3182
- var QuoterV2_default = [
3196
+ // src/abi/QuoterV2.ts
3197
+ var quoterV2ABI = [
3183
3198
  {
3184
3199
  inputs: [
3185
3200
  {
@@ -3479,21 +3494,20 @@ var SwapQuoter = class {
3479
3494
  * @returns The formatted calldata
3480
3495
  */
3481
3496
  static quoteCallParameters(route, amount, tradeType, options = {}) {
3482
- var _a;
3483
3497
  const singleHop = route.pools.length === 1;
3484
- const quoteAmount = toHex(amount.quotient);
3498
+ const quoteAmount = amount.quotient;
3485
3499
  let calldata;
3486
- const swapInterface = options.useQuoterV2 ? this.V2INTERFACE : this.V1INTERFACE;
3500
+ const swapAbi = options.useQuoterV2 ? this.V2ABI : this.V1ABI;
3487
3501
  if (singleHop) {
3488
3502
  const baseQuoteParams = {
3489
3503
  tokenIn: route.tokenPath[0].address,
3490
3504
  tokenOut: route.tokenPath[1].address,
3491
3505
  fee: route.pools[0].fee,
3492
- sqrtPriceLimitX96: toHex((_a = options == null ? void 0 : options.sqrtPriceLimitX96) != null ? _a : 0)
3506
+ sqrtPriceLimitX96: BigInt(options?.sqrtPriceLimitX96 ?? 0)
3493
3507
  };
3494
3508
  const v2QuoteParams = {
3495
3509
  ...baseQuoteParams,
3496
- ...tradeType == TradeType.EXACT_INPUT ? { amountIn: quoteAmount } : { amount: quoteAmount }
3510
+ ...tradeType === TradeType$1.EXACT_INPUT ? { amountIn: quoteAmount } : { amount: quoteAmount }
3497
3511
  };
3498
3512
  const v1QuoteParams = [
3499
3513
  baseQuoteParams.tokenIn,
@@ -3502,16 +3516,31 @@ var SwapQuoter = class {
3502
3516
  quoteAmount,
3503
3517
  baseQuoteParams.sqrtPriceLimitX96
3504
3518
  ];
3505
- const tradeTypeFunctionName = tradeType === TradeType.EXACT_INPUT ? "quoteExactInputSingle" : "quoteExactOutputSingle";
3506
- calldata = swapInterface.encodeFunctionData(
3507
- tradeTypeFunctionName,
3508
- options.useQuoterV2 ? [v2QuoteParams] : v1QuoteParams
3509
- );
3519
+ const tradeTypeFunctionName = tradeType === TradeType$1.EXACT_INPUT ? "quoteExactInputSingle" : "quoteExactOutputSingle";
3520
+ if (options.useQuoterV2) {
3521
+ calldata = encodeFunctionData({
3522
+ abi: this.V2ABI,
3523
+ functionName: tradeTypeFunctionName,
3524
+ // @ts-ignore // FIXME
3525
+ args: [v2QuoteParams]
3526
+ });
3527
+ } else {
3528
+ calldata = encodeFunctionData({
3529
+ abi: this.V1ABI,
3530
+ functionName: tradeTypeFunctionName,
3531
+ args: v1QuoteParams
3532
+ });
3533
+ }
3510
3534
  } else {
3511
- invariant11((options == null ? void 0 : options.sqrtPriceLimitX96) === void 0, "MULTIHOP_PRICE_LIMIT");
3512
- const path = encodeRouteToPath(route, tradeType === TradeType.EXACT_OUTPUT);
3513
- const tradeTypeFunctionName = tradeType === TradeType.EXACT_INPUT ? "quoteExactInput" : "quoteExactOutput";
3514
- calldata = swapInterface.encodeFunctionData(tradeTypeFunctionName, [path, quoteAmount]);
3535
+ invariant9(options?.sqrtPriceLimitX96 === void 0, "MULTIHOP_PRICE_LIMIT");
3536
+ const path = encodeRouteToPath(route, tradeType === TradeType$1.EXACT_OUTPUT);
3537
+ const tradeTypeFunctionName = tradeType === TradeType$1.EXACT_INPUT ? "quoteExactInput" : "quoteExactOutput";
3538
+ calldata = encodeFunctionData({
3539
+ // @ts-ignore
3540
+ abi: swapAbi,
3541
+ functionName: tradeTypeFunctionName,
3542
+ args: [path, quoteAmount]
3543
+ });
3515
3544
  }
3516
3545
  return {
3517
3546
  calldata,
@@ -3519,11 +3548,11 @@ var SwapQuoter = class {
3519
3548
  };
3520
3549
  }
3521
3550
  };
3522
- SwapQuoter.V1INTERFACE = new Interface(Quoter_default);
3523
- SwapQuoter.V2INTERFACE = new Interface(QuoterV2_default);
3551
+ SwapQuoter.V1ABI = quoterABI;
3552
+ SwapQuoter.V2ABI = quoterV2ABI;
3524
3553
 
3525
- // src/abi/V3Staker.json
3526
- var V3Staker_default = [
3554
+ // src/abi/V3Staker.ts
3555
+ var v3StakerABI = [
3527
3556
  {
3528
3557
  inputs: [
3529
3558
  {
@@ -4241,18 +4270,22 @@ var _Staker = class {
4241
4270
  * @returns The calldatas for 'unstakeToken' and 'claimReward'.
4242
4271
  */
4243
4272
  static encodeClaim(incentiveKey, options) {
4244
- var _a;
4245
4273
  const calldatas = [];
4246
4274
  calldatas.push(
4247
- _Staker.INTERFACE.encodeFunctionData("unstakeToken", [
4248
- this._encodeIncentiveKey(incentiveKey),
4249
- toHex(options.tokenId)
4250
- ])
4275
+ encodeFunctionData({
4276
+ abi: _Staker.ABI,
4277
+ functionName: "unstakeToken",
4278
+ args: [this._encodeIncentiveKey(incentiveKey), BigInt(options.tokenId)]
4279
+ })
4251
4280
  );
4252
4281
  const recipient = validateAndParseAddress(options.recipient);
4253
- const amount = (_a = options.amount) != null ? _a : 0;
4282
+ const amount = options.amount ?? 0;
4254
4283
  calldatas.push(
4255
- _Staker.INTERFACE.encodeFunctionData("claimReward", [incentiveKey.rewardToken.address, recipient, toHex(amount)])
4284
+ encodeFunctionData({
4285
+ abi: _Staker.ABI,
4286
+ functionName: "claimReward",
4287
+ args: [incentiveKey.rewardToken.address, recipient, BigInt(amount)]
4288
+ })
4256
4289
  );
4257
4290
  return calldatas;
4258
4291
  }
@@ -4272,10 +4305,11 @@ var _Staker = class {
4272
4305
  const incentiveKey = incentiveKeys[i];
4273
4306
  calldatas = calldatas.concat(this.encodeClaim(incentiveKey, options));
4274
4307
  calldatas.push(
4275
- _Staker.INTERFACE.encodeFunctionData("stakeToken", [
4276
- this._encodeIncentiveKey(incentiveKey),
4277
- toHex(options.tokenId)
4278
- ])
4308
+ encodeFunctionData({
4309
+ abi: _Staker.ABI,
4310
+ functionName: "stakeToken",
4311
+ args: [this._encodeIncentiveKey(incentiveKey), BigInt(options.tokenId)]
4312
+ })
4279
4313
  );
4280
4314
  }
4281
4315
  return {
@@ -4303,11 +4337,11 @@ var _Staker = class {
4303
4337
  }
4304
4338
  const owner = validateAndParseAddress(withdrawOptions.owner);
4305
4339
  calldatas.push(
4306
- _Staker.INTERFACE.encodeFunctionData("withdrawToken", [
4307
- toHex(withdrawOptions.tokenId),
4308
- owner,
4309
- withdrawOptions.data ? withdrawOptions.data : toHex(0)
4310
- ])
4340
+ encodeFunctionData({
4341
+ abi: _Staker.ABI,
4342
+ functionName: "withdrawToken",
4343
+ args: [BigInt(withdrawOptions.tokenId), owner, toHex(0)]
4344
+ })
4311
4345
  );
4312
4346
  return {
4313
4347
  calldata: Multicall.encodeMulticall(calldatas),
@@ -4328,16 +4362,18 @@ var _Staker = class {
4328
4362
  const incentiveKey = incentiveKeys[i];
4329
4363
  keys.push(this._encodeIncentiveKey(incentiveKey));
4330
4364
  }
4331
- data = defaultAbiCoder.encode([`${_Staker.INCENTIVE_KEY_ABI}[]`], [keys]);
4365
+ data = encodeAbiParameters(parseAbiParameters([`${_Staker.INCENTIVE_KEY_ABI}[]`]), [keys]);
4332
4366
  } else {
4333
- data = defaultAbiCoder.encode([_Staker.INCENTIVE_KEY_ABI], [this._encodeIncentiveKey(incentiveKeys[0])]);
4367
+ data = encodeAbiParameters(parseAbiParameters(_Staker.INCENTIVE_KEY_ABI), [
4368
+ this._encodeIncentiveKey(incentiveKeys[0])
4369
+ ]);
4334
4370
  }
4335
4371
  return data;
4336
4372
  }
4337
4373
  /**
4338
4374
  *
4339
4375
  * @param incentiveKey An `IncentiveKey` which represents a unique staking program.
4340
- * @returns An encoded IncentiveKey to be read by ethers
4376
+ * @returns An encoded IncentiveKey to be read by viem
4341
4377
  */
4342
4378
  static _encodeIncentiveKey(incentiveKey) {
4343
4379
  const { token0, token1, fee } = incentiveKey.pool;
@@ -4345,18 +4381,18 @@ var _Staker = class {
4345
4381
  return {
4346
4382
  rewardToken: incentiveKey.rewardToken.address,
4347
4383
  pool: Pool.getAddress(token0, token1, fee),
4348
- startTime: toHex(incentiveKey.startTime),
4349
- endTime: toHex(incentiveKey.endTime),
4384
+ startTime: BigInt(incentiveKey.startTime),
4385
+ endTime: BigInt(incentiveKey.endTime),
4350
4386
  refundee
4351
4387
  };
4352
4388
  }
4353
4389
  };
4354
4390
  var Staker = _Staker;
4355
- Staker.INTERFACE = new Interface(V3Staker_default);
4391
+ Staker.ABI = v3StakerABI;
4356
4392
  Staker.INCENTIVE_KEY_ABI = "tuple(address rewardToken, address pool, uint256 startTime, uint256 endTime, address refundee)";
4357
4393
 
4358
- // src/abi/SwapRouter.json
4359
- var SwapRouter_default = [
4394
+ // src/abi/SwapRouter.ts
4395
+ var swapRouterABI = [
4360
4396
  {
4361
4397
  inputs: [
4362
4398
  {
@@ -4953,18 +4989,17 @@ var _SwapRouter = class {
4953
4989
  * @param options options for the call parameters
4954
4990
  */
4955
4991
  static swapCallParameters(trades, options) {
4956
- var _a, _b;
4957
4992
  if (!Array.isArray(trades)) {
4958
4993
  trades = [trades];
4959
4994
  }
4960
4995
  const sampleTrade = trades[0];
4961
4996
  const tokenIn = sampleTrade.inputAmount.currency.wrapped;
4962
4997
  const tokenOut = sampleTrade.outputAmount.currency.wrapped;
4963
- invariant11(
4998
+ invariant9(
4964
4999
  trades.every((trade) => trade.inputAmount.currency.wrapped.equals(tokenIn)),
4965
5000
  "TOKEN_IN_DIFF"
4966
5001
  );
4967
- invariant11(
5002
+ invariant9(
4968
5003
  trades.every((trade) => trade.outputAmount.currency.wrapped.equals(tokenOut)),
4969
5004
  "TOKEN_OUT_DIFF"
4970
5005
  );
@@ -4981,15 +5016,15 @@ var _SwapRouter = class {
4981
5016
  const routerMustCustody = outputIsNative || !!options.fee;
4982
5017
  const totalValue = inputIsNative ? trades.reduce((sum, trade) => sum.add(trade.maximumAmountIn(options.slippageTolerance)), ZERO_IN) : ZERO_IN;
4983
5018
  if (options.inputTokenPermit) {
4984
- invariant11(sampleTrade.inputAmount.currency.isToken, "NON_TOKEN_PERMIT");
5019
+ invariant9(sampleTrade.inputAmount.currency.isToken, "NON_TOKEN_PERMIT");
4985
5020
  calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency, options.inputTokenPermit));
4986
5021
  }
4987
5022
  const recipient = validateAndParseAddress(options.recipient);
4988
- const deadline = toHex(options.deadline);
5023
+ const deadline = BigInt(options.deadline);
4989
5024
  for (const trade of trades) {
4990
5025
  for (const { route, inputAmount, outputAmount } of trade.swaps) {
4991
- const amountIn = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
4992
- const amountOut = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient);
5026
+ const amountIn = BigInt(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
5027
+ const amountOut = BigInt(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient);
4993
5028
  const singleHop = route.pools.length === 1;
4994
5029
  if (singleHop) {
4995
5030
  if (trade.tradeType === TradeType.EXACT_INPUT) {
@@ -5001,9 +5036,15 @@ var _SwapRouter = class {
5001
5036
  deadline,
5002
5037
  amountIn,
5003
5038
  amountOutMinimum: amountOut,
5004
- sqrtPriceLimitX96: toHex((_a = options.sqrtPriceLimitX96) != null ? _a : 0)
5039
+ sqrtPriceLimitX96: BigInt(options.sqrtPriceLimitX96 ?? 0)
5005
5040
  };
5006
- calldatas.push(_SwapRouter.INTERFACE.encodeFunctionData("exactInputSingle", [exactInputSingleParams]));
5041
+ calldatas.push(
5042
+ encodeFunctionData({
5043
+ abi: _SwapRouter.ABI,
5044
+ functionName: "exactInputSingle",
5045
+ args: [exactInputSingleParams]
5046
+ })
5047
+ );
5007
5048
  } else {
5008
5049
  const exactOutputSingleParams = {
5009
5050
  tokenIn: route.tokenPath[0].address,
@@ -5013,12 +5054,18 @@ var _SwapRouter = class {
5013
5054
  deadline,
5014
5055
  amountOut,
5015
5056
  amountInMaximum: amountIn,
5016
- sqrtPriceLimitX96: toHex((_b = options.sqrtPriceLimitX96) != null ? _b : 0)
5057
+ sqrtPriceLimitX96: BigInt(options.sqrtPriceLimitX96 ?? 0)
5017
5058
  };
5018
- calldatas.push(_SwapRouter.INTERFACE.encodeFunctionData("exactOutputSingle", [exactOutputSingleParams]));
5059
+ calldatas.push(
5060
+ encodeFunctionData({
5061
+ abi: _SwapRouter.ABI,
5062
+ functionName: "exactOutputSingle",
5063
+ args: [exactOutputSingleParams]
5064
+ })
5065
+ );
5019
5066
  }
5020
5067
  } else {
5021
- invariant11(options.sqrtPriceLimitX96 === void 0, "MULTIHOP_PRICE_LIMIT");
5068
+ invariant9(options.sqrtPriceLimitX96 === void 0, "MULTIHOP_PRICE_LIMIT");
5022
5069
  const path = encodeRouteToPath(route, trade.tradeType === TradeType.EXACT_OUTPUT);
5023
5070
  if (trade.tradeType === TradeType.EXACT_INPUT) {
5024
5071
  const exactInputParams = {
@@ -5028,7 +5075,9 @@ var _SwapRouter = class {
5028
5075
  amountIn,
5029
5076
  amountOutMinimum: amountOut
5030
5077
  };
5031
- calldatas.push(_SwapRouter.INTERFACE.encodeFunctionData("exactInput", [exactInputParams]));
5078
+ calldatas.push(
5079
+ encodeFunctionData({ abi: _SwapRouter.ABI, functionName: "exactInput", args: [exactInputParams] })
5080
+ );
5032
5081
  } else {
5033
5082
  const exactOutputParams = {
5034
5083
  path,
@@ -5037,7 +5086,9 @@ var _SwapRouter = class {
5037
5086
  amountOut,
5038
5087
  amountInMaximum: amountIn
5039
5088
  };
5040
- calldatas.push(_SwapRouter.INTERFACE.encodeFunctionData("exactOutput", [exactOutputParams]));
5089
+ calldatas.push(
5090
+ encodeFunctionData({ abi: _SwapRouter.ABI, functionName: "exactOutput", args: [exactOutputParams] })
5091
+ );
5041
5092
  }
5042
5093
  }
5043
5094
  }
@@ -5070,10 +5121,11 @@ var _SwapRouter = class {
5070
5121
  }
5071
5122
  };
5072
5123
  var SwapRouter = _SwapRouter;
5073
- SwapRouter.INTERFACE = new Interface(SwapRouter_default);
5124
+ // public static INTERFACE: Interface = new Interface(ISwapRouter)
5125
+ SwapRouter.ABI = swapRouterABI;
5074
5126
 
5075
- // src/abi/MasterChefV3.json
5076
- var MasterChefV3_default = [
5127
+ // src/abi/MasterChefV3.ts
5128
+ var masterChefV3ABI = [
5077
5129
  {
5078
5130
  inputs: [
5079
5131
  { internalType: "contract IERC20", name: "_CAKE", type: "address" },
@@ -5761,14 +5813,14 @@ var _MasterChefV3 = class {
5761
5813
  // Copy from NonfungiblePositionManager
5762
5814
  // Only support increaseLiquidity
5763
5815
  static addCallParameters(position, options) {
5764
- invariant11(JSBI4.greaterThan(position.liquidity, ZERO$1), "ZERO_LIQUIDITY");
5816
+ invariant9(position.liquidity > ZERO$2, "ZERO_LIQUIDITY");
5765
5817
  const calldatas = [];
5766
5818
  const { amount0: amount0Desired, amount1: amount1Desired } = position.mintAmounts;
5767
5819
  const minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
5768
- const amount0Min = toHex(minimumAmounts.amount0);
5769
- const amount1Min = toHex(minimumAmounts.amount1);
5770
- const deadline = toHex(options.deadline);
5771
- invariant11(!isMint(options), "NO_MINT_SUPPORT");
5820
+ const amount0Min = BigInt(minimumAmounts.amount0);
5821
+ const amount1Min = BigInt(minimumAmounts.amount1);
5822
+ const deadline = BigInt(options.deadline);
5823
+ invariant9(!isMint(options), "NO_MINT_SUPPORT");
5772
5824
  if (options.token0Permit) {
5773
5825
  calldatas.push(SelfPermit.encodePermit(position.pool.token0, options.token0Permit));
5774
5826
  }
@@ -5776,21 +5828,25 @@ var _MasterChefV3 = class {
5776
5828
  calldatas.push(SelfPermit.encodePermit(position.pool.token1, options.token1Permit));
5777
5829
  }
5778
5830
  calldatas.push(
5779
- _MasterChefV3.INTERFACE.encodeFunctionData("increaseLiquidity", [
5780
- {
5781
- tokenId: toHex(options.tokenId),
5782
- amount0Desired: toHex(amount0Desired),
5783
- amount1Desired: toHex(amount1Desired),
5784
- amount0Min,
5785
- amount1Min,
5786
- deadline
5787
- }
5788
- ])
5831
+ encodeFunctionData({
5832
+ abi: _MasterChefV3.ABI,
5833
+ functionName: "increaseLiquidity",
5834
+ args: [
5835
+ {
5836
+ tokenId: BigInt(options.tokenId),
5837
+ amount0Desired,
5838
+ amount1Desired,
5839
+ amount0Min,
5840
+ amount1Min,
5841
+ deadline
5842
+ }
5843
+ ]
5844
+ })
5789
5845
  );
5790
5846
  let value = toHex(0);
5791
5847
  if (options.useNative) {
5792
5848
  const { wrapped } = options.useNative;
5793
- invariant11(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
5849
+ invariant9(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped), "NO_WETH");
5794
5850
  const wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired;
5795
5851
  value = toHex(wrappedValue);
5796
5852
  }
@@ -5802,18 +5858,22 @@ var _MasterChefV3 = class {
5802
5858
  // Copy from NonfungiblePositionManager
5803
5859
  static encodeCollect(options) {
5804
5860
  const calldatas = [];
5805
- const tokenId = toHex(options.tokenId);
5861
+ const tokenId = BigInt(options.tokenId);
5806
5862
  const involvesETH = options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative;
5807
5863
  const recipient = validateAndParseAddress(options.recipient);
5808
5864
  calldatas.push(
5809
- _MasterChefV3.INTERFACE.encodeFunctionData("collect", [
5810
- {
5811
- tokenId,
5812
- recipient: involvesETH ? ADDRESS_ZERO : recipient,
5813
- amount0Max: MaxUint128,
5814
- amount1Max: MaxUint128
5815
- }
5816
- ])
5865
+ encodeFunctionData({
5866
+ abi: _MasterChefV3.ABI,
5867
+ functionName: "collect",
5868
+ args: [
5869
+ {
5870
+ tokenId,
5871
+ recipient: involvesETH ? ADDRESS_ZERO : recipient,
5872
+ amount0Max: MaxUint128,
5873
+ amount1Max: MaxUint128
5874
+ }
5875
+ ]
5876
+ })
5817
5877
  );
5818
5878
  if (involvesETH) {
5819
5879
  const ethAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed0.quotient : options.expectedCurrencyOwed1.quotient;
@@ -5833,40 +5893,35 @@ var _MasterChefV3 = class {
5833
5893
  }
5834
5894
  static removeCallParameters(position, options) {
5835
5895
  const calldatas = [];
5836
- const deadline = toHex(options.deadline);
5837
- const tokenId = toHex(options.tokenId);
5896
+ const deadline = BigInt(options.deadline);
5897
+ const tokenId = BigInt(options.tokenId);
5838
5898
  const partialPosition = new Position({
5839
5899
  pool: position.pool,
5840
5900
  liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
5841
5901
  tickLower: position.tickLower,
5842
5902
  tickUpper: position.tickUpper
5843
5903
  });
5844
- invariant11(JSBI4.greaterThan(partialPosition.liquidity, ZERO$1), "ZERO_LIQUIDITY");
5904
+ invariant9(partialPosition.liquidity > ZERO$2, "ZERO_LIQUIDITY");
5845
5905
  const { amount0: amount0Min, amount1: amount1Min } = partialPosition.burnAmountsWithSlippage(
5846
5906
  options.slippageTolerance
5847
5907
  );
5848
5908
  if (options.permit) {
5849
- calldatas.push(
5850
- _MasterChefV3.INTERFACE.encodeFunctionData("permit", [
5851
- validateAndParseAddress(options.permit.spender),
5852
- tokenId,
5853
- toHex(options.permit.deadline),
5854
- options.permit.v,
5855
- options.permit.r,
5856
- options.permit.s
5857
- ])
5858
- );
5909
+ throw new Error("NOT_IMPLEMENTED");
5859
5910
  }
5860
5911
  calldatas.push(
5861
- _MasterChefV3.INTERFACE.encodeFunctionData("decreaseLiquidity", [
5862
- {
5863
- tokenId,
5864
- liquidity: toHex(partialPosition.liquidity),
5865
- amount0Min: toHex(amount0Min),
5866
- amount1Min: toHex(amount1Min),
5867
- deadline
5868
- }
5869
- ])
5912
+ encodeFunctionData({
5913
+ abi: _MasterChefV3.ABI,
5914
+ functionName: "decreaseLiquidity",
5915
+ args: [
5916
+ {
5917
+ tokenId,
5918
+ liquidity: partialPosition.liquidity,
5919
+ amount0Min,
5920
+ amount1Min,
5921
+ deadline
5922
+ }
5923
+ ]
5924
+ })
5870
5925
  );
5871
5926
  const { expectedCurrencyOwed0, expectedCurrencyOwed1, ...rest } = options.collectOptions;
5872
5927
  calldatas.push(
@@ -5882,29 +5937,31 @@ var _MasterChefV3 = class {
5882
5937
  ...rest
5883
5938
  })
5884
5939
  );
5885
- if (rest == null ? void 0 : rest.recipient) {
5940
+ if (rest?.recipient) {
5886
5941
  if (options.liquidityPercentage.equalTo(ONE$1)) {
5887
5942
  calldatas.push(
5888
- _MasterChefV3.INTERFACE.encodeFunctionData("withdraw", [
5889
- tokenId.toString(),
5890
- validateAndParseAddress(rest == null ? void 0 : rest.recipient)
5891
- ])
5943
+ encodeFunctionData({
5944
+ abi: _MasterChefV3.ABI,
5945
+ functionName: "withdraw",
5946
+ args: [tokenId, validateAndParseAddress(rest?.recipient)]
5947
+ })
5892
5948
  );
5893
5949
  } else {
5894
5950
  calldatas.push(
5895
- _MasterChefV3.INTERFACE.encodeFunctionData("harvest", [
5896
- tokenId.toString(),
5897
- validateAndParseAddress(rest == null ? void 0 : rest.recipient)
5898
- ])
5951
+ encodeFunctionData({
5952
+ abi: _MasterChefV3.ABI,
5953
+ functionName: "harvest",
5954
+ args: [tokenId, validateAndParseAddress(rest?.recipient)]
5955
+ })
5899
5956
  );
5900
5957
  }
5901
5958
  }
5902
5959
  if (options.liquidityPercentage.equalTo(ONE$1)) {
5903
5960
  if (options.burnToken) {
5904
- calldatas.push(_MasterChefV3.INTERFACE.encodeFunctionData("burn", [tokenId]));
5961
+ calldatas.push(encodeFunctionData({ abi: _MasterChefV3.ABI, functionName: "burn", args: [tokenId] }));
5905
5962
  }
5906
5963
  } else {
5907
- invariant11(options.burnToken !== true, "CANNOT_BURN");
5964
+ invariant9(options.burnToken !== true, "CANNOT_BURN");
5908
5965
  }
5909
5966
  return {
5910
5967
  calldata: Multicall.encodeMulticall(calldatas),
@@ -5930,7 +5987,11 @@ var _MasterChefV3 = class {
5930
5987
  const { tokenId, to } = options;
5931
5988
  const calldatas = [];
5932
5989
  calldatas.push(
5933
- _MasterChefV3.INTERFACE.encodeFunctionData("harvest", [tokenId.toString(), validateAndParseAddress(to)])
5990
+ encodeFunctionData({
5991
+ abi: _MasterChefV3.ABI,
5992
+ functionName: "harvest",
5993
+ args: [BigInt(tokenId), validateAndParseAddress(to)]
5994
+ })
5934
5995
  );
5935
5996
  return calldatas;
5936
5997
  }
@@ -5938,7 +5999,11 @@ var _MasterChefV3 = class {
5938
5999
  const { tokenId, to } = options;
5939
6000
  const calldatas = [];
5940
6001
  calldatas.push(
5941
- _MasterChefV3.INTERFACE.encodeFunctionData("withdraw", [tokenId.toString(), validateAndParseAddress(to)])
6002
+ encodeFunctionData({
6003
+ abi: _MasterChefV3.ABI,
6004
+ functionName: "withdraw",
6005
+ args: [BigInt(tokenId), validateAndParseAddress(to)]
6006
+ })
5942
6007
  );
5943
6008
  return {
5944
6009
  calldata: Multicall.encodeMulticall(calldatas),
@@ -5947,6 +6012,6 @@ var _MasterChefV3 = class {
5947
6012
  }
5948
6013
  };
5949
6014
  var MasterChefV3 = _MasterChefV3;
5950
- MasterChefV3.INTERFACE = new Interface(MasterChefV3_default);
6015
+ MasterChefV3.ABI = masterChefV3ABI;
5951
6016
 
5952
- export { ADDRESS_ZERO, DEPLOYER_ADDRESS, DEPLOYER_ADDRESSES, FACTORY_ADDRESS, FeeAmount, FeeCalculator, FullMath, LiquidityMath, MasterChefV3, MaxUint128, Multicall, NoTickDataProvider, NonfungiblePositionManager, POOL_INIT_CODE_HASH, Payments, Pool, Position, PositionLibrary, PositionMath, Route, SelfPermit, SqrtPriceMath, Staker, SwapMath, SwapQuoter, SwapRouter, TICK_SPACINGS, Tick, TickLibrary, TickList, TickListDataProvider, TickMath, Trade, computePoolAddress, encodeRouteToPath, encodeSqrtRatioX96, getAmountsAtNewPrice, getAmountsByLiquidityAndPrice, getAverageLiquidity, getDependentAmount, getEstimatedLPFee, getEstimatedLPFeeWithProtocolFee, getLiquidityByAmountsAndPrice, getLiquidityBySingleAmount, getLiquidityFromSqrtRatioX96, getLiquidityFromTick, isMint, isSorted, maxLiquidityForAmounts, mostSignificantBit, nearestUsableTick, parseProtocolFees, priceToClosestTick, subIn256, tickToPrice, toHex, tradeComparator };
6017
+ export { ADDRESS_ZERO, DEPLOYER_ADDRESS, DEPLOYER_ADDRESSES, FACTORY_ADDRESS, FeeAmount, FeeCalculator, FullMath, LiquidityMath, MasterChefV3, MaxUint128, Multicall, NoTickDataProvider, NonfungiblePositionManager, POOL_INIT_CODE_HASH, Payments, Pool, Position, PositionLibrary, PositionMath, Route, SelfPermit, SqrtPriceMath, Staker, SwapMath, SwapQuoter, SwapRouter, TICK_SPACINGS, Tick, TickLibrary, TickList, TickListDataProvider, TickMath, Trade, computePoolAddress, encodeRouteToPath, encodeSqrtRatioX96, getAmountsAtNewPrice, getAmountsByLiquidityAndPrice, getAverageLiquidity, getDependentAmount, getEstimatedLPFee, getEstimatedLPFeeByAmounts, getEstimatedLPFeeByAmountsWithProtocolFee, getEstimatedLPFeeWithProtocolFee, getLiquidityByAmountsAndPrice, getLiquidityBySingleAmount, getLiquidityFromSqrtRatioX96, getLiquidityFromTick, isMint, isSorted, masterChefV3ABI, maxLiquidityForAmounts, mostSignificantBit, nearestUsableTick, nonfungiblePositionManagerABI, parseProtocolFees, peripheryPaymentsWithFeeABI, priceToClosestTick, quoterABI, quoterV2ABI, selfPermitABI, sqrtRatioX96ToPrice, subIn256, swapRouterABI, tickToPrice, toHex, tradeComparator, v3StakerABI };