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