@kayenfinance/v3-sdk 1.0.0-next.1

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