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