@juiceswapxyz/v3-sdk 0.1.4-beta.0 → 3.0.0

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