@huuduynvc/v3-sdk 3.24.1

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