@juiceswapxyz/v3-sdk 0.0.1-beta.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 (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -0
  3. package/dist/constants.d.ts +23 -0
  4. package/dist/entities/index.d.ts +7 -0
  5. package/dist/entities/pool.d.ts +81 -0
  6. package/dist/entities/position.d.ts +131 -0
  7. package/dist/entities/route.d.ts +26 -0
  8. package/dist/entities/tick.d.ts +13 -0
  9. package/dist/entities/tickDataProvider.d.ts +31 -0
  10. package/dist/entities/tickListDataProvider.d.ts +15 -0
  11. package/dist/entities/trade.d.ts +220 -0
  12. package/dist/index.d.ts +10 -0
  13. package/dist/index.js +8 -0
  14. package/dist/internalConstants.d.ts +6 -0
  15. package/dist/multicall.d.ts +10 -0
  16. package/dist/nonfungiblePositionManager.d.ts +159 -0
  17. package/dist/payments.d.ts +24 -0
  18. package/dist/quoter.d.ts +37 -0
  19. package/dist/selfPermit.d.ts +25 -0
  20. package/dist/staker.d.ts +101 -0
  21. package/dist/swapRouter.d.ts +51 -0
  22. package/dist/utils/calldata.d.ts +20 -0
  23. package/dist/utils/computePoolAddress.d.ts +20 -0
  24. package/dist/utils/encodeRouteToPath.d.ts +8 -0
  25. package/dist/utils/encodeSqrtRatioX96.d.ts +9 -0
  26. package/dist/utils/fullMath.d.ts +8 -0
  27. package/dist/utils/index.d.ts +18 -0
  28. package/dist/utils/isSorted.d.ts +7 -0
  29. package/dist/utils/liquidityMath.d.ts +8 -0
  30. package/dist/utils/maxLiquidityForAmounts.d.ts +14 -0
  31. package/dist/utils/mostSignificantBit.d.ts +2 -0
  32. package/dist/utils/nearestUsableTick.d.ts +6 -0
  33. package/dist/utils/position.d.ts +8 -0
  34. package/dist/utils/priceTickConversions.d.ts +15 -0
  35. package/dist/utils/sqrtPriceMath.d.ts +13 -0
  36. package/dist/utils/swapMath.d.ts +9 -0
  37. package/dist/utils/tickLibrary.d.ts +14 -0
  38. package/dist/utils/tickList.d.ts +23 -0
  39. package/dist/utils/tickMath.d.ts +34 -0
  40. package/dist/utils/v3swap.d.ts +8 -0
  41. package/dist/v3-sdk.cjs.development.js +3002 -0
  42. package/dist/v3-sdk.cjs.development.js.map +1 -0
  43. package/dist/v3-sdk.cjs.production.min.js +2 -0
  44. package/dist/v3-sdk.cjs.production.min.js.map +1 -0
  45. package/dist/v3-sdk.esm.js +2961 -0
  46. package/dist/v3-sdk.esm.js.map +1 -0
  47. package/package.json +89 -0
@@ -0,0 +1,2961 @@
1
+ import { ChainId, computeZksyncCreate2Address, MaxUint256, sqrt, Price, CurrencyAmount, Percent, TradeType, Fraction, sortedInsert, validateAndParseAddress } from '@juiceswapxyz/sdk-core';
2
+ import JSBI from 'jsbi';
3
+ import invariant from 'tiny-invariant';
4
+ import { defaultAbiCoder, Interface } from '@ethersproject/abi';
5
+ import { getCreate2Address } from '@ethersproject/address';
6
+ import { keccak256, pack } from '@ethersproject/solidity';
7
+ import IMulticall from '@uniswap/v3-periphery/artifacts/contracts/interfaces/IMulticall.sol/IMulticall.json';
8
+ import INonfungiblePositionManager from '@uniswap/v3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json';
9
+ import ISelfPermit from '@uniswap/v3-periphery/artifacts/contracts/interfaces/ISelfPermit.sol/ISelfPermit.json';
10
+ import IPeripheryPaymentsWithFee from '@uniswap/v3-periphery/artifacts/contracts/interfaces/IPeripheryPaymentsWithFee.sol/IPeripheryPaymentsWithFee.json';
11
+ import IQuoter from '@uniswap/v3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json';
12
+ import IQuoterV2 from '@uniswap/swap-router-contracts/artifacts/contracts/lens/QuoterV2.sol/QuoterV2.json';
13
+ import IUniswapV3Staker from '@uniswap/v3-staker/artifacts/contracts/UniswapV3Staker.sol/UniswapV3Staker.json';
14
+ import ISwapRouter from '@uniswap/v3-periphery/artifacts/contracts/SwapRouter.sol/SwapRouter.json';
15
+
16
+ function _arrayLikeToArray(r, a) {
17
+ (null == a || a > r.length) && (a = r.length);
18
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
19
+ return n;
20
+ }
21
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
22
+ try {
23
+ var i = n[a](c),
24
+ u = i.value;
25
+ } catch (n) {
26
+ return void e(n);
27
+ }
28
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
29
+ }
30
+ function _asyncToGenerator(n) {
31
+ return function () {
32
+ var t = this,
33
+ e = arguments;
34
+ return new Promise(function (r, o) {
35
+ var a = n.apply(t, e);
36
+ function _next(n) {
37
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
38
+ }
39
+ function _throw(n) {
40
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
41
+ }
42
+ _next(void 0);
43
+ });
44
+ };
45
+ }
46
+ function _defineProperties(e, r) {
47
+ for (var t = 0; t < r.length; t++) {
48
+ var o = r[t];
49
+ o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
50
+ }
51
+ }
52
+ function _createClass(e, r, t) {
53
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
54
+ writable: !1
55
+ }), e;
56
+ }
57
+ function _createForOfIteratorHelperLoose(r, e) {
58
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
59
+ if (t) return (t = t.call(r)).next.bind(t);
60
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
61
+ t && (r = t);
62
+ var o = 0;
63
+ return function () {
64
+ return o >= r.length ? {
65
+ done: !0
66
+ } : {
67
+ done: !1,
68
+ value: r[o++]
69
+ };
70
+ };
71
+ }
72
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
73
+ }
74
+ function _extends() {
75
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
76
+ for (var e = 1; e < arguments.length; e++) {
77
+ var t = arguments[e];
78
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
79
+ }
80
+ return n;
81
+ }, _extends.apply(null, arguments);
82
+ }
83
+ function _objectWithoutPropertiesLoose(r, e) {
84
+ if (null == r) return {};
85
+ var t = {};
86
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
87
+ if (-1 !== e.indexOf(n)) continue;
88
+ t[n] = r[n];
89
+ }
90
+ return t;
91
+ }
92
+ function _regenerator() {
93
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
94
+ var e,
95
+ t,
96
+ r = "function" == typeof Symbol ? Symbol : {},
97
+ n = r.iterator || "@@iterator",
98
+ o = r.toStringTag || "@@toStringTag";
99
+ function i(r, n, o, i) {
100
+ var c = n && n.prototype instanceof Generator ? n : Generator,
101
+ u = Object.create(c.prototype);
102
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
103
+ var i,
104
+ c,
105
+ u,
106
+ f = 0,
107
+ p = o || [],
108
+ y = !1,
109
+ G = {
110
+ p: 0,
111
+ n: 0,
112
+ v: e,
113
+ a: d,
114
+ f: d.bind(e, 4),
115
+ d: function (t, r) {
116
+ return i = t, c = 0, u = e, G.n = r, a;
117
+ }
118
+ };
119
+ function d(r, n) {
120
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
121
+ var o,
122
+ i = p[t],
123
+ d = G.p,
124
+ l = i[2];
125
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
126
+ }
127
+ if (o || r > 1) return a;
128
+ throw y = !0, n;
129
+ }
130
+ return function (o, p, l) {
131
+ if (f > 1) throw TypeError("Generator is already running");
132
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
133
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
134
+ try {
135
+ if (f = 2, i) {
136
+ if (c || (o = "next"), t = i[o]) {
137
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
138
+ if (!t.done) return t;
139
+ u = t.value, c < 2 && (c = 0);
140
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
141
+ i = e;
142
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
143
+ } catch (t) {
144
+ i = e, c = 1, u = t;
145
+ } finally {
146
+ f = 1;
147
+ }
148
+ }
149
+ return {
150
+ value: t,
151
+ done: y
152
+ };
153
+ };
154
+ }(r, o, i), !0), u;
155
+ }
156
+ var a = {};
157
+ function Generator() {}
158
+ function GeneratorFunction() {}
159
+ function GeneratorFunctionPrototype() {}
160
+ t = Object.getPrototypeOf;
161
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
162
+ return this;
163
+ }), t),
164
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
165
+ function f(e) {
166
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
167
+ }
168
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
169
+ return this;
170
+ }), _regeneratorDefine(u, "toString", function () {
171
+ return "[object Generator]";
172
+ }), (_regenerator = function () {
173
+ return {
174
+ w: i,
175
+ m: f
176
+ };
177
+ })();
178
+ }
179
+ function _regeneratorDefine(e, r, n, t) {
180
+ var i = Object.defineProperty;
181
+ try {
182
+ i({}, "", {});
183
+ } catch (e) {
184
+ i = 0;
185
+ }
186
+ _regeneratorDefine = function (e, r, n, t) {
187
+ function o(r, n) {
188
+ _regeneratorDefine(e, r, function (e) {
189
+ return this._invoke(r, n, e);
190
+ });
191
+ }
192
+ r ? i ? i(e, r, {
193
+ value: n,
194
+ enumerable: !t,
195
+ configurable: !t,
196
+ writable: !t
197
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
198
+ }, _regeneratorDefine(e, r, n, t);
199
+ }
200
+ function _toPrimitive(t, r) {
201
+ if ("object" != typeof t || !t) return t;
202
+ var e = t[Symbol.toPrimitive];
203
+ if (void 0 !== e) {
204
+ var i = e.call(t, r || "default");
205
+ if ("object" != typeof i) return i;
206
+ throw new TypeError("@@toPrimitive must return a primitive value.");
207
+ }
208
+ return ("string" === r ? String : Number)(t);
209
+ }
210
+ function _toPropertyKey(t) {
211
+ var i = _toPrimitive(t, "string");
212
+ return "symbol" == typeof i ? i : i + "";
213
+ }
214
+ function _unsupportedIterableToArray(r, a) {
215
+ if (r) {
216
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
217
+ var t = {}.toString.call(r).slice(8, -1);
218
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
219
+ }
220
+ }
221
+
222
+ var _TICK_SPACINGS;
223
+ var FACTORY_ADDRESS = '0x1F98431c8aD98523631AE4a59f267346ea31F984';
224
+ var ADDRESS_ZERO = '0x0000000000000000000000000000000000000000';
225
+ // @deprecated please use poolInitCodeHash(chainId: ChainId)
226
+ var POOL_INIT_CODE_HASH = '0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54';
227
+ function poolInitCodeHash(chainId) {
228
+ switch (chainId) {
229
+ case ChainId.ZKSYNC:
230
+ return '0x010013f177ea1fcbc4520f9a3ca7cd2d1d77959e05aa66484027cb38e712aeed';
231
+ default:
232
+ return POOL_INIT_CODE_HASH;
233
+ }
234
+ }
235
+ /**
236
+ * The default factory enabled fee amounts, denominated in hundredths of bips.
237
+ */
238
+ var FeeAmount;
239
+ (function (FeeAmount) {
240
+ FeeAmount[FeeAmount["LOWEST"] = 100] = "LOWEST";
241
+ FeeAmount[FeeAmount["LOW_200"] = 200] = "LOW_200";
242
+ FeeAmount[FeeAmount["LOW_300"] = 300] = "LOW_300";
243
+ FeeAmount[FeeAmount["LOW_400"] = 400] = "LOW_400";
244
+ FeeAmount[FeeAmount["LOW"] = 500] = "LOW";
245
+ FeeAmount[FeeAmount["MEDIUM"] = 3000] = "MEDIUM";
246
+ FeeAmount[FeeAmount["HIGH"] = 10000] = "HIGH";
247
+ })(FeeAmount || (FeeAmount = {}));
248
+ /**
249
+ * The default factory tick spacings by fee amount.
250
+ */
251
+ var TICK_SPACINGS = (_TICK_SPACINGS = {}, _TICK_SPACINGS[FeeAmount.LOWEST] = 1, _TICK_SPACINGS[FeeAmount.LOW_200] = 4, _TICK_SPACINGS[FeeAmount.LOW_300] = 6, _TICK_SPACINGS[FeeAmount.LOW_400] = 8, _TICK_SPACINGS[FeeAmount.LOW] = 10, _TICK_SPACINGS[FeeAmount.MEDIUM] = 60, _TICK_SPACINGS[FeeAmount.HIGH] = 200, _TICK_SPACINGS);
252
+
253
+ // constants used internally but not expected to be used externally
254
+ var NEGATIVE_ONE = /*#__PURE__*/JSBI.BigInt(-1);
255
+ var ZERO = /*#__PURE__*/JSBI.BigInt(0);
256
+ var ONE = /*#__PURE__*/JSBI.BigInt(1);
257
+ // used in liquidity amount math
258
+ var Q96 = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(96));
259
+ var Q192 = /*#__PURE__*/JSBI.exponentiate(Q96, /*#__PURE__*/JSBI.BigInt(2));
260
+
261
+ /**
262
+ * Computes a pool address
263
+ * @param factoryAddress The Uniswap V3 factory address
264
+ * @param tokenA The first token of the pair, irrespective of sort order
265
+ * @param tokenB The second token of the pair, irrespective of sort order
266
+ * @param fee The fee tier of the pool
267
+ * @param initCodeHashManualOverride Override the init code hash used to compute the pool address if necessary
268
+ * @param chainId
269
+ * @returns The pool address
270
+ */
271
+ function computePoolAddress(_ref) {
272
+ var factoryAddress = _ref.factoryAddress,
273
+ tokenA = _ref.tokenA,
274
+ tokenB = _ref.tokenB,
275
+ fee = _ref.fee,
276
+ initCodeHashManualOverride = _ref.initCodeHashManualOverride,
277
+ chainId = _ref.chainId;
278
+ var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
279
+ token0 = _ref2[0],
280
+ token1 = _ref2[1]; // does safety checks
281
+ var salt = keccak256(['bytes'], [defaultAbiCoder.encode(['address', 'address', 'uint24'], [token0.address, token1.address, fee])]);
282
+ var initCodeHash = initCodeHashManualOverride != null ? initCodeHashManualOverride : poolInitCodeHash(chainId);
283
+ // ZKSync uses a different create2 address computation
284
+ // Most likely all ZKEVM chains will use the different computation from standard create2
285
+ switch (chainId) {
286
+ case ChainId.ZKSYNC:
287
+ return computeZksyncCreate2Address(factoryAddress, initCodeHash, salt);
288
+ default:
289
+ return getCreate2Address(factoryAddress, salt, initCodeHash);
290
+ }
291
+ }
292
+
293
+ var FullMath = /*#__PURE__*/function () {
294
+ /**
295
+ * Cannot be constructed.
296
+ */
297
+ function FullMath() {}
298
+ FullMath.mulDivRoundingUp = function mulDivRoundingUp(a, b, denominator) {
299
+ var product = JSBI.multiply(a, b);
300
+ var result = JSBI.divide(product, denominator);
301
+ if (JSBI.notEqual(JSBI.remainder(product, denominator), ZERO)) result = JSBI.add(result, ONE);
302
+ return result;
303
+ };
304
+ return FullMath;
305
+ }();
306
+
307
+ var MaxUint160 = /*#__PURE__*/JSBI.subtract(/*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(160)), ONE);
308
+ function multiplyIn256(x, y) {
309
+ var product = JSBI.multiply(x, y);
310
+ return JSBI.bitwiseAnd(product, MaxUint256);
311
+ }
312
+ function addIn256(x, y) {
313
+ var sum = JSBI.add(x, y);
314
+ return JSBI.bitwiseAnd(sum, MaxUint256);
315
+ }
316
+ var SqrtPriceMath = /*#__PURE__*/function () {
317
+ /**
318
+ * Cannot be constructed.
319
+ */
320
+ function SqrtPriceMath() {}
321
+ SqrtPriceMath.getAmount0Delta = function getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
322
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
323
+ var _ref = [sqrtRatioBX96, sqrtRatioAX96];
324
+ sqrtRatioAX96 = _ref[0];
325
+ sqrtRatioBX96 = _ref[1];
326
+ }
327
+ var numerator1 = JSBI.leftShift(liquidity, JSBI.BigInt(96));
328
+ var numerator2 = JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96);
329
+ return roundUp ? FullMath.mulDivRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), ONE, sqrtRatioAX96) : JSBI.divide(JSBI.divide(JSBI.multiply(numerator1, numerator2), sqrtRatioBX96), sqrtRatioAX96);
330
+ };
331
+ SqrtPriceMath.getAmount1Delta = function getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
332
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
333
+ var _ref2 = [sqrtRatioBX96, sqrtRatioAX96];
334
+ sqrtRatioAX96 = _ref2[0];
335
+ sqrtRatioBX96 = _ref2[1];
336
+ }
337
+ return roundUp ? FullMath.mulDivRoundingUp(liquidity, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96), Q96) : JSBI.divide(JSBI.multiply(liquidity, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96)), Q96);
338
+ };
339
+ SqrtPriceMath.getNextSqrtPriceFromInput = function getNextSqrtPriceFromInput(sqrtPX96, liquidity, amountIn, zeroForOne) {
340
+ !JSBI.greaterThan(sqrtPX96, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
341
+ !JSBI.greaterThan(liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
342
+ return zeroForOne ? this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
343
+ };
344
+ SqrtPriceMath.getNextSqrtPriceFromOutput = function getNextSqrtPriceFromOutput(sqrtPX96, liquidity, amountOut, zeroForOne) {
345
+ !JSBI.greaterThan(sqrtPX96, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
346
+ !JSBI.greaterThan(liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
347
+ return zeroForOne ? this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
348
+ };
349
+ SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp = function getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amount, add) {
350
+ if (JSBI.equal(amount, ZERO)) return sqrtPX96;
351
+ var numerator1 = JSBI.leftShift(liquidity, JSBI.BigInt(96));
352
+ if (add) {
353
+ var product = multiplyIn256(amount, sqrtPX96);
354
+ if (JSBI.equal(JSBI.divide(product, amount), sqrtPX96)) {
355
+ var denominator = addIn256(numerator1, product);
356
+ if (JSBI.greaterThanOrEqual(denominator, numerator1)) {
357
+ return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator);
358
+ }
359
+ }
360
+ return FullMath.mulDivRoundingUp(numerator1, ONE, JSBI.add(JSBI.divide(numerator1, sqrtPX96), amount));
361
+ } else {
362
+ var _product = multiplyIn256(amount, sqrtPX96);
363
+ !JSBI.equal(JSBI.divide(_product, amount), sqrtPX96) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
364
+ !JSBI.greaterThan(numerator1, _product) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
365
+ var _denominator = JSBI.subtract(numerator1, _product);
366
+ return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, _denominator);
367
+ }
368
+ };
369
+ SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown = function getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amount, add) {
370
+ if (add) {
371
+ var quotient = JSBI.lessThanOrEqual(amount, MaxUint160) ? JSBI.divide(JSBI.leftShift(amount, JSBI.BigInt(96)), liquidity) : JSBI.divide(JSBI.multiply(amount, Q96), liquidity);
372
+ return JSBI.add(sqrtPX96, quotient);
373
+ } else {
374
+ var _quotient = FullMath.mulDivRoundingUp(amount, Q96, liquidity);
375
+ !JSBI.greaterThan(sqrtPX96, _quotient) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
376
+ return JSBI.subtract(sqrtPX96, _quotient);
377
+ }
378
+ };
379
+ return SqrtPriceMath;
380
+ }();
381
+
382
+ var MAX_FEE = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(10), /*#__PURE__*/JSBI.BigInt(6));
383
+ var SwapMath = /*#__PURE__*/function () {
384
+ /**
385
+ * Cannot be constructed.
386
+ */
387
+ function SwapMath() {}
388
+ SwapMath.computeSwapStep = function computeSwapStep(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, amountRemaining, feePips) {
389
+ var returnValues = {};
390
+ feePips = JSBI.BigInt(feePips);
391
+ var zeroForOne = JSBI.greaterThanOrEqual(sqrtRatioCurrentX96, sqrtRatioTargetX96);
392
+ var exactIn = JSBI.greaterThanOrEqual(amountRemaining, ZERO);
393
+ if (exactIn) {
394
+ var amountRemainingLessFee = JSBI.divide(JSBI.multiply(amountRemaining, JSBI.subtract(MAX_FEE, feePips)), MAX_FEE);
395
+ returnValues.amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
396
+ if (JSBI.greaterThanOrEqual(amountRemainingLessFee, returnValues.amountIn)) {
397
+ returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
398
+ } else {
399
+ returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne);
400
+ }
401
+ } else {
402
+ returnValues.amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
403
+ if (JSBI.greaterThanOrEqual(JSBI.multiply(amountRemaining, NEGATIVE_ONE), returnValues.amountOut)) {
404
+ returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
405
+ } else {
406
+ returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtRatioCurrentX96, liquidity, JSBI.multiply(amountRemaining, NEGATIVE_ONE), zeroForOne);
407
+ }
408
+ }
409
+ var max = JSBI.equal(sqrtRatioTargetX96, returnValues.sqrtRatioNextX96);
410
+ if (zeroForOne) {
411
+ returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount0Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
412
+ returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount1Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
413
+ } else {
414
+ returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, true);
415
+ returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, false);
416
+ }
417
+ if (!exactIn && JSBI.greaterThan(returnValues.amountOut, JSBI.multiply(amountRemaining, NEGATIVE_ONE))) {
418
+ returnValues.amountOut = JSBI.multiply(amountRemaining, NEGATIVE_ONE);
419
+ }
420
+ if (exactIn && JSBI.notEqual(returnValues.sqrtRatioNextX96, sqrtRatioTargetX96)) {
421
+ // we didn't reach the target, so take the remainder of the maximum input as fee
422
+ returnValues.feeAmount = JSBI.subtract(amountRemaining, returnValues.amountIn);
423
+ } else {
424
+ returnValues.feeAmount = FullMath.mulDivRoundingUp(returnValues.amountIn, feePips, JSBI.subtract(MAX_FEE, feePips));
425
+ }
426
+ return [returnValues.sqrtRatioNextX96, returnValues.amountIn, returnValues.amountOut, returnValues.feeAmount];
427
+ };
428
+ return SwapMath;
429
+ }();
430
+
431
+ var LiquidityMath = /*#__PURE__*/function () {
432
+ /**
433
+ * Cannot be constructed.
434
+ */
435
+ function LiquidityMath() {}
436
+ LiquidityMath.addDelta = function addDelta(x, y) {
437
+ if (JSBI.lessThan(y, ZERO)) {
438
+ return JSBI.subtract(x, JSBI.multiply(y, NEGATIVE_ONE));
439
+ } else {
440
+ return JSBI.add(x, y);
441
+ }
442
+ };
443
+ return LiquidityMath;
444
+ }();
445
+
446
+ var TWO = /*#__PURE__*/JSBI.BigInt(2);
447
+ var POWERS_OF_2 = /*#__PURE__*/[128, 64, 32, 16, 8, 4, 2, 1].map(function (pow) {
448
+ return [pow, JSBI.exponentiate(TWO, JSBI.BigInt(pow))];
449
+ });
450
+ function mostSignificantBit(x) {
451
+ !JSBI.greaterThan(x, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO') : invariant(false) : void 0;
452
+ !JSBI.lessThanOrEqual(x, MaxUint256) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX') : invariant(false) : void 0;
453
+ var msb = 0;
454
+ for (var _iterator = _createForOfIteratorHelperLoose(POWERS_OF_2), _step; !(_step = _iterator()).done;) {
455
+ var _step$value = _step.value,
456
+ power = _step$value[0],
457
+ min = _step$value[1];
458
+ if (JSBI.greaterThanOrEqual(x, min)) {
459
+ x = JSBI.signedRightShift(x, JSBI.BigInt(power));
460
+ msb += power;
461
+ }
462
+ }
463
+ return msb;
464
+ }
465
+
466
+ function mulShift(val, mulBy) {
467
+ return JSBI.signedRightShift(JSBI.multiply(val, JSBI.BigInt(mulBy)), JSBI.BigInt(128));
468
+ }
469
+ var Q32 = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(32));
470
+ var TickMath = /*#__PURE__*/function () {
471
+ /**
472
+ * Cannot be constructed.
473
+ */
474
+ function TickMath() {}
475
+ /**
476
+ * Returns the sqrt ratio as a Q64.96 for the given tick. The sqrt ratio is computed as sqrt(1.0001)^tick
477
+ * @param tick the tick for which to compute the sqrt ratio
478
+ */
479
+ TickMath.getSqrtRatioAtTick = function getSqrtRatioAtTick(tick) {
480
+ !(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK && Number.isInteger(tick)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK') : invariant(false) : void 0;
481
+ var absTick = tick < 0 ? tick * -1 : tick;
482
+ var ratio = (absTick & 0x1) !== 0 ? JSBI.BigInt('0xfffcb933bd6fad37aa2d162d1a594001') : JSBI.BigInt('0x100000000000000000000000000000000');
483
+ if ((absTick & 0x2) !== 0) ratio = mulShift(ratio, '0xfff97272373d413259a46990580e213a');
484
+ if ((absTick & 0x4) !== 0) ratio = mulShift(ratio, '0xfff2e50f5f656932ef12357cf3c7fdcc');
485
+ if ((absTick & 0x8) !== 0) ratio = mulShift(ratio, '0xffe5caca7e10e4e61c3624eaa0941cd0');
486
+ if ((absTick & 0x10) !== 0) ratio = mulShift(ratio, '0xffcb9843d60f6159c9db58835c926644');
487
+ if ((absTick & 0x20) !== 0) ratio = mulShift(ratio, '0xff973b41fa98c081472e6896dfb254c0');
488
+ if ((absTick & 0x40) !== 0) ratio = mulShift(ratio, '0xff2ea16466c96a3843ec78b326b52861');
489
+ if ((absTick & 0x80) !== 0) ratio = mulShift(ratio, '0xfe5dee046a99a2a811c461f1969c3053');
490
+ if ((absTick & 0x100) !== 0) ratio = mulShift(ratio, '0xfcbe86c7900a88aedcffc83b479aa3a4');
491
+ if ((absTick & 0x200) !== 0) ratio = mulShift(ratio, '0xf987a7253ac413176f2b074cf7815e54');
492
+ if ((absTick & 0x400) !== 0) ratio = mulShift(ratio, '0xf3392b0822b70005940c7a398e4b70f3');
493
+ if ((absTick & 0x800) !== 0) ratio = mulShift(ratio, '0xe7159475a2c29b7443b29c7fa6e889d9');
494
+ if ((absTick & 0x1000) !== 0) ratio = mulShift(ratio, '0xd097f3bdfd2022b8845ad8f792aa5825');
495
+ if ((absTick & 0x2000) !== 0) ratio = mulShift(ratio, '0xa9f746462d870fdf8a65dc1f90e061e5');
496
+ if ((absTick & 0x4000) !== 0) ratio = mulShift(ratio, '0x70d869a156d2a1b890bb3df62baf32f7');
497
+ if ((absTick & 0x8000) !== 0) ratio = mulShift(ratio, '0x31be135f97d08fd981231505542fcfa6');
498
+ if ((absTick & 0x10000) !== 0) ratio = mulShift(ratio, '0x9aa508b5b7a84e1c677de54f3e99bc9');
499
+ if ((absTick & 0x20000) !== 0) ratio = mulShift(ratio, '0x5d6af8dedb81196699c329225ee604');
500
+ if ((absTick & 0x40000) !== 0) ratio = mulShift(ratio, '0x2216e584f5fa1ea926041bedfe98');
501
+ if ((absTick & 0x80000) !== 0) ratio = mulShift(ratio, '0x48a170391f7dc42444e8fa2');
502
+ if (tick > 0) ratio = JSBI.divide(MaxUint256, ratio);
503
+ // back to Q96
504
+ return JSBI.greaterThan(JSBI.remainder(ratio, Q32), ZERO) ? JSBI.add(JSBI.divide(ratio, Q32), ONE) : JSBI.divide(ratio, Q32);
505
+ }
506
+ /**
507
+ * Returns the tick corresponding to a given sqrt ratio, s.t. #getSqrtRatioAtTick(tick) <= sqrtRatioX96
508
+ * and #getSqrtRatioAtTick(tick + 1) > sqrtRatioX96
509
+ * @param sqrtRatioX96 the sqrt ratio as a Q64.96 for which to compute the tick
510
+ */;
511
+ TickMath.getTickAtSqrtRatio = function getTickAtSqrtRatio(sqrtRatioX96) {
512
+ !(JSBI.greaterThanOrEqual(sqrtRatioX96, TickMath.MIN_SQRT_RATIO) && JSBI.lessThan(sqrtRatioX96, TickMath.MAX_SQRT_RATIO)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SQRT_RATIO') : invariant(false) : void 0;
513
+ var sqrtRatioX128 = JSBI.leftShift(sqrtRatioX96, JSBI.BigInt(32));
514
+ var msb = mostSignificantBit(sqrtRatioX128);
515
+ var r;
516
+ if (JSBI.greaterThanOrEqual(JSBI.BigInt(msb), JSBI.BigInt(128))) {
517
+ r = JSBI.signedRightShift(sqrtRatioX128, JSBI.BigInt(msb - 127));
518
+ } else {
519
+ r = JSBI.leftShift(sqrtRatioX128, JSBI.BigInt(127 - msb));
520
+ }
521
+ var log_2 = JSBI.leftShift(JSBI.subtract(JSBI.BigInt(msb), JSBI.BigInt(128)), JSBI.BigInt(64));
522
+ for (var i = 0; i < 14; i++) {
523
+ r = JSBI.signedRightShift(JSBI.multiply(r, r), JSBI.BigInt(127));
524
+ var f = JSBI.signedRightShift(r, JSBI.BigInt(128));
525
+ log_2 = JSBI.bitwiseOr(log_2, JSBI.leftShift(f, JSBI.BigInt(63 - i)));
526
+ r = JSBI.signedRightShift(r, f);
527
+ }
528
+ var log_sqrt10001 = JSBI.multiply(log_2, JSBI.BigInt('255738958999603826347141'));
529
+ var tickLow = JSBI.toNumber(JSBI.signedRightShift(JSBI.subtract(log_sqrt10001, JSBI.BigInt('3402992956809132418596140100660247210')), JSBI.BigInt(128)));
530
+ var tickHigh = JSBI.toNumber(JSBI.signedRightShift(JSBI.add(log_sqrt10001, JSBI.BigInt('291339464771989622907027621153398088495')), JSBI.BigInt(128)));
531
+ return tickLow === tickHigh ? tickLow : JSBI.lessThanOrEqual(TickMath.getSqrtRatioAtTick(tickHigh), sqrtRatioX96) ? tickHigh : tickLow;
532
+ };
533
+ return TickMath;
534
+ }();
535
+ /**
536
+ * The minimum tick that can be used on any pool.
537
+ */
538
+ TickMath.MIN_TICK = -887272;
539
+ /**
540
+ * The maximum tick that can be used on any pool.
541
+ */
542
+ TickMath.MAX_TICK = -TickMath.MIN_TICK;
543
+ /**
544
+ * The sqrt ratio corresponding to the minimum tick that could be used on any pool.
545
+ */
546
+ TickMath.MIN_SQRT_RATIO = /*#__PURE__*/JSBI.BigInt('4295128739');
547
+ /**
548
+ * The sqrt ratio corresponding to the maximum tick that could be used on any pool.
549
+ */
550
+ TickMath.MAX_SQRT_RATIO = /*#__PURE__*/JSBI.BigInt('1461446703485210103287273052203988822378723970342');
551
+
552
+ function v3Swap(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8, _x9) {
553
+ return _v3Swap.apply(this, arguments);
554
+ }
555
+ function _v3Swap() {
556
+ _v3Swap = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(fee, sqrtRatioX96, tickCurrent, liquidity, tickSpacing, tickDataProvider, zeroForOne, amountSpecified, sqrtPriceLimitX96) {
557
+ var exactInput, state, step, _yield$tickDataProvid, _SwapMath$computeSwap, liquidityNet, _t;
558
+ return _regenerator().w(function (_context) {
559
+ while (1) switch (_context.n) {
560
+ case 0:
561
+ if (!sqrtPriceLimitX96) sqrtPriceLimitX96 = zeroForOne ? JSBI.add(TickMath.MIN_SQRT_RATIO, ONE) : JSBI.subtract(TickMath.MAX_SQRT_RATIO, ONE);
562
+ if (zeroForOne) {
563
+ !JSBI.greaterThan(sqrtPriceLimitX96, TickMath.MIN_SQRT_RATIO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'RATIO_MIN') : invariant(false) : void 0;
564
+ !JSBI.lessThan(sqrtPriceLimitX96, sqrtRatioX96) ? process.env.NODE_ENV !== "production" ? invariant(false, 'RATIO_CURRENT') : invariant(false) : void 0;
565
+ } else {
566
+ !JSBI.lessThan(sqrtPriceLimitX96, TickMath.MAX_SQRT_RATIO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'RATIO_MAX') : invariant(false) : void 0;
567
+ !JSBI.greaterThan(sqrtPriceLimitX96, sqrtRatioX96) ? process.env.NODE_ENV !== "production" ? invariant(false, 'RATIO_CURRENT') : invariant(false) : void 0;
568
+ }
569
+ exactInput = JSBI.greaterThanOrEqual(amountSpecified, ZERO); // keep track of swap state
570
+ state = {
571
+ amountSpecifiedRemaining: amountSpecified,
572
+ amountCalculated: ZERO,
573
+ sqrtPriceX96: sqrtRatioX96,
574
+ tick: tickCurrent,
575
+ liquidity: liquidity
576
+ }; // start swap while loop
577
+ case 1:
578
+ if (!(JSBI.notEqual(state.amountSpecifiedRemaining, ZERO) && state.sqrtPriceX96 !== sqrtPriceLimitX96)) {
579
+ _context.n = 7;
580
+ break;
581
+ }
582
+ step = {};
583
+ step.sqrtPriceStartX96 = state.sqrtPriceX96;
584
+ _context.n = 2;
585
+ return tickDataProvider.nextInitializedTickWithinOneWord(state.tick, zeroForOne, tickSpacing);
586
+ case 2:
587
+ _yield$tickDataProvid = _context.v;
588
+ step.tickNext = _yield$tickDataProvid[0];
589
+ step.initialized = _yield$tickDataProvid[1];
590
+ if (step.tickNext < TickMath.MIN_TICK) {
591
+ step.tickNext = TickMath.MIN_TICK;
592
+ } else if (step.tickNext > TickMath.MAX_TICK) {
593
+ step.tickNext = TickMath.MAX_TICK;
594
+ }
595
+ step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
596
+ _SwapMath$computeSwap = SwapMath.computeSwapStep(state.sqrtPriceX96, (zeroForOne ? JSBI.lessThan(step.sqrtPriceNextX96, sqrtPriceLimitX96) : JSBI.greaterThan(step.sqrtPriceNextX96, sqrtPriceLimitX96)) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96, state.liquidity, state.amountSpecifiedRemaining, fee);
597
+ state.sqrtPriceX96 = _SwapMath$computeSwap[0];
598
+ step.amountIn = _SwapMath$computeSwap[1];
599
+ step.amountOut = _SwapMath$computeSwap[2];
600
+ step.feeAmount = _SwapMath$computeSwap[3];
601
+ if (exactInput) {
602
+ state.amountSpecifiedRemaining = JSBI.subtract(state.amountSpecifiedRemaining, JSBI.add(step.amountIn, step.feeAmount));
603
+ state.amountCalculated = JSBI.subtract(state.amountCalculated, step.amountOut);
604
+ } else {
605
+ state.amountSpecifiedRemaining = JSBI.add(state.amountSpecifiedRemaining, step.amountOut);
606
+ state.amountCalculated = JSBI.add(state.amountCalculated, JSBI.add(step.amountIn, step.feeAmount));
607
+ }
608
+ // TODO
609
+ if (!JSBI.equal(state.sqrtPriceX96, step.sqrtPriceNextX96)) {
610
+ _context.n = 5;
611
+ break;
612
+ }
613
+ if (!step.initialized) {
614
+ _context.n = 4;
615
+ break;
616
+ }
617
+ _t = JSBI;
618
+ _context.n = 3;
619
+ return tickDataProvider.getTick(step.tickNext);
620
+ case 3:
621
+ liquidityNet = _t.BigInt.call(_t, _context.v.liquidityNet);
622
+ // if we're moving leftward, we interpret liquidityNet as the opposite sign
623
+ // safe because liquidityNet cannot be type(int128).min
624
+ if (zeroForOne) liquidityNet = JSBI.multiply(liquidityNet, NEGATIVE_ONE);
625
+ state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
626
+ case 4:
627
+ state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
628
+ _context.n = 6;
629
+ break;
630
+ case 5:
631
+ if (JSBI.notEqual(state.sqrtPriceX96, step.sqrtPriceStartX96)) {
632
+ // updated comparison function
633
+ // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
634
+ state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
635
+ }
636
+ case 6:
637
+ _context.n = 1;
638
+ break;
639
+ case 7:
640
+ return _context.a(2, {
641
+ amountCalculated: state.amountCalculated,
642
+ sqrtRatioX96: state.sqrtPriceX96,
643
+ liquidity: state.liquidity,
644
+ tickCurrent: state.tick
645
+ });
646
+ }
647
+ }, _callee);
648
+ }));
649
+ return _v3Swap.apply(this, arguments);
650
+ }
651
+
652
+ /**
653
+ * This tick data provider does not know how to fetch any tick data. It throws whenever it is required. Useful if you
654
+ * do not need to load tick data for your use case.
655
+ */
656
+ var NoTickDataProvider = /*#__PURE__*/function () {
657
+ function NoTickDataProvider() {}
658
+ var _proto = NoTickDataProvider.prototype;
659
+ _proto.getTick = /*#__PURE__*/function () {
660
+ var _getTick = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(_tick) {
661
+ return _regenerator().w(function (_context) {
662
+ while (1) switch (_context.n) {
663
+ case 0:
664
+ throw new Error(NoTickDataProvider.ERROR_MESSAGE);
665
+ case 1:
666
+ return _context.a(2);
667
+ }
668
+ }, _callee);
669
+ }));
670
+ function getTick(_x) {
671
+ return _getTick.apply(this, arguments);
672
+ }
673
+ return getTick;
674
+ }();
675
+ _proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () {
676
+ var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(_tick, _lte, _tickSpacing) {
677
+ return _regenerator().w(function (_context2) {
678
+ while (1) switch (_context2.n) {
679
+ case 0:
680
+ throw new Error(NoTickDataProvider.ERROR_MESSAGE);
681
+ case 1:
682
+ return _context2.a(2);
683
+ }
684
+ }, _callee2);
685
+ }));
686
+ function nextInitializedTickWithinOneWord(_x2, _x3, _x4) {
687
+ return _nextInitializedTickWithinOneWord.apply(this, arguments);
688
+ }
689
+ return nextInitializedTickWithinOneWord;
690
+ }();
691
+ return NoTickDataProvider;
692
+ }();
693
+ NoTickDataProvider.ERROR_MESSAGE = 'No tick data provider was given';
694
+
695
+ /**
696
+ * Determines if a tick list is sorted
697
+ * @param list The tick list
698
+ * @param comparator The comparator
699
+ * @returns true if sorted
700
+ */
701
+ function isSorted(list, comparator) {
702
+ for (var i = 0; i < list.length - 1; i++) {
703
+ if (comparator(list[i], list[i + 1]) > 0) {
704
+ return false;
705
+ }
706
+ }
707
+ return true;
708
+ }
709
+
710
+ function tickComparator(a, b) {
711
+ return a.index - b.index;
712
+ }
713
+ /**
714
+ * Utility methods for interacting with sorted lists of ticks
715
+ */
716
+ var TickList = /*#__PURE__*/function () {
717
+ /**
718
+ * Cannot be constructed
719
+ */
720
+ function TickList() {}
721
+ TickList.validateList = function validateList(ticks, tickSpacing) {
722
+ !(tickSpacing > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_SPACING_NONZERO') : invariant(false) : void 0;
723
+ // ensure ticks are spaced appropriately
724
+ !ticks.every(function (_ref) {
725
+ var index = _ref.index;
726
+ return index % tickSpacing === 0;
727
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_SPACING') : invariant(false) : void 0;
728
+ // ensure tick liquidity deltas sum to 0
729
+ !JSBI.equal(ticks.reduce(function (accumulator, _ref2) {
730
+ var liquidityNet = _ref2.liquidityNet;
731
+ return JSBI.add(accumulator, liquidityNet);
732
+ }, ZERO), ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO_NET') : invariant(false) : void 0;
733
+ !isSorted(ticks, tickComparator) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SORTED') : invariant(false) : void 0;
734
+ };
735
+ TickList.isBelowSmallest = function isBelowSmallest(ticks, tick) {
736
+ !(ticks.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LENGTH') : invariant(false) : void 0;
737
+ return tick < ticks[0].index;
738
+ };
739
+ TickList.isAtOrAboveLargest = function isAtOrAboveLargest(ticks, tick) {
740
+ !(ticks.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LENGTH') : invariant(false) : void 0;
741
+ return tick >= ticks[ticks.length - 1].index;
742
+ };
743
+ TickList.getTick = function getTick(ticks, index) {
744
+ var tick = ticks[this.binarySearch(ticks, index)];
745
+ !(tick.index === index) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NOT_CONTAINED') : invariant(false) : void 0;
746
+ return tick;
747
+ }
748
+ /**
749
+ * Finds the largest tick in the list of ticks that is less than or equal to tick
750
+ * @param ticks list of ticks
751
+ * @param tick tick to find the largest tick that is less than or equal to tick
752
+ * @private
753
+ */;
754
+ TickList.binarySearch = function binarySearch(ticks, tick) {
755
+ !!this.isBelowSmallest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'BELOW_SMALLEST') : invariant(false) : void 0;
756
+ var l = 0;
757
+ var r = ticks.length - 1;
758
+ var i;
759
+ while (true) {
760
+ i = Math.floor((l + r) / 2);
761
+ if (ticks[i].index <= tick && (i === ticks.length - 1 || ticks[i + 1].index > tick)) {
762
+ return i;
763
+ }
764
+ if (ticks[i].index < tick) {
765
+ l = i + 1;
766
+ } else {
767
+ r = i - 1;
768
+ }
769
+ }
770
+ };
771
+ TickList.nextInitializedTick = function nextInitializedTick(ticks, tick, lte) {
772
+ if (lte) {
773
+ !!TickList.isBelowSmallest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'BELOW_SMALLEST') : invariant(false) : void 0;
774
+ if (TickList.isAtOrAboveLargest(ticks, tick)) {
775
+ return ticks[ticks.length - 1];
776
+ }
777
+ var index = this.binarySearch(ticks, tick);
778
+ return ticks[index];
779
+ } else {
780
+ !!this.isAtOrAboveLargest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'AT_OR_ABOVE_LARGEST') : invariant(false) : void 0;
781
+ if (this.isBelowSmallest(ticks, tick)) {
782
+ return ticks[0];
783
+ }
784
+ var _index = this.binarySearch(ticks, tick);
785
+ return ticks[_index + 1];
786
+ }
787
+ };
788
+ TickList.nextInitializedTickWithinOneWord = function nextInitializedTickWithinOneWord(ticks, tick, lte, tickSpacing) {
789
+ var compressed = Math.floor(tick / tickSpacing); // matches rounding in the code
790
+ if (lte) {
791
+ var wordPos = compressed >> 8;
792
+ var minimum = (wordPos << 8) * tickSpacing;
793
+ if (TickList.isBelowSmallest(ticks, tick)) {
794
+ return [minimum, false];
795
+ }
796
+ var index = TickList.nextInitializedTick(ticks, tick, lte).index;
797
+ var nextInitializedTick = Math.max(minimum, index);
798
+ return [nextInitializedTick, nextInitializedTick === index];
799
+ } else {
800
+ var _wordPos = compressed + 1 >> 8;
801
+ var maximum = ((_wordPos + 1 << 8) - 1) * tickSpacing;
802
+ if (this.isAtOrAboveLargest(ticks, tick)) {
803
+ return [maximum, false];
804
+ }
805
+ var _index2 = this.nextInitializedTick(ticks, tick, lte).index;
806
+ var _nextInitializedTick = Math.min(maximum, _index2);
807
+ return [_nextInitializedTick, _nextInitializedTick === _index2];
808
+ }
809
+ };
810
+ return TickList;
811
+ }();
812
+
813
+ /**
814
+ * Converts a big int to a hex string
815
+ * @param bigintIsh
816
+ * @returns The hex encoded calldata
817
+ */
818
+ function toHex(bigintIsh) {
819
+ var bigInt = JSBI.BigInt(bigintIsh);
820
+ var hex = bigInt.toString(16);
821
+ if (hex.length % 2 !== 0) {
822
+ hex = "0" + hex;
823
+ }
824
+ return "0x" + hex;
825
+ }
826
+
827
+ /**
828
+ * Converts a route to a hex encoded path
829
+ * @param route the v3 path to convert to an encoded path
830
+ * @param exactOutput whether the route should be encoded in reverse, for making exact output swaps
831
+ */
832
+ function encodeRouteToPath(route, exactOutput) {
833
+ var firstInputToken = route.input.wrapped;
834
+ var _route$pools$reduce = route.pools.reduce(function (_ref, pool, index) {
835
+ var inputToken = _ref.inputToken,
836
+ path = _ref.path,
837
+ types = _ref.types;
838
+ var outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
839
+ if (index === 0) {
840
+ return {
841
+ inputToken: outputToken,
842
+ types: ['address', 'uint24', 'address'],
843
+ path: [inputToken.address, pool.fee, outputToken.address]
844
+ };
845
+ } else {
846
+ return {
847
+ inputToken: outputToken,
848
+ types: [].concat(types, ['uint24', 'address']),
849
+ path: [].concat(path, [pool.fee, outputToken.address])
850
+ };
851
+ }
852
+ }, {
853
+ inputToken: firstInputToken,
854
+ path: [],
855
+ types: []
856
+ }),
857
+ path = _route$pools$reduce.path,
858
+ types = _route$pools$reduce.types;
859
+ return exactOutput ? pack(types.reverse(), path.reverse()) : pack(types, path);
860
+ }
861
+
862
+ /**
863
+ * Returns the sqrt ratio as a Q64.96 corresponding to a given ratio of amount1 and amount0
864
+ * @param amount1 The numerator amount i.e., the amount of token1
865
+ * @param amount0 The denominator amount i.e., the amount of token0
866
+ * @returns The sqrt ratio
867
+ */
868
+ function encodeSqrtRatioX96(amount1, amount0) {
869
+ var numerator = JSBI.leftShift(JSBI.BigInt(amount1), JSBI.BigInt(192));
870
+ var denominator = JSBI.BigInt(amount0);
871
+ var ratioX192 = JSBI.divide(numerator, denominator);
872
+ return sqrt(ratioX192);
873
+ }
874
+
875
+ /**
876
+ * Returns an imprecise maximum amount of liquidity received for a given amount of token 0.
877
+ * This function is available to accommodate LiquidityAmounts#getLiquidityForAmount0 in the v3 periphery,
878
+ * which could be more precise by at least 32 bits by dividing by Q64 instead of Q96 in the intermediate step,
879
+ * and shifting the subtracted ratio left by 32 bits. This imprecise calculation will likely be replaced in a future
880
+ * v3 router contract.
881
+ * @param sqrtRatioAX96 The price at the lower boundary
882
+ * @param sqrtRatioBX96 The price at the upper boundary
883
+ * @param amount0 The token0 amount
884
+ * @returns liquidity for amount0, imprecise
885
+ */
886
+ function maxLiquidityForAmount0Imprecise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
887
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
888
+ var _ref = [sqrtRatioBX96, sqrtRatioAX96];
889
+ sqrtRatioAX96 = _ref[0];
890
+ sqrtRatioBX96 = _ref[1];
891
+ }
892
+ var intermediate = JSBI.divide(JSBI.multiply(sqrtRatioAX96, sqrtRatioBX96), Q96);
893
+ return JSBI.divide(JSBI.multiply(JSBI.BigInt(amount0), intermediate), JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
894
+ }
895
+ /**
896
+ * Returns a precise maximum amount of liquidity received for a given amount of token 0 by dividing by Q64 instead of Q96 in the intermediate step,
897
+ * and shifting the subtracted ratio left by 32 bits.
898
+ * @param sqrtRatioAX96 The price at the lower boundary
899
+ * @param sqrtRatioBX96 The price at the upper boundary
900
+ * @param amount0 The token0 amount
901
+ * @returns liquidity for amount0, precise
902
+ */
903
+ function maxLiquidityForAmount0Precise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
904
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
905
+ var _ref2 = [sqrtRatioBX96, sqrtRatioAX96];
906
+ sqrtRatioAX96 = _ref2[0];
907
+ sqrtRatioBX96 = _ref2[1];
908
+ }
909
+ var numerator = JSBI.multiply(JSBI.multiply(JSBI.BigInt(amount0), sqrtRatioAX96), sqrtRatioBX96);
910
+ var denominator = JSBI.multiply(Q96, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
911
+ return JSBI.divide(numerator, denominator);
912
+ }
913
+ /**
914
+ * Computes the maximum amount of liquidity received for a given amount of token1
915
+ * @param sqrtRatioAX96 The price at the lower tick boundary
916
+ * @param sqrtRatioBX96 The price at the upper tick boundary
917
+ * @param amount1 The token1 amount
918
+ * @returns liquidity for amount1
919
+ */
920
+ function maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1) {
921
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
922
+ var _ref3 = [sqrtRatioBX96, sqrtRatioAX96];
923
+ sqrtRatioAX96 = _ref3[0];
924
+ sqrtRatioBX96 = _ref3[1];
925
+ }
926
+ return JSBI.divide(JSBI.multiply(JSBI.BigInt(amount1), Q96), JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
927
+ }
928
+ /**
929
+ * Computes the maximum amount of liquidity received for a given amount of token0, token1,
930
+ * and the prices at the tick boundaries.
931
+ * @param sqrtRatioCurrentX96 the current price
932
+ * @param sqrtRatioAX96 price at lower boundary
933
+ * @param sqrtRatioBX96 price at upper boundary
934
+ * @param amount0 token0 amount
935
+ * @param amount1 token1 amount
936
+ * @param useFullPrecision if false, liquidity will be maximized according to what the router can calculate,
937
+ * not what core can theoretically support
938
+ */
939
+ function maxLiquidityForAmounts(sqrtRatioCurrentX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision) {
940
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
941
+ var _ref4 = [sqrtRatioBX96, sqrtRatioAX96];
942
+ sqrtRatioAX96 = _ref4[0];
943
+ sqrtRatioBX96 = _ref4[1];
944
+ }
945
+ var maxLiquidityForAmount0 = useFullPrecision ? maxLiquidityForAmount0Precise : maxLiquidityForAmount0Imprecise;
946
+ if (JSBI.lessThanOrEqual(sqrtRatioCurrentX96, sqrtRatioAX96)) {
947
+ return maxLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
948
+ } else if (JSBI.lessThan(sqrtRatioCurrentX96, sqrtRatioBX96)) {
949
+ var liquidity0 = maxLiquidityForAmount0(sqrtRatioCurrentX96, sqrtRatioBX96, amount0);
950
+ var liquidity1 = maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioCurrentX96, amount1);
951
+ return JSBI.lessThan(liquidity0, liquidity1) ? liquidity0 : liquidity1;
952
+ } else {
953
+ return maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
954
+ }
955
+ }
956
+
957
+ /**
958
+ * Returns the closest tick that is nearest a given tick and usable for the given tick spacing
959
+ * @param tick the target tick
960
+ * @param tickSpacing the spacing of the pool
961
+ */
962
+ function nearestUsableTick(tick, tickSpacing) {
963
+ !(Number.isInteger(tick) && Number.isInteger(tickSpacing)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INTEGERS') : invariant(false) : void 0;
964
+ !(tickSpacing > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_SPACING') : invariant(false) : void 0;
965
+ !(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_BOUND') : invariant(false) : void 0;
966
+ var rounded = Math.round(tick / tickSpacing) * tickSpacing;
967
+ if (rounded < TickMath.MIN_TICK) return rounded + tickSpacing;else if (rounded > TickMath.MAX_TICK) return rounded - tickSpacing;else return rounded;
968
+ }
969
+
970
+ var Q128 = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(128));
971
+ var PositionLibrary = /*#__PURE__*/function () {
972
+ /**
973
+ * Cannot be constructed.
974
+ */
975
+ function PositionLibrary() {}
976
+ // replicates the portions of Position#update required to compute unaccounted fees
977
+ PositionLibrary.getTokensOwed = function getTokensOwed(feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, feeGrowthInside0X128, feeGrowthInside1X128) {
978
+ var tokensOwed0 = JSBI.divide(JSBI.multiply(subIn256(feeGrowthInside0X128, feeGrowthInside0LastX128), liquidity), Q128);
979
+ var tokensOwed1 = JSBI.divide(JSBI.multiply(subIn256(feeGrowthInside1X128, feeGrowthInside1LastX128), liquidity), Q128);
980
+ return [tokensOwed0, tokensOwed1];
981
+ };
982
+ return PositionLibrary;
983
+ }();
984
+
985
+ /**
986
+ * Returns a price object corresponding to the input tick and the base/quote token
987
+ * Inputs must be tokens because the address order is used to interpret the price represented by the tick
988
+ * @param baseToken the base token of the price
989
+ * @param quoteToken the quote token of the price
990
+ * @param tick the tick for which to return the price
991
+ */
992
+ function tickToPrice(baseToken, quoteToken, tick) {
993
+ var sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
994
+ var ratioX192 = JSBI.multiply(sqrtRatioX96, sqrtRatioX96);
995
+ return baseToken.sortsBefore(quoteToken) ? new Price(baseToken, quoteToken, Q192, ratioX192) : new Price(baseToken, quoteToken, ratioX192, Q192);
996
+ }
997
+ /**
998
+ * Returns the first tick for which the given price is greater than or equal to the tick price
999
+ * @param price for which to return the closest tick that represents a price less than or equal to the input price,
1000
+ * i.e. the price of the returned tick is less than or equal to the input price
1001
+ */
1002
+ function priceToClosestTick(price) {
1003
+ var sorted = price.baseCurrency.sortsBefore(price.quoteCurrency);
1004
+ var sqrtRatioX96 = sorted ? encodeSqrtRatioX96(price.numerator, price.denominator) : encodeSqrtRatioX96(price.denominator, price.numerator);
1005
+ var tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1006
+ var nextTickPrice = tickToPrice(price.baseCurrency, price.quoteCurrency, tick + 1);
1007
+ if (sorted) {
1008
+ if (!price.lessThan(nextTickPrice)) {
1009
+ tick++;
1010
+ }
1011
+ } else {
1012
+ if (!price.greaterThan(nextTickPrice)) {
1013
+ tick++;
1014
+ }
1015
+ }
1016
+ return tick;
1017
+ }
1018
+
1019
+ var Q256 = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(256));
1020
+ function subIn256(x, y) {
1021
+ var difference = JSBI.subtract(x, y);
1022
+ if (JSBI.lessThan(difference, ZERO)) {
1023
+ return JSBI.add(Q256, difference);
1024
+ } else {
1025
+ return difference;
1026
+ }
1027
+ }
1028
+ var TickLibrary = /*#__PURE__*/function () {
1029
+ /**
1030
+ * Cannot be constructed.
1031
+ */
1032
+ function TickLibrary() {}
1033
+ TickLibrary.getFeeGrowthInside = function getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) {
1034
+ var feeGrowthBelow0X128;
1035
+ var feeGrowthBelow1X128;
1036
+ if (tickCurrent >= tickLower) {
1037
+ feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128;
1038
+ feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128;
1039
+ } else {
1040
+ feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128);
1041
+ feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128);
1042
+ }
1043
+ var feeGrowthAbove0X128;
1044
+ var feeGrowthAbove1X128;
1045
+ if (tickCurrent < tickUpper) {
1046
+ feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128;
1047
+ feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128;
1048
+ } else {
1049
+ feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128);
1050
+ feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128);
1051
+ }
1052
+ return [subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128), subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)];
1053
+ };
1054
+ return TickLibrary;
1055
+ }();
1056
+
1057
+ var Tick = function Tick(_ref) {
1058
+ var index = _ref.index,
1059
+ liquidityGross = _ref.liquidityGross,
1060
+ liquidityNet = _ref.liquidityNet;
1061
+ !(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK') : invariant(false) : void 0;
1062
+ this.index = index;
1063
+ this.liquidityGross = JSBI.BigInt(liquidityGross);
1064
+ this.liquidityNet = JSBI.BigInt(liquidityNet);
1065
+ };
1066
+
1067
+ /**
1068
+ * A data provider for ticks that is backed by an in-memory array of ticks.
1069
+ */
1070
+ var TickListDataProvider = /*#__PURE__*/function () {
1071
+ function TickListDataProvider(ticks, tickSpacing) {
1072
+ var ticksMapped = ticks.map(function (t) {
1073
+ return t instanceof Tick ? t : new Tick(t);
1074
+ });
1075
+ TickList.validateList(ticksMapped, tickSpacing);
1076
+ this.ticks = ticksMapped;
1077
+ }
1078
+ var _proto = TickListDataProvider.prototype;
1079
+ _proto.getTick = /*#__PURE__*/function () {
1080
+ var _getTick = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(tick) {
1081
+ return _regenerator().w(function (_context) {
1082
+ while (1) switch (_context.n) {
1083
+ case 0:
1084
+ return _context.a(2, TickList.getTick(this.ticks, tick));
1085
+ }
1086
+ }, _callee, this);
1087
+ }));
1088
+ function getTick(_x) {
1089
+ return _getTick.apply(this, arguments);
1090
+ }
1091
+ return getTick;
1092
+ }();
1093
+ _proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () {
1094
+ var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(tick, lte, tickSpacing) {
1095
+ return _regenerator().w(function (_context2) {
1096
+ while (1) switch (_context2.n) {
1097
+ case 0:
1098
+ return _context2.a(2, TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing));
1099
+ }
1100
+ }, _callee2, this);
1101
+ }));
1102
+ function nextInitializedTickWithinOneWord(_x2, _x3, _x4) {
1103
+ return _nextInitializedTickWithinOneWord.apply(this, arguments);
1104
+ }
1105
+ return nextInitializedTickWithinOneWord;
1106
+ }();
1107
+ return TickListDataProvider;
1108
+ }();
1109
+
1110
+ /**
1111
+ * By default, pools will not allow operations that require ticks.
1112
+ */
1113
+ var NO_TICK_DATA_PROVIDER_DEFAULT = /*#__PURE__*/new NoTickDataProvider();
1114
+ /**
1115
+ * Represents a V3 pool
1116
+ */
1117
+ var Pool = /*#__PURE__*/function () {
1118
+ /**
1119
+ * Construct a pool
1120
+ * @param tokenA One of the tokens in the pool
1121
+ * @param tokenB The other token in the pool
1122
+ * @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
1123
+ * @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0
1124
+ * @param liquidity The current value of in range liquidity
1125
+ * @param tickCurrent The current tick of the pool
1126
+ * @param ticks The current state of the pool ticks or a data provider that can return tick data
1127
+ */
1128
+ function Pool(tokenA, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks) {
1129
+ if (ticks === void 0) {
1130
+ ticks = NO_TICK_DATA_PROVIDER_DEFAULT;
1131
+ }
1132
+ !(Number.isInteger(fee) && fee < 1000000) ? process.env.NODE_ENV !== "production" ? invariant(false, 'FEE') : invariant(false) : void 0;
1133
+ var tickCurrentSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent);
1134
+ var nextTickSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent + 1);
1135
+ !(JSBI.greaterThanOrEqual(JSBI.BigInt(sqrtRatioX96), tickCurrentSqrtRatioX96) && JSBI.lessThanOrEqual(JSBI.BigInt(sqrtRatioX96), nextTickSqrtRatioX96)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PRICE_BOUNDS') : invariant(false) : void 0;
1136
+ var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
1137
+ this.token0 = _ref[0];
1138
+ this.token1 = _ref[1];
1139
+ this.fee = fee;
1140
+ this.sqrtRatioX96 = JSBI.BigInt(sqrtRatioX96);
1141
+ this.liquidity = JSBI.BigInt(liquidity);
1142
+ this.tickCurrent = tickCurrent;
1143
+ this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks, TICK_SPACINGS[fee]) : ticks;
1144
+ }
1145
+ Pool.getAddress = function getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, factoryAddressOverride) {
1146
+ return computePoolAddress({
1147
+ factoryAddress: factoryAddressOverride != null ? factoryAddressOverride : FACTORY_ADDRESS,
1148
+ fee: fee,
1149
+ tokenA: tokenA,
1150
+ tokenB: tokenB,
1151
+ initCodeHashManualOverride: initCodeHashManualOverride
1152
+ });
1153
+ }
1154
+ /**
1155
+ * Returns true if the token is either token0 or token1
1156
+ * @param token The token to check
1157
+ * @returns True if token is either token0 or token
1158
+ */;
1159
+ var _proto = Pool.prototype;
1160
+ _proto.involvesToken = function involvesToken(token) {
1161
+ return token.equals(this.token0) || token.equals(this.token1);
1162
+ }
1163
+ /**
1164
+ * Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
1165
+ */;
1166
+ /**
1167
+ * Return the price of the given token in terms of the other token in the pool.
1168
+ * @param token The token to return price of
1169
+ * @returns The price of the given token, in terms of the other.
1170
+ */
1171
+ _proto.priceOf = function priceOf(token) {
1172
+ !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
1173
+ return token.equals(this.token0) ? this.token0Price : this.token1Price;
1174
+ }
1175
+ /**
1176
+ * Returns the chain ID of the tokens in the pool.
1177
+ */;
1178
+ /**
1179
+ * Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
1180
+ * @param inputAmount The input amount for which to quote the output amount
1181
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
1182
+ * @returns The output amount and the pool with updated state
1183
+ */
1184
+ _proto.getOutputAmount =
1185
+ /*#__PURE__*/
1186
+ function () {
1187
+ var _getOutputAmount = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(inputAmount, sqrtPriceLimitX96) {
1188
+ var zeroForOne, _yield$this$swap, outputAmount, sqrtRatioX96, liquidity, tickCurrent, outputToken;
1189
+ return _regenerator().w(function (_context) {
1190
+ while (1) switch (_context.n) {
1191
+ case 0:
1192
+ !this.involvesToken(inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
1193
+ zeroForOne = inputAmount.currency.equals(this.token0);
1194
+ _context.n = 1;
1195
+ return this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96);
1196
+ case 1:
1197
+ _yield$this$swap = _context.v;
1198
+ outputAmount = _yield$this$swap.amountCalculated;
1199
+ sqrtRatioX96 = _yield$this$swap.sqrtRatioX96;
1200
+ liquidity = _yield$this$swap.liquidity;
1201
+ tickCurrent = _yield$this$swap.tickCurrent;
1202
+ outputToken = zeroForOne ? this.token1 : this.token0;
1203
+ return _context.a(2, [CurrencyAmount.fromRawAmount(outputToken, JSBI.multiply(outputAmount, NEGATIVE_ONE)), new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]);
1204
+ }
1205
+ }, _callee, this);
1206
+ }));
1207
+ function getOutputAmount(_x, _x2) {
1208
+ return _getOutputAmount.apply(this, arguments);
1209
+ }
1210
+ return getOutputAmount;
1211
+ }()
1212
+ /**
1213
+ * Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
1214
+ * @param outputAmount the output amount for which to quote the input amount
1215
+ * @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
1216
+ * @returns The input amount and the pool with updated state
1217
+ */
1218
+ ;
1219
+ _proto.getInputAmount =
1220
+ /*#__PURE__*/
1221
+ function () {
1222
+ var _getInputAmount = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(outputAmount, sqrtPriceLimitX96) {
1223
+ var zeroForOne, _yield$this$swap2, inputAmount, sqrtRatioX96, liquidity, tickCurrent, inputToken;
1224
+ return _regenerator().w(function (_context2) {
1225
+ while (1) switch (_context2.n) {
1226
+ case 0:
1227
+ !(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
1228
+ zeroForOne = outputAmount.currency.equals(this.token1);
1229
+ _context2.n = 1;
1230
+ return this.swap(zeroForOne, JSBI.multiply(outputAmount.quotient, NEGATIVE_ONE), sqrtPriceLimitX96);
1231
+ case 1:
1232
+ _yield$this$swap2 = _context2.v;
1233
+ inputAmount = _yield$this$swap2.amountCalculated;
1234
+ sqrtRatioX96 = _yield$this$swap2.sqrtRatioX96;
1235
+ liquidity = _yield$this$swap2.liquidity;
1236
+ tickCurrent = _yield$this$swap2.tickCurrent;
1237
+ inputToken = zeroForOne ? this.token0 : this.token1;
1238
+ return _context2.a(2, [CurrencyAmount.fromRawAmount(inputToken, inputAmount), new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]);
1239
+ }
1240
+ }, _callee2, this);
1241
+ }));
1242
+ function getInputAmount(_x3, _x4) {
1243
+ return _getInputAmount.apply(this, arguments);
1244
+ }
1245
+ return getInputAmount;
1246
+ }()
1247
+ /**
1248
+ * Executes a swap
1249
+ * @param zeroForOne Whether the amount in is token0 or token1
1250
+ * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
1251
+ * @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
1252
+ * @returns amountCalculated
1253
+ * @returns sqrtRatioX96
1254
+ * @returns liquidity
1255
+ * @returns tickCurrent
1256
+ */
1257
+ ;
1258
+ _proto.swap =
1259
+ /*#__PURE__*/
1260
+ function () {
1261
+ var _swap = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
1262
+ return _regenerator().w(function (_context3) {
1263
+ while (1) switch (_context3.n) {
1264
+ case 0:
1265
+ return _context3.a(2, v3Swap(JSBI.BigInt(this.fee), this.sqrtRatioX96, this.tickCurrent, this.liquidity, this.tickSpacing, this.tickDataProvider, zeroForOne, amountSpecified, sqrtPriceLimitX96));
1266
+ }
1267
+ }, _callee3, this);
1268
+ }));
1269
+ function swap(_x5, _x6, _x7) {
1270
+ return _swap.apply(this, arguments);
1271
+ }
1272
+ return swap;
1273
+ }();
1274
+ return _createClass(Pool, [{
1275
+ key: "token0Price",
1276
+ get: function get() {
1277
+ var _this$_token0Price;
1278
+ return (_this$_token0Price = this._token0Price) != null ? _this$_token0Price : this._token0Price = new Price(this.token0, this.token1, Q192, JSBI.multiply(this.sqrtRatioX96, this.sqrtRatioX96));
1279
+ }
1280
+ /**
1281
+ * Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
1282
+ */
1283
+ }, {
1284
+ key: "token1Price",
1285
+ get: function get() {
1286
+ var _this$_token1Price;
1287
+ return (_this$_token1Price = this._token1Price) != null ? _this$_token1Price : this._token1Price = new Price(this.token1, this.token0, JSBI.multiply(this.sqrtRatioX96, this.sqrtRatioX96), Q192);
1288
+ }
1289
+ }, {
1290
+ key: "chainId",
1291
+ get: function get() {
1292
+ return this.token0.chainId;
1293
+ }
1294
+ }, {
1295
+ key: "tickSpacing",
1296
+ get: function get() {
1297
+ return TICK_SPACINGS[this.fee];
1298
+ }
1299
+ }]);
1300
+ }();
1301
+
1302
+ /**
1303
+ * Represents a position on a Uniswap V3 Pool
1304
+ */
1305
+ var Position = /*#__PURE__*/function () {
1306
+ /**
1307
+ * Constructs a position for a given pool with the given liquidity
1308
+ * @param pool For which pool the liquidity is assigned
1309
+ * @param liquidity The amount of liquidity that is in the position
1310
+ * @param tickLower The lower tick of the position
1311
+ * @param tickUpper The upper tick of the position
1312
+ */
1313
+ function Position(_ref) {
1314
+ var pool = _ref.pool,
1315
+ liquidity = _ref.liquidity,
1316
+ tickLower = _ref.tickLower,
1317
+ tickUpper = _ref.tickUpper;
1318
+ // cached resuts for the getters
1319
+ this._token0Amount = null;
1320
+ this._token1Amount = null;
1321
+ this._mintAmounts = null;
1322
+ !(tickLower < tickUpper) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_ORDER') : invariant(false) : void 0;
1323
+ !(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_LOWER') : invariant(false) : void 0;
1324
+ !(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_UPPER') : invariant(false) : void 0;
1325
+ this.pool = pool;
1326
+ this.tickLower = tickLower;
1327
+ this.tickUpper = tickUpper;
1328
+ this.liquidity = JSBI.BigInt(liquidity);
1329
+ }
1330
+ /**
1331
+ * Returns the price of token0 at the lower tick
1332
+ */
1333
+ var _proto = Position.prototype;
1334
+ /**
1335
+ * Returns the lower and upper sqrt ratios if the price 'slips' up to slippage tolerance percentage
1336
+ * @param slippageTolerance The amount by which the price can 'slip' before the transaction will revert
1337
+ * @returns The sqrt ratios after slippage
1338
+ */
1339
+ _proto.ratiosAfterSlippage = function ratiosAfterSlippage(slippageTolerance) {
1340
+ var priceLower = this.pool.token0Price.asFraction.multiply(new Percent(1).subtract(slippageTolerance));
1341
+ var priceUpper = this.pool.token0Price.asFraction.multiply(slippageTolerance.add(1));
1342
+ var sqrtRatioX96Lower = encodeSqrtRatioX96(priceLower.numerator, priceLower.denominator);
1343
+ if (JSBI.lessThanOrEqual(sqrtRatioX96Lower, TickMath.MIN_SQRT_RATIO)) {
1344
+ sqrtRatioX96Lower = JSBI.add(TickMath.MIN_SQRT_RATIO, JSBI.BigInt(1));
1345
+ }
1346
+ var sqrtRatioX96Upper = encodeSqrtRatioX96(priceUpper.numerator, priceUpper.denominator);
1347
+ if (JSBI.greaterThanOrEqual(sqrtRatioX96Upper, TickMath.MAX_SQRT_RATIO)) {
1348
+ sqrtRatioX96Upper = JSBI.subtract(TickMath.MAX_SQRT_RATIO, JSBI.BigInt(1));
1349
+ }
1350
+ return {
1351
+ sqrtRatioX96Lower: sqrtRatioX96Lower,
1352
+ sqrtRatioX96Upper: sqrtRatioX96Upper
1353
+ };
1354
+ }
1355
+ /**
1356
+ * Returns the minimum amounts that must be sent in order to safely mint the amount of liquidity held by the position
1357
+ * with the given slippage tolerance
1358
+ * @param slippageTolerance Tolerance of unfavorable slippage from the current price
1359
+ * @returns The amounts, with slippage
1360
+ */;
1361
+ _proto.mintAmountsWithSlippage = function mintAmountsWithSlippage(slippageTolerance) {
1362
+ // get lower/upper prices
1363
+ var _this$ratiosAfterSlip = this.ratiosAfterSlippage(slippageTolerance),
1364
+ sqrtRatioX96Upper = _this$ratiosAfterSlip.sqrtRatioX96Upper,
1365
+ sqrtRatioX96Lower = _this$ratiosAfterSlip.sqrtRatioX96Lower;
1366
+ // construct counterfactual pools
1367
+ var poolLower = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Lower, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower));
1368
+ var poolUpper = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Upper, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper));
1369
+ // because the router is imprecise, we need to calculate the position that will be created (assuming no slippage)
1370
+ var positionThatWillBeCreated = Position.fromAmounts(_extends({
1371
+ pool: this.pool,
1372
+ tickLower: this.tickLower,
1373
+ tickUpper: this.tickUpper
1374
+ }, this.mintAmounts, {
1375
+ useFullPrecision: false
1376
+ }));
1377
+ // we want the smaller amounts...
1378
+ // ...which occurs at the upper price for amount0...
1379
+ var amount0 = new Position({
1380
+ pool: poolUpper,
1381
+ liquidity: positionThatWillBeCreated.liquidity,
1382
+ tickLower: this.tickLower,
1383
+ tickUpper: this.tickUpper
1384
+ }).mintAmounts.amount0;
1385
+ // ...and the lower for amount1
1386
+ var amount1 = new Position({
1387
+ pool: poolLower,
1388
+ liquidity: positionThatWillBeCreated.liquidity,
1389
+ tickLower: this.tickLower,
1390
+ tickUpper: this.tickUpper
1391
+ }).mintAmounts.amount1;
1392
+ return {
1393
+ amount0: amount0,
1394
+ amount1: amount1
1395
+ };
1396
+ }
1397
+ /**
1398
+ * Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the
1399
+ * position with the given slippage tolerance
1400
+ * @param slippageTolerance tolerance of unfavorable slippage from the current price
1401
+ * @returns The amounts, with slippage
1402
+ */;
1403
+ _proto.burnAmountsWithSlippage = function burnAmountsWithSlippage(slippageTolerance) {
1404
+ // get lower/upper prices
1405
+ var _this$ratiosAfterSlip2 = this.ratiosAfterSlippage(slippageTolerance),
1406
+ sqrtRatioX96Upper = _this$ratiosAfterSlip2.sqrtRatioX96Upper,
1407
+ sqrtRatioX96Lower = _this$ratiosAfterSlip2.sqrtRatioX96Lower;
1408
+ // construct counterfactual pools
1409
+ var poolLower = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Lower, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower));
1410
+ var poolUpper = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Upper, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper));
1411
+ // we want the smaller amounts...
1412
+ // ...which occurs at the upper price for amount0...
1413
+ var amount0 = new Position({
1414
+ pool: poolUpper,
1415
+ liquidity: this.liquidity,
1416
+ tickLower: this.tickLower,
1417
+ tickUpper: this.tickUpper
1418
+ }).amount0;
1419
+ // ...and the lower for amount1
1420
+ var amount1 = new Position({
1421
+ pool: poolLower,
1422
+ liquidity: this.liquidity,
1423
+ tickLower: this.tickLower,
1424
+ tickUpper: this.tickUpper
1425
+ }).amount1;
1426
+ return {
1427
+ amount0: amount0.quotient,
1428
+ amount1: amount1.quotient
1429
+ };
1430
+ }
1431
+ /**
1432
+ * Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at
1433
+ * the current price for the pool
1434
+ */;
1435
+ /**
1436
+ * Computes the maximum amount of liquidity received for a given amount of token0, token1,
1437
+ * and the prices at the tick boundaries.
1438
+ * @param pool The pool for which the position should be created
1439
+ * @param tickLower The lower tick of the position
1440
+ * @param tickUpper The upper tick of the position
1441
+ * @param amount0 token0 amount
1442
+ * @param amount1 token1 amount
1443
+ * @param useFullPrecision If false, liquidity will be maximized according to what the router can calculate,
1444
+ * not what core can theoretically support
1445
+ * @returns The amount of liquidity for the position
1446
+ */
1447
+ Position.fromAmounts = function fromAmounts(_ref2) {
1448
+ var pool = _ref2.pool,
1449
+ tickLower = _ref2.tickLower,
1450
+ tickUpper = _ref2.tickUpper,
1451
+ amount0 = _ref2.amount0,
1452
+ amount1 = _ref2.amount1,
1453
+ useFullPrecision = _ref2.useFullPrecision;
1454
+ var sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
1455
+ var sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
1456
+ return new Position({
1457
+ pool: pool,
1458
+ tickLower: tickLower,
1459
+ tickUpper: tickUpper,
1460
+ liquidity: maxLiquidityForAmounts(pool.sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision)
1461
+ });
1462
+ }
1463
+ /**
1464
+ * Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1
1465
+ * @param pool The pool for which the position is created
1466
+ * @param tickLower The lower tick
1467
+ * @param tickUpper The upper tick
1468
+ * @param amount0 The desired amount of token0
1469
+ * @param useFullPrecision If true, liquidity will be maximized according to what the router can calculate,
1470
+ * not what core can theoretically support
1471
+ * @returns The position
1472
+ */;
1473
+ Position.fromAmount0 = function fromAmount0(_ref3) {
1474
+ var pool = _ref3.pool,
1475
+ tickLower = _ref3.tickLower,
1476
+ tickUpper = _ref3.tickUpper,
1477
+ amount0 = _ref3.amount0,
1478
+ useFullPrecision = _ref3.useFullPrecision;
1479
+ return Position.fromAmounts({
1480
+ pool: pool,
1481
+ tickLower: tickLower,
1482
+ tickUpper: tickUpper,
1483
+ amount0: amount0,
1484
+ amount1: MaxUint256,
1485
+ useFullPrecision: useFullPrecision
1486
+ });
1487
+ }
1488
+ /**
1489
+ * Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
1490
+ * @param pool The pool for which the position is created
1491
+ * @param tickLower The lower tick
1492
+ * @param tickUpper The upper tick
1493
+ * @param amount1 The desired amount of token1
1494
+ * @returns The position
1495
+ */;
1496
+ Position.fromAmount1 = function fromAmount1(_ref4) {
1497
+ var pool = _ref4.pool,
1498
+ tickLower = _ref4.tickLower,
1499
+ tickUpper = _ref4.tickUpper,
1500
+ amount1 = _ref4.amount1;
1501
+ // this function always uses full precision,
1502
+ return Position.fromAmounts({
1503
+ pool: pool,
1504
+ tickLower: tickLower,
1505
+ tickUpper: tickUpper,
1506
+ amount0: MaxUint256,
1507
+ amount1: amount1,
1508
+ useFullPrecision: true
1509
+ });
1510
+ };
1511
+ return _createClass(Position, [{
1512
+ key: "token0PriceLower",
1513
+ get: function get() {
1514
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickLower);
1515
+ }
1516
+ /**
1517
+ * Returns the price of token0 at the upper tick
1518
+ */
1519
+ }, {
1520
+ key: "token0PriceUpper",
1521
+ get: function get() {
1522
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickUpper);
1523
+ }
1524
+ /**
1525
+ * Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
1526
+ */
1527
+ }, {
1528
+ key: "amount0",
1529
+ get: function get() {
1530
+ if (this._token0Amount === null) {
1531
+ if (this.pool.tickCurrent < this.tickLower) {
1532
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.token0, SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
1533
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1534
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.token0, SqrtPriceMath.getAmount0Delta(this.pool.sqrtRatioX96, TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
1535
+ } else {
1536
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.token0, ZERO);
1537
+ }
1538
+ }
1539
+ return this._token0Amount;
1540
+ }
1541
+ /**
1542
+ * Returns the amount of token1 that this position's liquidity could be burned for at the current pool price
1543
+ */
1544
+ }, {
1545
+ key: "amount1",
1546
+ get: function get() {
1547
+ if (this._token1Amount === null) {
1548
+ if (this.pool.tickCurrent < this.tickLower) {
1549
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.token1, ZERO);
1550
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1551
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.token1, SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), this.pool.sqrtRatioX96, this.liquidity, false));
1552
+ } else {
1553
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.token1, SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
1554
+ }
1555
+ }
1556
+ return this._token1Amount;
1557
+ }
1558
+ }, {
1559
+ key: "mintAmounts",
1560
+ get: function get() {
1561
+ if (this._mintAmounts === null) {
1562
+ if (this.pool.tickCurrent < this.tickLower) {
1563
+ return {
1564
+ amount0: SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true),
1565
+ amount1: ZERO
1566
+ };
1567
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1568
+ return {
1569
+ amount0: SqrtPriceMath.getAmount0Delta(this.pool.sqrtRatioX96, TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true),
1570
+ amount1: SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), this.pool.sqrtRatioX96, this.liquidity, true)
1571
+ };
1572
+ } else {
1573
+ return {
1574
+ amount0: ZERO,
1575
+ amount1: SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true)
1576
+ };
1577
+ }
1578
+ }
1579
+ return this._mintAmounts;
1580
+ }
1581
+ }]);
1582
+ }();
1583
+
1584
+ /**
1585
+ * Represents a list of pools through which a swap can occur
1586
+ * @template TInput The input token
1587
+ * @template TOutput The output token
1588
+ */
1589
+ var Route = /*#__PURE__*/function () {
1590
+ /**
1591
+ * Creates an instance of route.
1592
+ * @param pools An array of `Pool` objects, ordered by the route the swap will take
1593
+ * @param input The input token
1594
+ * @param output The output token
1595
+ */
1596
+ function Route(pools, input, output) {
1597
+ this._midPrice = null;
1598
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
1599
+ var chainId = pools[0].chainId;
1600
+ var allOnSameChain = pools.every(function (pool) {
1601
+ return pool.chainId === chainId;
1602
+ });
1603
+ !allOnSameChain ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0;
1604
+ var wrappedInput = input.wrapped;
1605
+ !pools[0].involvesToken(wrappedInput) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
1606
+ !pools[pools.length - 1].involvesToken(output.wrapped) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
1607
+ /**
1608
+ * Normalizes token0-token1 order and selects the next token/fee step to add to the path
1609
+ * */
1610
+ var tokenPath = [wrappedInput];
1611
+ for (var _iterator = _createForOfIteratorHelperLoose(pools.entries()), _step; !(_step = _iterator()).done;) {
1612
+ var _step$value = _step.value,
1613
+ i = _step$value[0],
1614
+ pool = _step$value[1];
1615
+ var currentInputToken = tokenPath[i];
1616
+ !(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PATH') : invariant(false) : void 0;
1617
+ var nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0;
1618
+ tokenPath.push(nextToken);
1619
+ }
1620
+ this.pools = pools;
1621
+ this.tokenPath = tokenPath;
1622
+ this.input = input;
1623
+ this.output = output != null ? output : tokenPath[tokenPath.length - 1];
1624
+ }
1625
+ return _createClass(Route, [{
1626
+ key: "chainId",
1627
+ get: function get() {
1628
+ return this.pools[0].chainId;
1629
+ }
1630
+ /**
1631
+ * Returns the mid price of the route
1632
+ */
1633
+ }, {
1634
+ key: "midPrice",
1635
+ get: function get() {
1636
+ if (this._midPrice !== null) return this._midPrice;
1637
+ var price = this.pools.slice(1).reduce(function (_ref, pool) {
1638
+ var nextInput = _ref.nextInput,
1639
+ price = _ref.price;
1640
+ return nextInput.equals(pool.token0) ? {
1641
+ nextInput: pool.token1,
1642
+ price: price.multiply(pool.token0Price)
1643
+ } : {
1644
+ nextInput: pool.token0,
1645
+ price: price.multiply(pool.token1Price)
1646
+ };
1647
+ }, this.pools[0].token0.equals(this.input.wrapped) ? {
1648
+ nextInput: this.pools[0].token1,
1649
+ price: this.pools[0].token0Price
1650
+ } : {
1651
+ nextInput: this.pools[0].token0,
1652
+ price: this.pools[0].token1Price
1653
+ }).price;
1654
+ return this._midPrice = new Price(this.input, this.output, price.denominator, price.numerator);
1655
+ }
1656
+ }]);
1657
+ }();
1658
+
1659
+ /**
1660
+ * Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them
1661
+ * @template TInput The input token, either Ether or an ERC-20
1662
+ * @template TOutput The output token, either Ether or an ERC-20
1663
+ * @template TTradeType The trade type, either exact input or exact output
1664
+ * @param a The first trade to compare
1665
+ * @param b The second trade to compare
1666
+ * @returns A sorted ordering for two neighboring elements in a trade array
1667
+ */
1668
+ function tradeComparator(a, b) {
1669
+ // must have same input and output token for comparison
1670
+ !a.inputAmount.currency.equals(b.inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY') : invariant(false) : void 0;
1671
+ !a.outputAmount.currency.equals(b.outputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY') : invariant(false) : void 0;
1672
+ if (a.outputAmount.equalTo(b.outputAmount)) {
1673
+ if (a.inputAmount.equalTo(b.inputAmount)) {
1674
+ // consider the number of hops since each hop costs gas
1675
+ var aHops = a.swaps.reduce(function (total, cur) {
1676
+ return total + cur.route.tokenPath.length;
1677
+ }, 0);
1678
+ var bHops = b.swaps.reduce(function (total, cur) {
1679
+ return total + cur.route.tokenPath.length;
1680
+ }, 0);
1681
+ return aHops - bHops;
1682
+ }
1683
+ // trade A requires less input than trade B, so A should come first
1684
+ if (a.inputAmount.lessThan(b.inputAmount)) {
1685
+ return -1;
1686
+ } else {
1687
+ return 1;
1688
+ }
1689
+ } else {
1690
+ // tradeA has less output than trade B, so should come second
1691
+ if (a.outputAmount.lessThan(b.outputAmount)) {
1692
+ return 1;
1693
+ } else {
1694
+ return -1;
1695
+ }
1696
+ }
1697
+ }
1698
+ /**
1699
+ * Represents a trade executed against a set of routes where some percentage of the input is
1700
+ * split across each route.
1701
+ *
1702
+ * Each route has its own set of pools. Pools can not be re-used across routes.
1703
+ *
1704
+ * Does not account for slippage, i.e., changes in price environment that can occur between
1705
+ * the time the trade is submitted and when it is executed.
1706
+ * @template TInput The input token, either Ether or an ERC-20
1707
+ * @template TOutput The output token, either Ether or an ERC-20
1708
+ * @template TTradeType The trade type, either exact input or exact output
1709
+ */
1710
+ var Trade = /*#__PURE__*/function () {
1711
+ /**
1712
+ * Construct a trade by passing in the pre-computed property values
1713
+ * @param routes The routes through which the trade occurs
1714
+ * @param tradeType The type of trade, exact input or exact output
1715
+ */
1716
+ function Trade(_ref) {
1717
+ var routes = _ref.routes,
1718
+ tradeType = _ref.tradeType;
1719
+ var inputCurrency = routes[0].inputAmount.currency;
1720
+ var outputCurrency = routes[0].outputAmount.currency;
1721
+ !routes.every(function (_ref2) {
1722
+ var route = _ref2.route;
1723
+ return inputCurrency.wrapped.equals(route.input.wrapped);
1724
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY_MATCH') : invariant(false) : void 0;
1725
+ !routes.every(function (_ref3) {
1726
+ var route = _ref3.route;
1727
+ return outputCurrency.wrapped.equals(route.output.wrapped);
1728
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY_MATCH') : invariant(false) : void 0;
1729
+ var numPools = routes.map(function (_ref4) {
1730
+ var route = _ref4.route;
1731
+ return route.pools.length;
1732
+ }).reduce(function (total, cur) {
1733
+ return total + cur;
1734
+ }, 0);
1735
+ var poolAddressSet = new Set();
1736
+ for (var _iterator = _createForOfIteratorHelperLoose(routes), _step; !(_step = _iterator()).done;) {
1737
+ var route = _step.value.route;
1738
+ for (var _iterator2 = _createForOfIteratorHelperLoose(route.pools), _step2; !(_step2 = _iterator2()).done;) {
1739
+ var pool = _step2.value;
1740
+ poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, pool.fee));
1741
+ }
1742
+ }
1743
+ !(numPools === poolAddressSet.size) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS_DUPLICATED') : invariant(false) : void 0;
1744
+ this.swaps = routes;
1745
+ this.tradeType = tradeType;
1746
+ }
1747
+ /**
1748
+ * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
1749
+ * this will return an error.
1750
+ *
1751
+ * When the trade consists of just a single route, this returns the route of the trade,
1752
+ * i.e. which pools the trade goes through.
1753
+ */
1754
+ /**
1755
+ * Constructs an exact in trade with the given amount in and route
1756
+ * @template TInput The input token, either Ether or an ERC-20
1757
+ * @template TOutput The output token, either Ether or an ERC-20
1758
+ * @param route The route of the exact in trade
1759
+ * @param amountIn The amount being passed in
1760
+ * @returns The exact in trade
1761
+ */
1762
+ Trade.exactIn =
1763
+ /*#__PURE__*/
1764
+ function () {
1765
+ var _exactIn = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(route, amountIn) {
1766
+ return _regenerator().w(function (_context) {
1767
+ while (1) switch (_context.n) {
1768
+ case 0:
1769
+ return _context.a(2, Trade.fromRoute(route, amountIn, TradeType.EXACT_INPUT));
1770
+ }
1771
+ }, _callee);
1772
+ }));
1773
+ function exactIn(_x, _x2) {
1774
+ return _exactIn.apply(this, arguments);
1775
+ }
1776
+ return exactIn;
1777
+ }()
1778
+ /**
1779
+ * Constructs an exact out trade with the given amount out and route
1780
+ * @template TInput The input token, either Ether or an ERC-20
1781
+ * @template TOutput The output token, either Ether or an ERC-20
1782
+ * @param route The route of the exact out trade
1783
+ * @param amountOut The amount returned by the trade
1784
+ * @returns The exact out trade
1785
+ */
1786
+ ;
1787
+ Trade.exactOut =
1788
+ /*#__PURE__*/
1789
+ function () {
1790
+ var _exactOut = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(route, amountOut) {
1791
+ return _regenerator().w(function (_context2) {
1792
+ while (1) switch (_context2.n) {
1793
+ case 0:
1794
+ return _context2.a(2, Trade.fromRoute(route, amountOut, TradeType.EXACT_OUTPUT));
1795
+ }
1796
+ }, _callee2);
1797
+ }));
1798
+ function exactOut(_x3, _x4) {
1799
+ return _exactOut.apply(this, arguments);
1800
+ }
1801
+ return exactOut;
1802
+ }()
1803
+ /**
1804
+ * Constructs a trade by simulating swaps through the given route
1805
+ * @template TInput The input token, either Ether or an ERC-20.
1806
+ * @template TOutput The output token, either Ether or an ERC-20.
1807
+ * @template TTradeType The type of the trade, either exact in or exact out.
1808
+ * @param route route to swap through
1809
+ * @param amount the amount specified, either input or output, depending on tradeType
1810
+ * @param tradeType whether the trade is an exact input or exact output swap
1811
+ * @returns The route
1812
+ */
1813
+ ;
1814
+ Trade.fromRoute =
1815
+ /*#__PURE__*/
1816
+ function () {
1817
+ var _fromRoute = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(route, amount, tradeType) {
1818
+ var amounts, inputAmount, outputAmount, i, pool, _yield$pool$getOutput, _outputAmount, _i, _pool, _yield$_pool$getInput, _inputAmount;
1819
+ return _regenerator().w(function (_context3) {
1820
+ while (1) switch (_context3.n) {
1821
+ case 0:
1822
+ amounts = new Array(route.tokenPath.length);
1823
+ if (!(tradeType === TradeType.EXACT_INPUT)) {
1824
+ _context3.n = 5;
1825
+ break;
1826
+ }
1827
+ !amount.currency.equals(route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
1828
+ amounts[0] = amount.wrapped;
1829
+ i = 0;
1830
+ case 1:
1831
+ if (!(i < route.tokenPath.length - 1)) {
1832
+ _context3.n = 4;
1833
+ break;
1834
+ }
1835
+ pool = route.pools[i];
1836
+ _context3.n = 2;
1837
+ return pool.getOutputAmount(amounts[i]);
1838
+ case 2:
1839
+ _yield$pool$getOutput = _context3.v;
1840
+ _outputAmount = _yield$pool$getOutput[0];
1841
+ amounts[i + 1] = _outputAmount;
1842
+ case 3:
1843
+ i++;
1844
+ _context3.n = 1;
1845
+ break;
1846
+ case 4:
1847
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1848
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amounts[amounts.length - 1].numerator, amounts[amounts.length - 1].denominator);
1849
+ _context3.n = 10;
1850
+ break;
1851
+ case 5:
1852
+ !amount.currency.equals(route.output) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
1853
+ amounts[amounts.length - 1] = amount.wrapped;
1854
+ _i = route.tokenPath.length - 1;
1855
+ case 6:
1856
+ if (!(_i > 0)) {
1857
+ _context3.n = 9;
1858
+ break;
1859
+ }
1860
+ _pool = route.pools[_i - 1];
1861
+ _context3.n = 7;
1862
+ return _pool.getInputAmount(amounts[_i]);
1863
+ case 7:
1864
+ _yield$_pool$getInput = _context3.v;
1865
+ _inputAmount = _yield$_pool$getInput[0];
1866
+ amounts[_i - 1] = _inputAmount;
1867
+ case 8:
1868
+ _i--;
1869
+ _context3.n = 6;
1870
+ break;
1871
+ case 9:
1872
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
1873
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1874
+ case 10:
1875
+ return _context3.a(2, new Trade({
1876
+ routes: [{
1877
+ inputAmount: inputAmount,
1878
+ outputAmount: outputAmount,
1879
+ route: route
1880
+ }],
1881
+ tradeType: tradeType
1882
+ }));
1883
+ }
1884
+ }, _callee3);
1885
+ }));
1886
+ function fromRoute(_x5, _x6, _x7) {
1887
+ return _fromRoute.apply(this, arguments);
1888
+ }
1889
+ return fromRoute;
1890
+ }()
1891
+ /**
1892
+ * Constructs a trade from routes by simulating swaps
1893
+ *
1894
+ * @template TInput The input token, either Ether or an ERC-20.
1895
+ * @template TOutput The output token, either Ether or an ERC-20.
1896
+ * @template TTradeType The type of the trade, either exact in or exact out.
1897
+ * @param routes the routes to swap through and how much of the amount should be routed through each
1898
+ * @param tradeType whether the trade is an exact input or exact output swap
1899
+ * @returns The trade
1900
+ */
1901
+ ;
1902
+ Trade.fromRoutes =
1903
+ /*#__PURE__*/
1904
+ function () {
1905
+ var _fromRoutes = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(routes, tradeType) {
1906
+ var populatedRoutes, _iterator3, _step3, _step3$value, route, amount, amounts, inputAmount, outputAmount, i, pool, _yield$pool$getOutput2, _outputAmount2, _i2, _pool2, _yield$_pool2$getInpu, _inputAmount2;
1907
+ return _regenerator().w(function (_context4) {
1908
+ while (1) switch (_context4.n) {
1909
+ case 0:
1910
+ populatedRoutes = [];
1911
+ _iterator3 = _createForOfIteratorHelperLoose(routes);
1912
+ case 1:
1913
+ if ((_step3 = _iterator3()).done) {
1914
+ _context4.n = 13;
1915
+ break;
1916
+ }
1917
+ _step3$value = _step3.value, route = _step3$value.route, amount = _step3$value.amount;
1918
+ amounts = new Array(route.tokenPath.length);
1919
+ inputAmount = void 0;
1920
+ outputAmount = void 0;
1921
+ if (!(tradeType === TradeType.EXACT_INPUT)) {
1922
+ _context4.n = 6;
1923
+ break;
1924
+ }
1925
+ !amount.currency.equals(route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
1926
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1927
+ amounts[0] = CurrencyAmount.fromFractionalAmount(route.input.wrapped, amount.numerator, amount.denominator);
1928
+ i = 0;
1929
+ case 2:
1930
+ if (!(i < route.tokenPath.length - 1)) {
1931
+ _context4.n = 5;
1932
+ break;
1933
+ }
1934
+ pool = route.pools[i];
1935
+ _context4.n = 3;
1936
+ return pool.getOutputAmount(amounts[i]);
1937
+ case 3:
1938
+ _yield$pool$getOutput2 = _context4.v;
1939
+ _outputAmount2 = _yield$pool$getOutput2[0];
1940
+ amounts[i + 1] = _outputAmount2;
1941
+ case 4:
1942
+ i++;
1943
+ _context4.n = 2;
1944
+ break;
1945
+ case 5:
1946
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amounts[amounts.length - 1].numerator, amounts[amounts.length - 1].denominator);
1947
+ _context4.n = 11;
1948
+ break;
1949
+ case 6:
1950
+ !amount.currency.equals(route.output) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
1951
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1952
+ amounts[amounts.length - 1] = CurrencyAmount.fromFractionalAmount(route.output.wrapped, amount.numerator, amount.denominator);
1953
+ _i2 = route.tokenPath.length - 1;
1954
+ case 7:
1955
+ if (!(_i2 > 0)) {
1956
+ _context4.n = 10;
1957
+ break;
1958
+ }
1959
+ _pool2 = route.pools[_i2 - 1];
1960
+ _context4.n = 8;
1961
+ return _pool2.getInputAmount(amounts[_i2]);
1962
+ case 8:
1963
+ _yield$_pool2$getInpu = _context4.v;
1964
+ _inputAmount2 = _yield$_pool2$getInpu[0];
1965
+ amounts[_i2 - 1] = _inputAmount2;
1966
+ case 9:
1967
+ _i2--;
1968
+ _context4.n = 7;
1969
+ break;
1970
+ case 10:
1971
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
1972
+ case 11:
1973
+ populatedRoutes.push({
1974
+ route: route,
1975
+ inputAmount: inputAmount,
1976
+ outputAmount: outputAmount
1977
+ });
1978
+ case 12:
1979
+ _context4.n = 1;
1980
+ break;
1981
+ case 13:
1982
+ return _context4.a(2, new Trade({
1983
+ routes: populatedRoutes,
1984
+ tradeType: tradeType
1985
+ }));
1986
+ }
1987
+ }, _callee4);
1988
+ }));
1989
+ function fromRoutes(_x8, _x9) {
1990
+ return _fromRoutes.apply(this, arguments);
1991
+ }
1992
+ return fromRoutes;
1993
+ }()
1994
+ /**
1995
+ * Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade
1996
+ * elsewhere and do not have any tick data
1997
+ * @template TInput The input token, either Ether or an ERC-20
1998
+ * @template TOutput The output token, either Ether or an ERC-20
1999
+ * @template TTradeType The type of the trade, either exact in or exact out
2000
+ * @param constructorArguments The arguments passed to the trade constructor
2001
+ * @returns The unchecked trade
2002
+ */
2003
+ ;
2004
+ Trade.createUncheckedTrade = function createUncheckedTrade(constructorArguments) {
2005
+ return new Trade(_extends({}, constructorArguments, {
2006
+ routes: [{
2007
+ inputAmount: constructorArguments.inputAmount,
2008
+ outputAmount: constructorArguments.outputAmount,
2009
+ route: constructorArguments.route
2010
+ }]
2011
+ }));
2012
+ }
2013
+ /**
2014
+ * Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade
2015
+ * elsewhere and do not have any tick data
2016
+ * @template TInput The input token, either Ether or an ERC-20
2017
+ * @template TOutput The output token, either Ether or an ERC-20
2018
+ * @template TTradeType The type of the trade, either exact in or exact out
2019
+ * @param constructorArguments The arguments passed to the trade constructor
2020
+ * @returns The unchecked trade
2021
+ */;
2022
+ Trade.createUncheckedTradeWithMultipleRoutes = function createUncheckedTradeWithMultipleRoutes(constructorArguments) {
2023
+ return new Trade(constructorArguments);
2024
+ }
2025
+ /**
2026
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
2027
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
2028
+ * @returns The amount out
2029
+ */;
2030
+ var _proto = Trade.prototype;
2031
+ _proto.minimumAmountOut = function minimumAmountOut(slippageTolerance, amountOut) {
2032
+ if (amountOut === void 0) {
2033
+ amountOut = this.outputAmount;
2034
+ }
2035
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
2036
+ if (this.tradeType === TradeType.EXACT_OUTPUT) {
2037
+ return amountOut;
2038
+ } else {
2039
+ var slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
2040
+ return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
2041
+ }
2042
+ }
2043
+ /**
2044
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
2045
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
2046
+ * @returns The amount in
2047
+ */;
2048
+ _proto.maximumAmountIn = function maximumAmountIn(slippageTolerance, amountIn) {
2049
+ if (amountIn === void 0) {
2050
+ amountIn = this.inputAmount;
2051
+ }
2052
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
2053
+ if (this.tradeType === TradeType.EXACT_INPUT) {
2054
+ return amountIn;
2055
+ } else {
2056
+ var slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
2057
+ return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
2058
+ }
2059
+ }
2060
+ /**
2061
+ * Return the execution price after accounting for slippage tolerance
2062
+ * @param slippageTolerance the allowed tolerated slippage
2063
+ * @returns The execution price
2064
+ */;
2065
+ _proto.worstExecutionPrice = function worstExecutionPrice(slippageTolerance) {
2066
+ return new Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
2067
+ }
2068
+ /**
2069
+ * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
2070
+ * amount to an output token, making at most `maxHops` hops.
2071
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
2072
+ * the amount in among multiple routes.
2073
+ * @param pools the pools to consider in finding the best trade
2074
+ * @param nextAmountIn exact amount of input currency to spend
2075
+ * @param currencyOut the desired currency out
2076
+ * @param maxNumResults maximum number of results to return
2077
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
2078
+ * @param currentPools used in recursion; the current list of pools
2079
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
2080
+ * @param bestTrades used in recursion; the current list of best trades
2081
+ * @returns The exact in trade
2082
+ */;
2083
+ Trade.bestTradeExactIn =
2084
+ /*#__PURE__*/
2085
+ function () {
2086
+ var _bestTradeExactIn = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(pools, currencyAmountIn, currencyOut, _temp,
2087
+ // used in recursion.
2088
+ currentPools, nextAmountIn, bestTrades) {
2089
+ var _ref5, _ref5$maxNumResults, maxNumResults, _ref5$maxHops, maxHops, amountIn, tokenOut, i, pool, amountOut, _yield$pool$getOutput3, poolsExcludingThisPool, _t, _t2, _t3;
2090
+ return _regenerator().w(function (_context5) {
2091
+ while (1) switch (_context5.p = _context5.n) {
2092
+ case 0:
2093
+ _ref5 = _temp === void 0 ? {} : _temp, _ref5$maxNumResults = _ref5.maxNumResults, maxNumResults = _ref5$maxNumResults === void 0 ? 3 : _ref5$maxNumResults, _ref5$maxHops = _ref5.maxHops, maxHops = _ref5$maxHops === void 0 ? 3 : _ref5$maxHops;
2094
+ if (currentPools === void 0) {
2095
+ currentPools = [];
2096
+ }
2097
+ if (nextAmountIn === void 0) {
2098
+ nextAmountIn = currencyAmountIn;
2099
+ }
2100
+ if (bestTrades === void 0) {
2101
+ bestTrades = [];
2102
+ }
2103
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
2104
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
2105
+ !(currencyAmountIn === nextAmountIn || currentPools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
2106
+ amountIn = nextAmountIn.wrapped;
2107
+ tokenOut = currencyOut.wrapped;
2108
+ i = 0;
2109
+ case 1:
2110
+ if (!(i < pools.length)) {
2111
+ _context5.n = 11;
2112
+ break;
2113
+ }
2114
+ pool = pools[i]; // pool irrelevant
2115
+ if (!(!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency))) {
2116
+ _context5.n = 2;
2117
+ break;
2118
+ }
2119
+ return _context5.a(3, 10);
2120
+ case 2:
2121
+ amountOut = void 0;
2122
+ _context5.p = 3;
2123
+ _context5.n = 4;
2124
+ return pool.getOutputAmount(amountIn);
2125
+ case 4:
2126
+ _yield$pool$getOutput3 = _context5.v;
2127
+ amountOut = _yield$pool$getOutput3[0];
2128
+ _context5.n = 7;
2129
+ break;
2130
+ case 5:
2131
+ _context5.p = 5;
2132
+ _t = _context5.v;
2133
+ if (!_t.isInsufficientInputAmountError) {
2134
+ _context5.n = 6;
2135
+ break;
2136
+ }
2137
+ return _context5.a(3, 10);
2138
+ case 6:
2139
+ throw _t;
2140
+ case 7:
2141
+ if (!(amountOut.currency.isToken && amountOut.currency.equals(tokenOut))) {
2142
+ _context5.n = 9;
2143
+ break;
2144
+ }
2145
+ _t2 = sortedInsert;
2146
+ _t3 = bestTrades;
2147
+ _context5.n = 8;
2148
+ return Trade.fromRoute(new Route([].concat(currentPools, [pool]), currencyAmountIn.currency, currencyOut), currencyAmountIn, TradeType.EXACT_INPUT);
2149
+ case 8:
2150
+ _t2(_t3, _context5.v, maxNumResults, tradeComparator);
2151
+ _context5.n = 10;
2152
+ break;
2153
+ case 9:
2154
+ if (!(maxHops > 1 && pools.length > 1)) {
2155
+ _context5.n = 10;
2156
+ break;
2157
+ }
2158
+ poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length)); // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops
2159
+ _context5.n = 10;
2160
+ return Trade.bestTradeExactIn(poolsExcludingThisPool, currencyAmountIn, currencyOut, {
2161
+ maxNumResults: maxNumResults,
2162
+ maxHops: maxHops - 1
2163
+ }, [].concat(currentPools, [pool]), amountOut, bestTrades);
2164
+ case 10:
2165
+ i++;
2166
+ _context5.n = 1;
2167
+ break;
2168
+ case 11:
2169
+ return _context5.a(2, bestTrades);
2170
+ }
2171
+ }, _callee5, null, [[3, 5]]);
2172
+ }));
2173
+ function bestTradeExactIn(_x0, _x1, _x10, _x11, _x12, _x13, _x14) {
2174
+ return _bestTradeExactIn.apply(this, arguments);
2175
+ }
2176
+ return bestTradeExactIn;
2177
+ }()
2178
+ /**
2179
+ * similar to the above method but instead targets a fixed output amount
2180
+ * given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
2181
+ * to an output token amount, making at most `maxHops` hops
2182
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
2183
+ * the amount in among multiple routes.
2184
+ * @param pools the pools to consider in finding the best trade
2185
+ * @param currencyIn the currency to spend
2186
+ * @param currencyAmountOut the desired currency amount out
2187
+ * @param nextAmountOut the exact amount of currency out
2188
+ * @param maxNumResults maximum number of results to return
2189
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
2190
+ * @param currentPools used in recursion; the current list of pools
2191
+ * @param bestTrades used in recursion; the current list of best trades
2192
+ * @returns The exact out trade
2193
+ */
2194
+ ;
2195
+ Trade.bestTradeExactOut =
2196
+ /*#__PURE__*/
2197
+ function () {
2198
+ var _bestTradeExactOut = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(pools, currencyIn, currencyAmountOut, _temp2,
2199
+ // used in recursion.
2200
+ currentPools, nextAmountOut, bestTrades) {
2201
+ var _ref6, _ref6$maxNumResults, maxNumResults, _ref6$maxHops, maxHops, amountOut, tokenIn, i, pool, amountIn, _yield$pool$getInputA, poolsExcludingThisPool, _t4, _t5, _t6;
2202
+ return _regenerator().w(function (_context6) {
2203
+ while (1) switch (_context6.p = _context6.n) {
2204
+ case 0:
2205
+ _ref6 = _temp2 === void 0 ? {} : _temp2, _ref6$maxNumResults = _ref6.maxNumResults, maxNumResults = _ref6$maxNumResults === void 0 ? 3 : _ref6$maxNumResults, _ref6$maxHops = _ref6.maxHops, maxHops = _ref6$maxHops === void 0 ? 3 : _ref6$maxHops;
2206
+ if (currentPools === void 0) {
2207
+ currentPools = [];
2208
+ }
2209
+ if (nextAmountOut === void 0) {
2210
+ nextAmountOut = currencyAmountOut;
2211
+ }
2212
+ if (bestTrades === void 0) {
2213
+ bestTrades = [];
2214
+ }
2215
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
2216
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
2217
+ !(currencyAmountOut === nextAmountOut || currentPools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
2218
+ amountOut = nextAmountOut.wrapped;
2219
+ tokenIn = currencyIn.wrapped;
2220
+ i = 0;
2221
+ case 1:
2222
+ if (!(i < pools.length)) {
2223
+ _context6.n = 11;
2224
+ break;
2225
+ }
2226
+ pool = pools[i]; // pool irrelevant
2227
+ if (!(!pool.token0.equals(amountOut.currency) && !pool.token1.equals(amountOut.currency))) {
2228
+ _context6.n = 2;
2229
+ break;
2230
+ }
2231
+ return _context6.a(3, 10);
2232
+ case 2:
2233
+ amountIn = void 0;
2234
+ _context6.p = 3;
2235
+ _context6.n = 4;
2236
+ return pool.getInputAmount(amountOut);
2237
+ case 4:
2238
+ _yield$pool$getInputA = _context6.v;
2239
+ amountIn = _yield$pool$getInputA[0];
2240
+ _context6.n = 7;
2241
+ break;
2242
+ case 5:
2243
+ _context6.p = 5;
2244
+ _t4 = _context6.v;
2245
+ if (!_t4.isInsufficientReservesError) {
2246
+ _context6.n = 6;
2247
+ break;
2248
+ }
2249
+ return _context6.a(3, 10);
2250
+ case 6:
2251
+ throw _t4;
2252
+ case 7:
2253
+ if (!amountIn.currency.equals(tokenIn)) {
2254
+ _context6.n = 9;
2255
+ break;
2256
+ }
2257
+ _t5 = sortedInsert;
2258
+ _t6 = bestTrades;
2259
+ _context6.n = 8;
2260
+ return Trade.fromRoute(new Route([pool].concat(currentPools), currencyIn, currencyAmountOut.currency), currencyAmountOut, TradeType.EXACT_OUTPUT);
2261
+ case 8:
2262
+ _t5(_t6, _context6.v, maxNumResults, tradeComparator);
2263
+ _context6.n = 10;
2264
+ break;
2265
+ case 9:
2266
+ if (!(maxHops > 1 && pools.length > 1)) {
2267
+ _context6.n = 10;
2268
+ break;
2269
+ }
2270
+ poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length)); // otherwise, consider all the other paths that arrive at this token as long as we have not exceeded maxHops
2271
+ _context6.n = 10;
2272
+ return Trade.bestTradeExactOut(poolsExcludingThisPool, currencyIn, currencyAmountOut, {
2273
+ maxNumResults: maxNumResults,
2274
+ maxHops: maxHops - 1
2275
+ }, [pool].concat(currentPools), amountIn, bestTrades);
2276
+ case 10:
2277
+ i++;
2278
+ _context6.n = 1;
2279
+ break;
2280
+ case 11:
2281
+ return _context6.a(2, bestTrades);
2282
+ }
2283
+ }, _callee6, null, [[3, 5]]);
2284
+ }));
2285
+ function bestTradeExactOut(_x15, _x16, _x17, _x18, _x19, _x20, _x21) {
2286
+ return _bestTradeExactOut.apply(this, arguments);
2287
+ }
2288
+ return bestTradeExactOut;
2289
+ }();
2290
+ return _createClass(Trade, [{
2291
+ key: "route",
2292
+ get: function get() {
2293
+ !(this.swaps.length === 1) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MULTIPLE_ROUTES') : invariant(false) : void 0;
2294
+ return this.swaps[0].route;
2295
+ }
2296
+ /**
2297
+ * The input amount for the trade assuming no slippage.
2298
+ */
2299
+ }, {
2300
+ key: "inputAmount",
2301
+ get: function get() {
2302
+ if (this._inputAmount) {
2303
+ return this._inputAmount;
2304
+ }
2305
+ var inputCurrency = this.swaps[0].inputAmount.currency;
2306
+ var totalInputFromRoutes = this.swaps.map(function (_ref7) {
2307
+ var inputAmount = _ref7.inputAmount;
2308
+ return inputAmount;
2309
+ }).reduce(function (total, cur) {
2310
+ return total.add(cur);
2311
+ }, CurrencyAmount.fromRawAmount(inputCurrency, 0));
2312
+ this._inputAmount = totalInputFromRoutes;
2313
+ return this._inputAmount;
2314
+ }
2315
+ /**
2316
+ * The output amount for the trade assuming no slippage.
2317
+ */
2318
+ }, {
2319
+ key: "outputAmount",
2320
+ get: function get() {
2321
+ if (this._outputAmount) {
2322
+ return this._outputAmount;
2323
+ }
2324
+ var outputCurrency = this.swaps[0].outputAmount.currency;
2325
+ var totalOutputFromRoutes = this.swaps.map(function (_ref8) {
2326
+ var outputAmount = _ref8.outputAmount;
2327
+ return outputAmount;
2328
+ }).reduce(function (total, cur) {
2329
+ return total.add(cur);
2330
+ }, CurrencyAmount.fromRawAmount(outputCurrency, 0));
2331
+ this._outputAmount = totalOutputFromRoutes;
2332
+ return this._outputAmount;
2333
+ }
2334
+ /**
2335
+ * The price expressed in terms of output amount/input amount.
2336
+ */
2337
+ }, {
2338
+ key: "executionPrice",
2339
+ get: function get() {
2340
+ var _this$_executionPrice;
2341
+ return (_this$_executionPrice = this._executionPrice) != null ? _this$_executionPrice : this._executionPrice = new Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
2342
+ }
2343
+ /**
2344
+ * Returns the percent difference between the route's mid price and the price impact
2345
+ */
2346
+ }, {
2347
+ key: "priceImpact",
2348
+ get: function get() {
2349
+ if (this._priceImpact) {
2350
+ return this._priceImpact;
2351
+ }
2352
+ var spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0);
2353
+ for (var _iterator4 = _createForOfIteratorHelperLoose(this.swaps), _step4; !(_step4 = _iterator4()).done;) {
2354
+ var _step4$value = _step4.value,
2355
+ route = _step4$value.route,
2356
+ inputAmount = _step4$value.inputAmount;
2357
+ var midPrice = route.midPrice;
2358
+ spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount));
2359
+ }
2360
+ var priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount);
2361
+ this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator);
2362
+ return this._priceImpact;
2363
+ }
2364
+ }]);
2365
+ }();
2366
+
2367
+ var Multicall = /*#__PURE__*/function () {
2368
+ /**
2369
+ * Cannot be constructed.
2370
+ */
2371
+ function Multicall() {}
2372
+ Multicall.encodeMulticall = function encodeMulticall(calldatas) {
2373
+ if (!Array.isArray(calldatas)) {
2374
+ calldatas = [calldatas];
2375
+ }
2376
+ return calldatas.length === 1 ? calldatas[0] : Multicall.INTERFACE.encodeFunctionData('multicall', [calldatas]);
2377
+ };
2378
+ Multicall.decodeMulticall = function decodeMulticall(multicall) {
2379
+ return Multicall.INTERFACE.decodeFunctionData('multicall', multicall).data;
2380
+ };
2381
+ return Multicall;
2382
+ }();
2383
+ Multicall.INTERFACE = /*#__PURE__*/new Interface(IMulticall.abi);
2384
+
2385
+ function isAllowedPermit(permitOptions) {
2386
+ return 'nonce' in permitOptions;
2387
+ }
2388
+ var SelfPermit = /*#__PURE__*/function () {
2389
+ /**
2390
+ * Cannot be constructed.
2391
+ */
2392
+ function SelfPermit() {}
2393
+ SelfPermit.encodePermit = function encodePermit(token, options) {
2394
+ return isAllowedPermit(options) ? SelfPermit.INTERFACE.encodeFunctionData('selfPermitAllowed', [token.address, toHex(options.nonce), toHex(options.expiry), options.v, options.r, options.s]) : SelfPermit.INTERFACE.encodeFunctionData('selfPermit', [token.address, toHex(options.amount), toHex(options.deadline), options.v, options.r, options.s]);
2395
+ };
2396
+ return SelfPermit;
2397
+ }();
2398
+ SelfPermit.INTERFACE = /*#__PURE__*/new Interface(ISelfPermit.abi);
2399
+
2400
+ var Payments = /*#__PURE__*/function () {
2401
+ /**
2402
+ * Cannot be constructed.
2403
+ */
2404
+ function Payments() {}
2405
+ Payments.encodeFeeBips = function encodeFeeBips(fee) {
2406
+ return toHex(fee.multiply(10000).quotient);
2407
+ };
2408
+ Payments.encodeUnwrapWETH9 = function encodeUnwrapWETH9(amountMinimum, recipient, feeOptions) {
2409
+ recipient = validateAndParseAddress(recipient);
2410
+ if (!!feeOptions) {
2411
+ var feeBips = this.encodeFeeBips(feeOptions.fee);
2412
+ var feeRecipient = validateAndParseAddress(feeOptions.recipient);
2413
+ return Payments.INTERFACE.encodeFunctionData('unwrapWETH9WithFee', [toHex(amountMinimum), recipient, feeBips, feeRecipient]);
2414
+ } else {
2415
+ return Payments.INTERFACE.encodeFunctionData('unwrapWETH9', [toHex(amountMinimum), recipient]);
2416
+ }
2417
+ };
2418
+ Payments.encodeSweepToken = function encodeSweepToken(token, amountMinimum, recipient, feeOptions) {
2419
+ recipient = validateAndParseAddress(recipient);
2420
+ if (!!feeOptions) {
2421
+ var feeBips = this.encodeFeeBips(feeOptions.fee);
2422
+ var feeRecipient = validateAndParseAddress(feeOptions.recipient);
2423
+ return Payments.INTERFACE.encodeFunctionData('sweepTokenWithFee', [token.address, toHex(amountMinimum), recipient, feeBips, feeRecipient]);
2424
+ } else {
2425
+ return Payments.INTERFACE.encodeFunctionData('sweepToken', [token.address, toHex(amountMinimum), recipient]);
2426
+ }
2427
+ };
2428
+ Payments.encodeRefundETH = function encodeRefundETH() {
2429
+ return Payments.INTERFACE.encodeFunctionData('refundETH');
2430
+ };
2431
+ return Payments;
2432
+ }();
2433
+ Payments.INTERFACE = /*#__PURE__*/new Interface(IPeripheryPaymentsWithFee.abi);
2434
+
2435
+ var _excluded = ["expectedCurrencyOwed0", "expectedCurrencyOwed1"];
2436
+ var MaxUint128 = /*#__PURE__*/toHex(/*#__PURE__*/JSBI.subtract(/*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(128)), /*#__PURE__*/JSBI.BigInt(1)));
2437
+ // type guard
2438
+ function isMint(options) {
2439
+ return Object.keys(options).some(function (k) {
2440
+ return k === 'recipient';
2441
+ });
2442
+ }
2443
+ var NFT_PERMIT_TYPES = {
2444
+ Permit: [{
2445
+ name: 'spender',
2446
+ type: 'address'
2447
+ }, {
2448
+ name: 'tokenId',
2449
+ type: 'uint256'
2450
+ }, {
2451
+ name: 'nonce',
2452
+ type: 'uint256'
2453
+ }, {
2454
+ name: 'deadline',
2455
+ type: 'uint256'
2456
+ }]
2457
+ };
2458
+ var NonfungiblePositionManager = /*#__PURE__*/function () {
2459
+ /**
2460
+ * Cannot be constructed.
2461
+ */
2462
+ function NonfungiblePositionManager() {}
2463
+ NonfungiblePositionManager.encodeCreate = function encodeCreate(pool) {
2464
+ return NonfungiblePositionManager.INTERFACE.encodeFunctionData('createAndInitializePoolIfNecessary', [pool.token0.address, pool.token1.address, pool.fee, toHex(pool.sqrtRatioX96)]);
2465
+ };
2466
+ NonfungiblePositionManager.createCallParameters = function createCallParameters(pool) {
2467
+ return {
2468
+ calldata: this.encodeCreate(pool),
2469
+ value: toHex(0)
2470
+ };
2471
+ };
2472
+ NonfungiblePositionManager.addCallParameters = function addCallParameters(position, options) {
2473
+ !JSBI.greaterThan(position.liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO_LIQUIDITY') : invariant(false) : void 0;
2474
+ var calldatas = [];
2475
+ // get amounts
2476
+ var _position$mintAmounts = position.mintAmounts,
2477
+ amount0Desired = _position$mintAmounts.amount0,
2478
+ amount1Desired = _position$mintAmounts.amount1;
2479
+ // adjust for slippage
2480
+ var minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
2481
+ var amount0Min = toHex(minimumAmounts.amount0);
2482
+ var amount1Min = toHex(minimumAmounts.amount1);
2483
+ var deadline = toHex(options.deadline);
2484
+ // create pool if needed
2485
+ if (isMint(options) && options.createPool) {
2486
+ calldatas.push(this.encodeCreate(position.pool));
2487
+ }
2488
+ // permits if necessary
2489
+ if (options.token0Permit) {
2490
+ calldatas.push(SelfPermit.encodePermit(position.pool.token0, options.token0Permit));
2491
+ }
2492
+ if (options.token1Permit) {
2493
+ calldatas.push(SelfPermit.encodePermit(position.pool.token1, options.token1Permit));
2494
+ }
2495
+ // mint
2496
+ if (isMint(options)) {
2497
+ var recipient = validateAndParseAddress(options.recipient);
2498
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('mint', [{
2499
+ token0: position.pool.token0.address,
2500
+ token1: position.pool.token1.address,
2501
+ fee: position.pool.fee,
2502
+ tickLower: position.tickLower,
2503
+ tickUpper: position.tickUpper,
2504
+ amount0Desired: toHex(amount0Desired),
2505
+ amount1Desired: toHex(amount1Desired),
2506
+ amount0Min: amount0Min,
2507
+ amount1Min: amount1Min,
2508
+ recipient: recipient,
2509
+ deadline: deadline
2510
+ }]));
2511
+ } else {
2512
+ // increase
2513
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('increaseLiquidity', [{
2514
+ tokenId: toHex(options.tokenId),
2515
+ amount0Desired: toHex(amount0Desired),
2516
+ amount1Desired: toHex(amount1Desired),
2517
+ amount0Min: amount0Min,
2518
+ amount1Min: amount1Min,
2519
+ deadline: deadline
2520
+ }]));
2521
+ }
2522
+ var value = toHex(0);
2523
+ if (options.useNative) {
2524
+ var wrapped = options.useNative.wrapped;
2525
+ !(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NO_WETH') : invariant(false) : void 0;
2526
+ var wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired;
2527
+ // we only need to refund if we're actually sending ETH
2528
+ if (JSBI.greaterThan(wrappedValue, ZERO)) {
2529
+ calldatas.push(Payments.encodeRefundETH());
2530
+ }
2531
+ value = toHex(wrappedValue);
2532
+ }
2533
+ return {
2534
+ calldata: Multicall.encodeMulticall(calldatas),
2535
+ value: value
2536
+ };
2537
+ };
2538
+ NonfungiblePositionManager.encodeCollect = function encodeCollect(options) {
2539
+ var calldatas = [];
2540
+ var tokenId = toHex(options.tokenId);
2541
+ var involvesETH = options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative;
2542
+ var recipient = validateAndParseAddress(options.recipient);
2543
+ // collect
2544
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('collect', [{
2545
+ tokenId: tokenId,
2546
+ recipient: involvesETH ? ADDRESS_ZERO : recipient,
2547
+ amount0Max: MaxUint128,
2548
+ amount1Max: MaxUint128
2549
+ }]));
2550
+ if (involvesETH) {
2551
+ var ethAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed0.quotient : options.expectedCurrencyOwed1.quotient;
2552
+ var token = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed1.currency : options.expectedCurrencyOwed0.currency;
2553
+ var tokenAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed1.quotient : options.expectedCurrencyOwed0.quotient;
2554
+ calldatas.push(Payments.encodeUnwrapWETH9(ethAmount, recipient));
2555
+ calldatas.push(Payments.encodeSweepToken(token, tokenAmount, recipient));
2556
+ }
2557
+ return calldatas;
2558
+ };
2559
+ NonfungiblePositionManager.collectCallParameters = function collectCallParameters(options) {
2560
+ var calldatas = NonfungiblePositionManager.encodeCollect(options);
2561
+ return {
2562
+ calldata: Multicall.encodeMulticall(calldatas),
2563
+ value: toHex(0)
2564
+ };
2565
+ }
2566
+ /**
2567
+ * Produces the calldata for completely or partially exiting a position
2568
+ * @param position The position to exit
2569
+ * @param options Additional information necessary for generating the calldata
2570
+ * @returns The call parameters
2571
+ */;
2572
+ NonfungiblePositionManager.removeCallParameters = function removeCallParameters(position, options) {
2573
+ var calldatas = [];
2574
+ var deadline = toHex(options.deadline);
2575
+ var tokenId = toHex(options.tokenId);
2576
+ // construct a partial position with a percentage of liquidity
2577
+ var partialPosition = new Position({
2578
+ pool: position.pool,
2579
+ liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
2580
+ tickLower: position.tickLower,
2581
+ tickUpper: position.tickUpper
2582
+ });
2583
+ !JSBI.greaterThan(partialPosition.liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO_LIQUIDITY') : invariant(false) : void 0;
2584
+ // slippage-adjusted underlying amounts
2585
+ var _partialPosition$burn = partialPosition.burnAmountsWithSlippage(options.slippageTolerance),
2586
+ amount0Min = _partialPosition$burn.amount0,
2587
+ amount1Min = _partialPosition$burn.amount1;
2588
+ if (options.permit) {
2589
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('permit', [validateAndParseAddress(options.permit.spender), tokenId, toHex(options.permit.deadline), options.permit.v, options.permit.r, options.permit.s]));
2590
+ }
2591
+ // remove liquidity
2592
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('decreaseLiquidity', [{
2593
+ tokenId: tokenId,
2594
+ liquidity: toHex(partialPosition.liquidity),
2595
+ amount0Min: toHex(amount0Min),
2596
+ amount1Min: toHex(amount1Min),
2597
+ deadline: deadline
2598
+ }]));
2599
+ var _options$collectOptio = options.collectOptions,
2600
+ expectedCurrencyOwed0 = _options$collectOptio.expectedCurrencyOwed0,
2601
+ expectedCurrencyOwed1 = _options$collectOptio.expectedCurrencyOwed1,
2602
+ rest = _objectWithoutPropertiesLoose(_options$collectOptio, _excluded);
2603
+ calldatas.push.apply(calldatas, NonfungiblePositionManager.encodeCollect(_extends({
2604
+ tokenId: toHex(options.tokenId),
2605
+ // add the underlying value to the expected currency already owed
2606
+ expectedCurrencyOwed0: expectedCurrencyOwed0.add(CurrencyAmount.fromRawAmount(expectedCurrencyOwed0.currency, amount0Min)),
2607
+ expectedCurrencyOwed1: expectedCurrencyOwed1.add(CurrencyAmount.fromRawAmount(expectedCurrencyOwed1.currency, amount1Min))
2608
+ }, rest)));
2609
+ if (options.liquidityPercentage.equalTo(ONE)) {
2610
+ if (options.burnToken) {
2611
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('burn', [tokenId]));
2612
+ }
2613
+ } else {
2614
+ !(options.burnToken !== true) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CANNOT_BURN') : invariant(false) : void 0;
2615
+ }
2616
+ return {
2617
+ calldata: Multicall.encodeMulticall(calldatas),
2618
+ value: toHex(0)
2619
+ };
2620
+ };
2621
+ NonfungiblePositionManager.safeTransferFromParameters = function safeTransferFromParameters(options) {
2622
+ var recipient = validateAndParseAddress(options.recipient);
2623
+ var sender = validateAndParseAddress(options.sender);
2624
+ var calldata;
2625
+ if (options.data) {
2626
+ calldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256,bytes)', [sender, recipient, toHex(options.tokenId), options.data]);
2627
+ } else {
2628
+ calldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256)', [sender, recipient, toHex(options.tokenId)]);
2629
+ }
2630
+ return {
2631
+ calldata: calldata,
2632
+ value: toHex(0)
2633
+ };
2634
+ }
2635
+ // Prepare the params for an EIP712 signTypedData request
2636
+ ;
2637
+ NonfungiblePositionManager.getPermitData = function getPermitData(permit, positionManagerAddress, chainId) {
2638
+ return {
2639
+ domain: {
2640
+ name: 'Uniswap V3 Positions NFT-V1',
2641
+ chainId: chainId,
2642
+ version: '1',
2643
+ verifyingContract: positionManagerAddress
2644
+ },
2645
+ types: NFT_PERMIT_TYPES,
2646
+ values: permit
2647
+ };
2648
+ };
2649
+ return NonfungiblePositionManager;
2650
+ }();
2651
+ NonfungiblePositionManager.INTERFACE = /*#__PURE__*/new Interface(INonfungiblePositionManager.abi);
2652
+
2653
+ /**
2654
+ * Represents the Uniswap V3 QuoterV1 contract with a method for returning the formatted
2655
+ * calldata needed to call the quoter contract.
2656
+ */
2657
+ var SwapQuoter = /*#__PURE__*/function () {
2658
+ function SwapQuoter() {}
2659
+ /**
2660
+ * Produces the on-chain method name of the appropriate function within QuoterV2,
2661
+ * and the relevant hex encoded parameters.
2662
+ * @template TInput The input token, either Ether or an ERC-20
2663
+ * @template TOutput The output token, either Ether or an ERC-20
2664
+ * @param route The swap route, a list of pools through which a swap can occur
2665
+ * @param amount The amount of the quote, either an amount in, or an amount out
2666
+ * @param tradeType The trade type, either exact input or exact output
2667
+ * @param options The optional params including price limit and Quoter contract switch
2668
+ * @returns The formatted calldata
2669
+ */
2670
+ SwapQuoter.quoteCallParameters = function quoteCallParameters(route, amount, tradeType, options) {
2671
+ if (options === void 0) {
2672
+ options = {};
2673
+ }
2674
+ var singleHop = route.pools.length === 1;
2675
+ var quoteAmount = toHex(amount.quotient);
2676
+ var calldata;
2677
+ var swapInterface = options.useQuoterV2 ? this.V2INTERFACE : this.V1INTERFACE;
2678
+ if (singleHop) {
2679
+ var _options$sqrtPriceLim, _options;
2680
+ var baseQuoteParams = {
2681
+ tokenIn: route.tokenPath[0].address,
2682
+ tokenOut: route.tokenPath[1].address,
2683
+ fee: route.pools[0].fee,
2684
+ sqrtPriceLimitX96: toHex((_options$sqrtPriceLim = (_options = options) == null ? void 0 : _options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim : 0)
2685
+ };
2686
+ var v2QuoteParams = _extends({}, baseQuoteParams, tradeType === TradeType.EXACT_INPUT ? {
2687
+ amountIn: quoteAmount
2688
+ } : {
2689
+ amount: quoteAmount
2690
+ });
2691
+ var v1QuoteParams = [baseQuoteParams.tokenIn, baseQuoteParams.tokenOut, baseQuoteParams.fee, quoteAmount, baseQuoteParams.sqrtPriceLimitX96];
2692
+ var tradeTypeFunctionName = tradeType === TradeType.EXACT_INPUT ? 'quoteExactInputSingle' : 'quoteExactOutputSingle';
2693
+ calldata = swapInterface.encodeFunctionData(tradeTypeFunctionName, options.useQuoterV2 ? [v2QuoteParams] : v1QuoteParams);
2694
+ } else {
2695
+ var _options2;
2696
+ !(((_options2 = options) == null ? void 0 : _options2.sqrtPriceLimitX96) === undefined) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MULTIHOP_PRICE_LIMIT') : invariant(false) : void 0;
2697
+ var path = encodeRouteToPath(route, tradeType === TradeType.EXACT_OUTPUT);
2698
+ var _tradeTypeFunctionName = tradeType === TradeType.EXACT_INPUT ? 'quoteExactInput' : 'quoteExactOutput';
2699
+ calldata = swapInterface.encodeFunctionData(_tradeTypeFunctionName, [path, quoteAmount]);
2700
+ }
2701
+ return {
2702
+ calldata: calldata,
2703
+ value: toHex(0)
2704
+ };
2705
+ };
2706
+ return SwapQuoter;
2707
+ }();
2708
+ SwapQuoter.V1INTERFACE = /*#__PURE__*/new Interface(IQuoter.abi);
2709
+ SwapQuoter.V2INTERFACE = /*#__PURE__*/new Interface(IQuoterV2.abi);
2710
+
2711
+ var Staker = /*#__PURE__*/function () {
2712
+ function Staker() {}
2713
+ /**
2714
+ * To claim rewards, must unstake and then claim.
2715
+ * @param incentiveKey The unique identifier of a staking program.
2716
+ * @param options Options for producing the calldata to claim. Can't claim unless you unstake.
2717
+ * @returns The calldatas for 'unstakeToken' and 'claimReward'.
2718
+ */
2719
+ Staker.encodeClaim = function encodeClaim(incentiveKey, options) {
2720
+ var _options$amount;
2721
+ var calldatas = [];
2722
+ calldatas.push(Staker.INTERFACE.encodeFunctionData('unstakeToken', [this._encodeIncentiveKey(incentiveKey), toHex(options.tokenId)]));
2723
+ var recipient = validateAndParseAddress(options.recipient);
2724
+ var amount = (_options$amount = options.amount) != null ? _options$amount : 0;
2725
+ calldatas.push(Staker.INTERFACE.encodeFunctionData('claimReward', [incentiveKey.rewardToken.address, recipient, toHex(amount)]));
2726
+ return calldatas;
2727
+ }
2728
+ /**
2729
+ *
2730
+ * Note: A `tokenId` can be staked in many programs but to claim rewards and continue the program you must unstake, claim, and then restake.
2731
+ * @param incentiveKeys An IncentiveKey or array of IncentiveKeys that `tokenId` is staked in.
2732
+ * Input an array of IncentiveKeys to claim rewards for each program.
2733
+ * @param options ClaimOptions to specify tokenId, recipient, and amount wanting to collect.
2734
+ * Note that you can only specify one amount and one recipient across the various programs if you are collecting from multiple programs at once.
2735
+ * @returns
2736
+ */;
2737
+ Staker.collectRewards = function collectRewards(incentiveKeys, options) {
2738
+ incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
2739
+ var calldatas = [];
2740
+ for (var i = 0; i < incentiveKeys.length; i++) {
2741
+ // the unique program tokenId is staked in
2742
+ var incentiveKey = incentiveKeys[i];
2743
+ // unstakes and claims for the unique program
2744
+ calldatas = calldatas.concat(this.encodeClaim(incentiveKey, options));
2745
+ // re-stakes the position for the unique program
2746
+ calldatas.push(Staker.INTERFACE.encodeFunctionData('stakeToken', [this._encodeIncentiveKey(incentiveKey), toHex(options.tokenId)]));
2747
+ }
2748
+ return {
2749
+ calldata: Multicall.encodeMulticall(calldatas),
2750
+ value: toHex(0)
2751
+ };
2752
+ }
2753
+ /**
2754
+ *
2755
+ * @param incentiveKeys A list of incentiveKeys to unstake from. Should include all incentiveKeys (unique staking programs) that `options.tokenId` is staked in.
2756
+ * @param withdrawOptions Options for producing claim calldata and withdraw calldata. Can't withdraw without unstaking all programs for `tokenId`.
2757
+ * @returns Calldata for unstaking, claiming, and withdrawing.
2758
+ */;
2759
+ Staker.withdrawToken = function withdrawToken(incentiveKeys, withdrawOptions) {
2760
+ var calldatas = [];
2761
+ incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
2762
+ var claimOptions = {
2763
+ tokenId: withdrawOptions.tokenId,
2764
+ recipient: withdrawOptions.recipient,
2765
+ amount: withdrawOptions.amount
2766
+ };
2767
+ for (var i = 0; i < incentiveKeys.length; i++) {
2768
+ var incentiveKey = incentiveKeys[i];
2769
+ calldatas = calldatas.concat(this.encodeClaim(incentiveKey, claimOptions));
2770
+ }
2771
+ var owner = validateAndParseAddress(withdrawOptions.owner);
2772
+ calldatas.push(Staker.INTERFACE.encodeFunctionData('withdrawToken', [toHex(withdrawOptions.tokenId), owner, withdrawOptions.data ? withdrawOptions.data : toHex(0)]));
2773
+ return {
2774
+ calldata: Multicall.encodeMulticall(calldatas),
2775
+ value: toHex(0)
2776
+ };
2777
+ }
2778
+ /**
2779
+ *
2780
+ * @param incentiveKeys A single IncentiveKey or array of IncentiveKeys to be encoded and used in the data parameter in `safeTransferFrom`
2781
+ * @returns An IncentiveKey as a string
2782
+ */;
2783
+ Staker.encodeDeposit = function encodeDeposit(incentiveKeys) {
2784
+ incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
2785
+ var data;
2786
+ if (incentiveKeys.length > 1) {
2787
+ var keys = [];
2788
+ for (var i = 0; i < incentiveKeys.length; i++) {
2789
+ var incentiveKey = incentiveKeys[i];
2790
+ keys.push(this._encodeIncentiveKey(incentiveKey));
2791
+ }
2792
+ data = defaultAbiCoder.encode([Staker.INCENTIVE_KEY_ABI + "[]"], [keys]);
2793
+ } else {
2794
+ data = defaultAbiCoder.encode([Staker.INCENTIVE_KEY_ABI], [this._encodeIncentiveKey(incentiveKeys[0])]);
2795
+ }
2796
+ return data;
2797
+ }
2798
+ /**
2799
+ *
2800
+ * @param incentiveKey An `IncentiveKey` which represents a unique staking program.
2801
+ * @returns An encoded IncentiveKey to be read by ethers
2802
+ */;
2803
+ Staker._encodeIncentiveKey = function _encodeIncentiveKey(incentiveKey) {
2804
+ var _incentiveKey$pool = incentiveKey.pool,
2805
+ token0 = _incentiveKey$pool.token0,
2806
+ token1 = _incentiveKey$pool.token1,
2807
+ fee = _incentiveKey$pool.fee;
2808
+ var refundee = validateAndParseAddress(incentiveKey.refundee);
2809
+ return {
2810
+ rewardToken: incentiveKey.rewardToken.address,
2811
+ pool: Pool.getAddress(token0, token1, fee),
2812
+ startTime: toHex(incentiveKey.startTime),
2813
+ endTime: toHex(incentiveKey.endTime),
2814
+ refundee: refundee
2815
+ };
2816
+ };
2817
+ return Staker;
2818
+ }();
2819
+ Staker.INTERFACE = /*#__PURE__*/new Interface(IUniswapV3Staker.abi);
2820
+ Staker.INCENTIVE_KEY_ABI = 'tuple(address rewardToken, address pool, uint256 startTime, uint256 endTime, address refundee)';
2821
+
2822
+ /**
2823
+ * Represents the Uniswap V3 SwapRouter, and has static methods for helping execute trades.
2824
+ */
2825
+ var SwapRouter = /*#__PURE__*/function () {
2826
+ /**
2827
+ * Cannot be constructed.
2828
+ */
2829
+ function SwapRouter() {}
2830
+ /**
2831
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
2832
+ * @param trade to produce call parameters for
2833
+ * @param options options for the call parameters
2834
+ */
2835
+ SwapRouter.swapCallParameters = function swapCallParameters(trades, options) {
2836
+ if (!Array.isArray(trades)) {
2837
+ trades = [trades];
2838
+ }
2839
+ var sampleTrade = trades[0];
2840
+ var tokenIn = sampleTrade.inputAmount.currency.wrapped;
2841
+ var tokenOut = sampleTrade.outputAmount.currency.wrapped;
2842
+ // All trades should have the same starting and ending token.
2843
+ !trades.every(function (trade) {
2844
+ return trade.inputAmount.currency.wrapped.equals(tokenIn);
2845
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN_IN_DIFF') : invariant(false) : void 0;
2846
+ !trades.every(function (trade) {
2847
+ return trade.outputAmount.currency.wrapped.equals(tokenOut);
2848
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN_OUT_DIFF') : invariant(false) : void 0;
2849
+ var calldatas = [];
2850
+ var ZERO_IN = CurrencyAmount.fromRawAmount(trades[0].inputAmount.currency, 0);
2851
+ var ZERO_OUT = CurrencyAmount.fromRawAmount(trades[0].outputAmount.currency, 0);
2852
+ var totalAmountOut = trades.reduce(function (sum, trade) {
2853
+ return sum.add(trade.minimumAmountOut(options.slippageTolerance));
2854
+ }, ZERO_OUT);
2855
+ // flag for whether a refund needs to happen
2856
+ var mustRefund = sampleTrade.inputAmount.currency.isNative && sampleTrade.tradeType === TradeType.EXACT_OUTPUT;
2857
+ var inputIsNative = sampleTrade.inputAmount.currency.isNative;
2858
+ // flags for whether funds should be send first to the router
2859
+ var outputIsNative = sampleTrade.outputAmount.currency.isNative;
2860
+ var routerMustCustody = outputIsNative || !!options.fee;
2861
+ var totalValue = inputIsNative ? trades.reduce(function (sum, trade) {
2862
+ return sum.add(trade.maximumAmountIn(options.slippageTolerance));
2863
+ }, ZERO_IN) : ZERO_IN;
2864
+ // encode permit if necessary
2865
+ if (options.inputTokenPermit) {
2866
+ !sampleTrade.inputAmount.currency.isToken ? process.env.NODE_ENV !== "production" ? invariant(false, 'NON_TOKEN_PERMIT') : invariant(false) : void 0;
2867
+ calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency, options.inputTokenPermit));
2868
+ }
2869
+ var recipient = validateAndParseAddress(options.recipient);
2870
+ var deadline = toHex(options.deadline);
2871
+ for (var _iterator = _createForOfIteratorHelperLoose(trades), _step; !(_step = _iterator()).done;) {
2872
+ var trade = _step.value;
2873
+ for (var _iterator2 = _createForOfIteratorHelperLoose(trade.swaps), _step2; !(_step2 = _iterator2()).done;) {
2874
+ var _step2$value = _step2.value,
2875
+ route = _step2$value.route,
2876
+ inputAmount = _step2$value.inputAmount,
2877
+ outputAmount = _step2$value.outputAmount;
2878
+ var amountIn = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
2879
+ var amountOut = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient);
2880
+ // flag for whether the trade is single hop or not
2881
+ var singleHop = route.pools.length === 1;
2882
+ if (singleHop) {
2883
+ if (trade.tradeType === TradeType.EXACT_INPUT) {
2884
+ var _options$sqrtPriceLim;
2885
+ var exactInputSingleParams = {
2886
+ tokenIn: route.tokenPath[0].address,
2887
+ tokenOut: route.tokenPath[1].address,
2888
+ fee: route.pools[0].fee,
2889
+ recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
2890
+ deadline: deadline,
2891
+ amountIn: amountIn,
2892
+ amountOutMinimum: amountOut,
2893
+ sqrtPriceLimitX96: toHex((_options$sqrtPriceLim = options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim : 0)
2894
+ };
2895
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]));
2896
+ } else {
2897
+ var _options$sqrtPriceLim2;
2898
+ var exactOutputSingleParams = {
2899
+ tokenIn: route.tokenPath[0].address,
2900
+ tokenOut: route.tokenPath[1].address,
2901
+ fee: route.pools[0].fee,
2902
+ recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
2903
+ deadline: deadline,
2904
+ amountOut: amountOut,
2905
+ amountInMaximum: amountIn,
2906
+ sqrtPriceLimitX96: toHex((_options$sqrtPriceLim2 = options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim2 : 0)
2907
+ };
2908
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutputSingle', [exactOutputSingleParams]));
2909
+ }
2910
+ } else {
2911
+ !(options.sqrtPriceLimitX96 === undefined) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MULTIHOP_PRICE_LIMIT') : invariant(false) : void 0;
2912
+ var path = encodeRouteToPath(route, trade.tradeType === TradeType.EXACT_OUTPUT);
2913
+ if (trade.tradeType === TradeType.EXACT_INPUT) {
2914
+ var exactInputParams = {
2915
+ path: path,
2916
+ recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
2917
+ deadline: deadline,
2918
+ amountIn: amountIn,
2919
+ amountOutMinimum: amountOut
2920
+ };
2921
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]));
2922
+ } else {
2923
+ var exactOutputParams = {
2924
+ path: path,
2925
+ recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
2926
+ deadline: deadline,
2927
+ amountOut: amountOut,
2928
+ amountInMaximum: amountIn
2929
+ };
2930
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutput', [exactOutputParams]));
2931
+ }
2932
+ }
2933
+ }
2934
+ }
2935
+ // unwrap
2936
+ if (routerMustCustody) {
2937
+ if (!!options.fee) {
2938
+ if (outputIsNative) {
2939
+ calldatas.push(Payments.encodeUnwrapWETH9(totalAmountOut.quotient, recipient, options.fee));
2940
+ } else {
2941
+ calldatas.push(Payments.encodeSweepToken(sampleTrade.outputAmount.currency.wrapped, totalAmountOut.quotient, recipient, options.fee));
2942
+ }
2943
+ } else {
2944
+ calldatas.push(Payments.encodeUnwrapWETH9(totalAmountOut.quotient, recipient));
2945
+ }
2946
+ }
2947
+ // refund
2948
+ if (mustRefund) {
2949
+ calldatas.push(Payments.encodeRefundETH());
2950
+ }
2951
+ return {
2952
+ calldata: Multicall.encodeMulticall(calldatas),
2953
+ value: toHex(totalValue.quotient)
2954
+ };
2955
+ };
2956
+ return SwapRouter;
2957
+ }();
2958
+ SwapRouter.INTERFACE = /*#__PURE__*/new Interface(ISwapRouter.abi);
2959
+
2960
+ export { ADDRESS_ZERO, FACTORY_ADDRESS, FeeAmount, FullMath, LiquidityMath, Multicall, NoTickDataProvider, NonfungiblePositionManager, POOL_INIT_CODE_HASH, Payments, Pool, Position, PositionLibrary, Route, SelfPermit, SqrtPriceMath, Staker, SwapMath, SwapQuoter, SwapRouter, TICK_SPACINGS, Tick, TickLibrary, TickList, TickListDataProvider, TickMath, Trade, computePoolAddress, encodeRouteToPath, encodeSqrtRatioX96, isSorted, maxLiquidityForAmounts, mostSignificantBit, nearestUsableTick, poolInitCodeHash, priceToClosestTick, subIn256, tickToPrice, toHex, tradeComparator, v3Swap };
2961
+ //# sourceMappingURL=v3-sdk.esm.js.map