elephantswapv3-sdk 0.0.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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -0
  3. package/dist/constants.d.ts +18 -0
  4. package/dist/elephantswapv3-sdk.cjs.development.js +4147 -0
  5. package/dist/elephantswapv3-sdk.cjs.development.js.map +1 -0
  6. package/dist/elephantswapv3-sdk.cjs.production.min.js +2 -0
  7. package/dist/elephantswapv3-sdk.cjs.production.min.js.map +1 -0
  8. package/dist/elephantswapv3-sdk.esm.js +4109 -0
  9. package/dist/elephantswapv3-sdk.esm.js.map +1 -0
  10. package/dist/entities/index.d.ts +7 -0
  11. package/dist/entities/pool.d.ts +81 -0
  12. package/dist/entities/position.d.ts +131 -0
  13. package/dist/entities/route.d.ts +26 -0
  14. package/dist/entities/tick.d.ts +13 -0
  15. package/dist/entities/tickDataProvider.d.ts +31 -0
  16. package/dist/entities/tickListDataProvider.d.ts +15 -0
  17. package/dist/entities/trade.d.ts +220 -0
  18. package/dist/index.d.ts +10 -0
  19. package/dist/index.js +8 -0
  20. package/dist/internalConstants.d.ts +6 -0
  21. package/dist/multicall.d.ts +9 -0
  22. package/dist/nonfungiblePositionManager.d.ts +146 -0
  23. package/dist/payments.d.ts +24 -0
  24. package/dist/quoter.d.ts +37 -0
  25. package/dist/selfPermit.d.ts +25 -0
  26. package/dist/staker.d.ts +101 -0
  27. package/dist/swapRouter.d.ts +51 -0
  28. package/dist/utils/calldata.d.ts +20 -0
  29. package/dist/utils/computePoolAddress.d.ts +18 -0
  30. package/dist/utils/encodeRouteToPath.d.ts +8 -0
  31. package/dist/utils/encodeSqrtRatioX96.d.ts +9 -0
  32. package/dist/utils/fullMath.d.ts +8 -0
  33. package/dist/utils/index.d.ts +17 -0
  34. package/dist/utils/isSorted.d.ts +7 -0
  35. package/dist/utils/liquidityMath.d.ts +8 -0
  36. package/dist/utils/maxLiquidityForAmounts.d.ts +14 -0
  37. package/dist/utils/mostSignificantBit.d.ts +2 -0
  38. package/dist/utils/nearestUsableTick.d.ts +6 -0
  39. package/dist/utils/position.d.ts +8 -0
  40. package/dist/utils/priceTickConversions.d.ts +15 -0
  41. package/dist/utils/sqrtPriceMath.d.ts +13 -0
  42. package/dist/utils/swapMath.d.ts +9 -0
  43. package/dist/utils/tickLibrary.d.ts +14 -0
  44. package/dist/utils/tickList.d.ts +23 -0
  45. package/dist/utils/tickMath.d.ts +34 -0
  46. package/package.json +55 -0
@@ -0,0 +1,4109 @@
1
+ import { MaxUint256, sqrt, Price, CurrencyAmount, Percent, TradeType, Fraction, sortedInsert, validateAndParseAddress } from 'elephantswapv3-sdk-core';
2
+ import JSBI from 'jsbi';
3
+ import invariant from 'tiny-invariant';
4
+ import { defaultAbiCoder, Interface } from '@ethersproject/abi';
5
+ import { getCreate2Address } from '@ethersproject/address';
6
+ import { keccak256, pack } from '@ethersproject/solidity';
7
+ import IMulticall from 'elephantswapv3-periphery/artifacts/contracts/interfaces/IMulticall.sol/IMulticall.json';
8
+ import INonfungiblePositionManager from 'elephantswapv3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json';
9
+ import ISelfPermit from 'elephantswapv3-periphery/artifacts/contracts/interfaces/ISelfPermit.sol/ISelfPermit.json';
10
+ import IPeripheryPaymentsWithFee from 'elephantswapv3-periphery/artifacts/contracts/interfaces/IPeripheryPaymentsWithFee.sol/IPeripheryPaymentsWithFee.json';
11
+ import IQuoter from 'elephantswapv3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json';
12
+ import IQuoterV2 from 'elephantswapv3-router-contracts/artifacts/contracts/lens/QuoterV2.sol/QuoterV2.json';
13
+ import IUniswapV3Staker from 'elephantswapv3-staker/artifacts/contracts/UniswapV3Staker.sol/UniswapV3Staker.json';
14
+ import ISwapRouter from 'elephantswapv3-periphery/artifacts/contracts/SwapRouter.sol/SwapRouter.json';
15
+
16
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
17
+ try {
18
+ var info = gen[key](arg);
19
+ var value = info.value;
20
+ } catch (error) {
21
+ reject(error);
22
+ return;
23
+ }
24
+
25
+ if (info.done) {
26
+ resolve(value);
27
+ } else {
28
+ Promise.resolve(value).then(_next, _throw);
29
+ }
30
+ }
31
+
32
+ function _asyncToGenerator(fn) {
33
+ return function () {
34
+ var self = this,
35
+ args = arguments;
36
+ return new Promise(function (resolve, reject) {
37
+ var gen = fn.apply(self, args);
38
+
39
+ function _next(value) {
40
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
41
+ }
42
+
43
+ function _throw(err) {
44
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
45
+ }
46
+
47
+ _next(undefined);
48
+ });
49
+ };
50
+ }
51
+
52
+ function _defineProperties(target, props) {
53
+ for (var i = 0; i < props.length; i++) {
54
+ var descriptor = props[i];
55
+ descriptor.enumerable = descriptor.enumerable || false;
56
+ descriptor.configurable = true;
57
+ if ("value" in descriptor) descriptor.writable = true;
58
+ Object.defineProperty(target, descriptor.key, descriptor);
59
+ }
60
+ }
61
+
62
+ function _createClass(Constructor, protoProps, staticProps) {
63
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
64
+ if (staticProps) _defineProperties(Constructor, staticProps);
65
+ return Constructor;
66
+ }
67
+
68
+ function _extends() {
69
+ _extends = Object.assign || function (target) {
70
+ for (var i = 1; i < arguments.length; i++) {
71
+ var source = arguments[i];
72
+
73
+ for (var key in source) {
74
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
75
+ target[key] = source[key];
76
+ }
77
+ }
78
+ }
79
+
80
+ return target;
81
+ };
82
+
83
+ return _extends.apply(this, arguments);
84
+ }
85
+
86
+ function _objectWithoutPropertiesLoose(source, excluded) {
87
+ if (source == null) return {};
88
+ var target = {};
89
+ var sourceKeys = Object.keys(source);
90
+ var key, i;
91
+
92
+ for (i = 0; i < sourceKeys.length; i++) {
93
+ key = sourceKeys[i];
94
+ if (excluded.indexOf(key) >= 0) continue;
95
+ target[key] = source[key];
96
+ }
97
+
98
+ return target;
99
+ }
100
+
101
+ function _unsupportedIterableToArray(o, minLen) {
102
+ if (!o) return;
103
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
104
+ var n = Object.prototype.toString.call(o).slice(8, -1);
105
+ if (n === "Object" && o.constructor) n = o.constructor.name;
106
+ if (n === "Map" || n === "Set") return Array.from(o);
107
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
108
+ }
109
+
110
+ function _arrayLikeToArray(arr, len) {
111
+ if (len == null || len > arr.length) len = arr.length;
112
+
113
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
114
+
115
+ return arr2;
116
+ }
117
+
118
+ function _createForOfIteratorHelperLoose(o, allowArrayLike) {
119
+ var it;
120
+
121
+ if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
122
+ if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
123
+ if (it) o = it;
124
+ var i = 0;
125
+ return function () {
126
+ if (i >= o.length) return {
127
+ done: true
128
+ };
129
+ return {
130
+ done: false,
131
+ value: o[i++]
132
+ };
133
+ };
134
+ }
135
+
136
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
137
+ }
138
+
139
+ it = o[Symbol.iterator]();
140
+ return it.next.bind(it);
141
+ }
142
+
143
+ function createCommonjsModule(fn, module) {
144
+ return module = { exports: {} }, fn(module, module.exports), module.exports;
145
+ }
146
+
147
+ var runtime_1 = createCommonjsModule(function (module) {
148
+ /**
149
+ * Copyright (c) 2014-present, Facebook, Inc.
150
+ *
151
+ * This source code is licensed under the MIT license found in the
152
+ * LICENSE file in the root directory of this source tree.
153
+ */
154
+
155
+ var runtime = (function (exports) {
156
+
157
+ var Op = Object.prototype;
158
+ var hasOwn = Op.hasOwnProperty;
159
+ var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; };
160
+ var undefined$1; // More compressible than void 0.
161
+ var $Symbol = typeof Symbol === "function" ? Symbol : {};
162
+ var iteratorSymbol = $Symbol.iterator || "@@iterator";
163
+ var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
164
+ var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
165
+
166
+ function define(obj, key, value) {
167
+ Object.defineProperty(obj, key, {
168
+ value: value,
169
+ enumerable: true,
170
+ configurable: true,
171
+ writable: true
172
+ });
173
+ return obj[key];
174
+ }
175
+ try {
176
+ // IE 8 has a broken Object.defineProperty that only works on DOM objects.
177
+ define({}, "");
178
+ } catch (err) {
179
+ define = function(obj, key, value) {
180
+ return obj[key] = value;
181
+ };
182
+ }
183
+
184
+ function wrap(innerFn, outerFn, self, tryLocsList) {
185
+ // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
186
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
187
+ var generator = Object.create(protoGenerator.prototype);
188
+ var context = new Context(tryLocsList || []);
189
+
190
+ // The ._invoke method unifies the implementations of the .next,
191
+ // .throw, and .return methods.
192
+ defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) });
193
+
194
+ return generator;
195
+ }
196
+ exports.wrap = wrap;
197
+
198
+ // Try/catch helper to minimize deoptimizations. Returns a completion
199
+ // record like context.tryEntries[i].completion. This interface could
200
+ // have been (and was previously) designed to take a closure to be
201
+ // invoked without arguments, but in all the cases we care about we
202
+ // already have an existing method we want to call, so there's no need
203
+ // to create a new function object. We can even get away with assuming
204
+ // the method takes exactly one argument, since that happens to be true
205
+ // in every case, so we don't have to touch the arguments object. The
206
+ // only additional allocation required is the completion record, which
207
+ // has a stable shape and so hopefully should be cheap to allocate.
208
+ function tryCatch(fn, obj, arg) {
209
+ try {
210
+ return { type: "normal", arg: fn.call(obj, arg) };
211
+ } catch (err) {
212
+ return { type: "throw", arg: err };
213
+ }
214
+ }
215
+
216
+ var GenStateSuspendedStart = "suspendedStart";
217
+ var GenStateSuspendedYield = "suspendedYield";
218
+ var GenStateExecuting = "executing";
219
+ var GenStateCompleted = "completed";
220
+
221
+ // Returning this object from the innerFn has the same effect as
222
+ // breaking out of the dispatch switch statement.
223
+ var ContinueSentinel = {};
224
+
225
+ // Dummy constructor functions that we use as the .constructor and
226
+ // .constructor.prototype properties for functions that return Generator
227
+ // objects. For full spec compliance, you may wish to configure your
228
+ // minifier not to mangle the names of these two functions.
229
+ function Generator() {}
230
+ function GeneratorFunction() {}
231
+ function GeneratorFunctionPrototype() {}
232
+
233
+ // This is a polyfill for %IteratorPrototype% for environments that
234
+ // don't natively support it.
235
+ var IteratorPrototype = {};
236
+ define(IteratorPrototype, iteratorSymbol, function () {
237
+ return this;
238
+ });
239
+
240
+ var getProto = Object.getPrototypeOf;
241
+ var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
242
+ if (NativeIteratorPrototype &&
243
+ NativeIteratorPrototype !== Op &&
244
+ hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
245
+ // This environment has a native %IteratorPrototype%; use it instead
246
+ // of the polyfill.
247
+ IteratorPrototype = NativeIteratorPrototype;
248
+ }
249
+
250
+ var Gp = GeneratorFunctionPrototype.prototype =
251
+ Generator.prototype = Object.create(IteratorPrototype);
252
+ GeneratorFunction.prototype = GeneratorFunctionPrototype;
253
+ defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true });
254
+ defineProperty(
255
+ GeneratorFunctionPrototype,
256
+ "constructor",
257
+ { value: GeneratorFunction, configurable: true }
258
+ );
259
+ GeneratorFunction.displayName = define(
260
+ GeneratorFunctionPrototype,
261
+ toStringTagSymbol,
262
+ "GeneratorFunction"
263
+ );
264
+
265
+ // Helper for defining the .next, .throw, and .return methods of the
266
+ // Iterator interface in terms of a single ._invoke method.
267
+ function defineIteratorMethods(prototype) {
268
+ ["next", "throw", "return"].forEach(function(method) {
269
+ define(prototype, method, function(arg) {
270
+ return this._invoke(method, arg);
271
+ });
272
+ });
273
+ }
274
+
275
+ exports.isGeneratorFunction = function(genFun) {
276
+ var ctor = typeof genFun === "function" && genFun.constructor;
277
+ return ctor
278
+ ? ctor === GeneratorFunction ||
279
+ // For the native GeneratorFunction constructor, the best we can
280
+ // do is to check its .name property.
281
+ (ctor.displayName || ctor.name) === "GeneratorFunction"
282
+ : false;
283
+ };
284
+
285
+ exports.mark = function(genFun) {
286
+ if (Object.setPrototypeOf) {
287
+ Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
288
+ } else {
289
+ genFun.__proto__ = GeneratorFunctionPrototype;
290
+ define(genFun, toStringTagSymbol, "GeneratorFunction");
291
+ }
292
+ genFun.prototype = Object.create(Gp);
293
+ return genFun;
294
+ };
295
+
296
+ // Within the body of any async function, `await x` is transformed to
297
+ // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
298
+ // `hasOwn.call(value, "__await")` to determine if the yielded value is
299
+ // meant to be awaited.
300
+ exports.awrap = function(arg) {
301
+ return { __await: arg };
302
+ };
303
+
304
+ function AsyncIterator(generator, PromiseImpl) {
305
+ function invoke(method, arg, resolve, reject) {
306
+ var record = tryCatch(generator[method], generator, arg);
307
+ if (record.type === "throw") {
308
+ reject(record.arg);
309
+ } else {
310
+ var result = record.arg;
311
+ var value = result.value;
312
+ if (value &&
313
+ typeof value === "object" &&
314
+ hasOwn.call(value, "__await")) {
315
+ return PromiseImpl.resolve(value.__await).then(function(value) {
316
+ invoke("next", value, resolve, reject);
317
+ }, function(err) {
318
+ invoke("throw", err, resolve, reject);
319
+ });
320
+ }
321
+
322
+ return PromiseImpl.resolve(value).then(function(unwrapped) {
323
+ // When a yielded Promise is resolved, its final value becomes
324
+ // the .value of the Promise<{value,done}> result for the
325
+ // current iteration.
326
+ result.value = unwrapped;
327
+ resolve(result);
328
+ }, function(error) {
329
+ // If a rejected Promise was yielded, throw the rejection back
330
+ // into the async generator function so it can be handled there.
331
+ return invoke("throw", error, resolve, reject);
332
+ });
333
+ }
334
+ }
335
+
336
+ var previousPromise;
337
+
338
+ function enqueue(method, arg) {
339
+ function callInvokeWithMethodAndArg() {
340
+ return new PromiseImpl(function(resolve, reject) {
341
+ invoke(method, arg, resolve, reject);
342
+ });
343
+ }
344
+
345
+ return previousPromise =
346
+ // If enqueue has been called before, then we want to wait until
347
+ // all previous Promises have been resolved before calling invoke,
348
+ // so that results are always delivered in the correct order. If
349
+ // enqueue has not been called before, then it is important to
350
+ // call invoke immediately, without waiting on a callback to fire,
351
+ // so that the async generator function has the opportunity to do
352
+ // any necessary setup in a predictable way. This predictability
353
+ // is why the Promise constructor synchronously invokes its
354
+ // executor callback, and why async functions synchronously
355
+ // execute code before the first await. Since we implement simple
356
+ // async functions in terms of async generators, it is especially
357
+ // important to get this right, even though it requires care.
358
+ previousPromise ? previousPromise.then(
359
+ callInvokeWithMethodAndArg,
360
+ // Avoid propagating failures to Promises returned by later
361
+ // invocations of the iterator.
362
+ callInvokeWithMethodAndArg
363
+ ) : callInvokeWithMethodAndArg();
364
+ }
365
+
366
+ // Define the unified helper method that is used to implement .next,
367
+ // .throw, and .return (see defineIteratorMethods).
368
+ defineProperty(this, "_invoke", { value: enqueue });
369
+ }
370
+
371
+ defineIteratorMethods(AsyncIterator.prototype);
372
+ define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
373
+ return this;
374
+ });
375
+ exports.AsyncIterator = AsyncIterator;
376
+
377
+ // Note that simple async functions are implemented on top of
378
+ // AsyncIterator objects; they just return a Promise for the value of
379
+ // the final result produced by the iterator.
380
+ exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
381
+ if (PromiseImpl === void 0) PromiseImpl = Promise;
382
+
383
+ var iter = new AsyncIterator(
384
+ wrap(innerFn, outerFn, self, tryLocsList),
385
+ PromiseImpl
386
+ );
387
+
388
+ return exports.isGeneratorFunction(outerFn)
389
+ ? iter // If outerFn is a generator, return the full iterator.
390
+ : iter.next().then(function(result) {
391
+ return result.done ? result.value : iter.next();
392
+ });
393
+ };
394
+
395
+ function makeInvokeMethod(innerFn, self, context) {
396
+ var state = GenStateSuspendedStart;
397
+
398
+ return function invoke(method, arg) {
399
+ if (state === GenStateExecuting) {
400
+ throw new Error("Generator is already running");
401
+ }
402
+
403
+ if (state === GenStateCompleted) {
404
+ if (method === "throw") {
405
+ throw arg;
406
+ }
407
+
408
+ // Be forgiving, per GeneratorResume behavior specified since ES2015:
409
+ // ES2015 spec, step 3: https://262.ecma-international.org/6.0/#sec-generatorresume
410
+ // Latest spec, step 2: https://tc39.es/ecma262/#sec-generatorresume
411
+ return doneResult();
412
+ }
413
+
414
+ context.method = method;
415
+ context.arg = arg;
416
+
417
+ while (true) {
418
+ var delegate = context.delegate;
419
+ if (delegate) {
420
+ var delegateResult = maybeInvokeDelegate(delegate, context);
421
+ if (delegateResult) {
422
+ if (delegateResult === ContinueSentinel) continue;
423
+ return delegateResult;
424
+ }
425
+ }
426
+
427
+ if (context.method === "next") {
428
+ // Setting context._sent for legacy support of Babel's
429
+ // function.sent implementation.
430
+ context.sent = context._sent = context.arg;
431
+
432
+ } else if (context.method === "throw") {
433
+ if (state === GenStateSuspendedStart) {
434
+ state = GenStateCompleted;
435
+ throw context.arg;
436
+ }
437
+
438
+ context.dispatchException(context.arg);
439
+
440
+ } else if (context.method === "return") {
441
+ context.abrupt("return", context.arg);
442
+ }
443
+
444
+ state = GenStateExecuting;
445
+
446
+ var record = tryCatch(innerFn, self, context);
447
+ if (record.type === "normal") {
448
+ // If an exception is thrown from innerFn, we leave state ===
449
+ // GenStateExecuting and loop back for another invocation.
450
+ state = context.done
451
+ ? GenStateCompleted
452
+ : GenStateSuspendedYield;
453
+
454
+ if (record.arg === ContinueSentinel) {
455
+ continue;
456
+ }
457
+
458
+ return {
459
+ value: record.arg,
460
+ done: context.done
461
+ };
462
+
463
+ } else if (record.type === "throw") {
464
+ state = GenStateCompleted;
465
+ // Dispatch the exception by looping back around to the
466
+ // context.dispatchException(context.arg) call above.
467
+ context.method = "throw";
468
+ context.arg = record.arg;
469
+ }
470
+ }
471
+ };
472
+ }
473
+
474
+ // Call delegate.iterator[context.method](context.arg) and handle the
475
+ // result, either by returning a { value, done } result from the
476
+ // delegate iterator, or by modifying context.method and context.arg,
477
+ // setting context.delegate to null, and returning the ContinueSentinel.
478
+ function maybeInvokeDelegate(delegate, context) {
479
+ var methodName = context.method;
480
+ var method = delegate.iterator[methodName];
481
+ if (method === undefined$1) {
482
+ // A .throw or .return when the delegate iterator has no .throw
483
+ // method, or a missing .next method, always terminate the
484
+ // yield* loop.
485
+ context.delegate = null;
486
+
487
+ // Note: ["return"] must be used for ES3 parsing compatibility.
488
+ if (methodName === "throw" && delegate.iterator["return"]) {
489
+ // If the delegate iterator has a return method, give it a
490
+ // chance to clean up.
491
+ context.method = "return";
492
+ context.arg = undefined$1;
493
+ maybeInvokeDelegate(delegate, context);
494
+
495
+ if (context.method === "throw") {
496
+ // If maybeInvokeDelegate(context) changed context.method from
497
+ // "return" to "throw", let that override the TypeError below.
498
+ return ContinueSentinel;
499
+ }
500
+ }
501
+ if (methodName !== "return") {
502
+ context.method = "throw";
503
+ context.arg = new TypeError(
504
+ "The iterator does not provide a '" + methodName + "' method");
505
+ }
506
+
507
+ return ContinueSentinel;
508
+ }
509
+
510
+ var record = tryCatch(method, delegate.iterator, context.arg);
511
+
512
+ if (record.type === "throw") {
513
+ context.method = "throw";
514
+ context.arg = record.arg;
515
+ context.delegate = null;
516
+ return ContinueSentinel;
517
+ }
518
+
519
+ var info = record.arg;
520
+
521
+ if (! info) {
522
+ context.method = "throw";
523
+ context.arg = new TypeError("iterator result is not an object");
524
+ context.delegate = null;
525
+ return ContinueSentinel;
526
+ }
527
+
528
+ if (info.done) {
529
+ // Assign the result of the finished delegate to the temporary
530
+ // variable specified by delegate.resultName (see delegateYield).
531
+ context[delegate.resultName] = info.value;
532
+
533
+ // Resume execution at the desired location (see delegateYield).
534
+ context.next = delegate.nextLoc;
535
+
536
+ // If context.method was "throw" but the delegate handled the
537
+ // exception, let the outer generator proceed normally. If
538
+ // context.method was "next", forget context.arg since it has been
539
+ // "consumed" by the delegate iterator. If context.method was
540
+ // "return", allow the original .return call to continue in the
541
+ // outer generator.
542
+ if (context.method !== "return") {
543
+ context.method = "next";
544
+ context.arg = undefined$1;
545
+ }
546
+
547
+ } else {
548
+ // Re-yield the result returned by the delegate method.
549
+ return info;
550
+ }
551
+
552
+ // The delegate iterator is finished, so forget it and continue with
553
+ // the outer generator.
554
+ context.delegate = null;
555
+ return ContinueSentinel;
556
+ }
557
+
558
+ // Define Generator.prototype.{next,throw,return} in terms of the
559
+ // unified ._invoke helper method.
560
+ defineIteratorMethods(Gp);
561
+
562
+ define(Gp, toStringTagSymbol, "Generator");
563
+
564
+ // A Generator should always return itself as the iterator object when the
565
+ // @@iterator function is called on it. Some browsers' implementations of the
566
+ // iterator prototype chain incorrectly implement this, causing the Generator
567
+ // object to not be returned from this call. This ensures that doesn't happen.
568
+ // See https://github.com/facebook/regenerator/issues/274 for more details.
569
+ define(Gp, iteratorSymbol, function() {
570
+ return this;
571
+ });
572
+
573
+ define(Gp, "toString", function() {
574
+ return "[object Generator]";
575
+ });
576
+
577
+ function pushTryEntry(locs) {
578
+ var entry = { tryLoc: locs[0] };
579
+
580
+ if (1 in locs) {
581
+ entry.catchLoc = locs[1];
582
+ }
583
+
584
+ if (2 in locs) {
585
+ entry.finallyLoc = locs[2];
586
+ entry.afterLoc = locs[3];
587
+ }
588
+
589
+ this.tryEntries.push(entry);
590
+ }
591
+
592
+ function resetTryEntry(entry) {
593
+ var record = entry.completion || {};
594
+ record.type = "normal";
595
+ delete record.arg;
596
+ entry.completion = record;
597
+ }
598
+
599
+ function Context(tryLocsList) {
600
+ // The root entry object (effectively a try statement without a catch
601
+ // or a finally block) gives us a place to store values thrown from
602
+ // locations where there is no enclosing try statement.
603
+ this.tryEntries = [{ tryLoc: "root" }];
604
+ tryLocsList.forEach(pushTryEntry, this);
605
+ this.reset(true);
606
+ }
607
+
608
+ exports.keys = function(val) {
609
+ var object = Object(val);
610
+ var keys = [];
611
+ for (var key in object) {
612
+ keys.push(key);
613
+ }
614
+ keys.reverse();
615
+
616
+ // Rather than returning an object with a next method, we keep
617
+ // things simple and return the next function itself.
618
+ return function next() {
619
+ while (keys.length) {
620
+ var key = keys.pop();
621
+ if (key in object) {
622
+ next.value = key;
623
+ next.done = false;
624
+ return next;
625
+ }
626
+ }
627
+
628
+ // To avoid creating an additional object, we just hang the .value
629
+ // and .done properties off the next function object itself. This
630
+ // also ensures that the minifier will not anonymize the function.
631
+ next.done = true;
632
+ return next;
633
+ };
634
+ };
635
+
636
+ function values(iterable) {
637
+ if (iterable != null) {
638
+ var iteratorMethod = iterable[iteratorSymbol];
639
+ if (iteratorMethod) {
640
+ return iteratorMethod.call(iterable);
641
+ }
642
+
643
+ if (typeof iterable.next === "function") {
644
+ return iterable;
645
+ }
646
+
647
+ if (!isNaN(iterable.length)) {
648
+ var i = -1, next = function next() {
649
+ while (++i < iterable.length) {
650
+ if (hasOwn.call(iterable, i)) {
651
+ next.value = iterable[i];
652
+ next.done = false;
653
+ return next;
654
+ }
655
+ }
656
+
657
+ next.value = undefined$1;
658
+ next.done = true;
659
+
660
+ return next;
661
+ };
662
+
663
+ return next.next = next;
664
+ }
665
+ }
666
+
667
+ throw new TypeError(typeof iterable + " is not iterable");
668
+ }
669
+ exports.values = values;
670
+
671
+ function doneResult() {
672
+ return { value: undefined$1, done: true };
673
+ }
674
+
675
+ Context.prototype = {
676
+ constructor: Context,
677
+
678
+ reset: function(skipTempReset) {
679
+ this.prev = 0;
680
+ this.next = 0;
681
+ // Resetting context._sent for legacy support of Babel's
682
+ // function.sent implementation.
683
+ this.sent = this._sent = undefined$1;
684
+ this.done = false;
685
+ this.delegate = null;
686
+
687
+ this.method = "next";
688
+ this.arg = undefined$1;
689
+
690
+ this.tryEntries.forEach(resetTryEntry);
691
+
692
+ if (!skipTempReset) {
693
+ for (var name in this) {
694
+ // Not sure about the optimal order of these conditions:
695
+ if (name.charAt(0) === "t" &&
696
+ hasOwn.call(this, name) &&
697
+ !isNaN(+name.slice(1))) {
698
+ this[name] = undefined$1;
699
+ }
700
+ }
701
+ }
702
+ },
703
+
704
+ stop: function() {
705
+ this.done = true;
706
+
707
+ var rootEntry = this.tryEntries[0];
708
+ var rootRecord = rootEntry.completion;
709
+ if (rootRecord.type === "throw") {
710
+ throw rootRecord.arg;
711
+ }
712
+
713
+ return this.rval;
714
+ },
715
+
716
+ dispatchException: function(exception) {
717
+ if (this.done) {
718
+ throw exception;
719
+ }
720
+
721
+ var context = this;
722
+ function handle(loc, caught) {
723
+ record.type = "throw";
724
+ record.arg = exception;
725
+ context.next = loc;
726
+
727
+ if (caught) {
728
+ // If the dispatched exception was caught by a catch block,
729
+ // then let that catch block handle the exception normally.
730
+ context.method = "next";
731
+ context.arg = undefined$1;
732
+ }
733
+
734
+ return !! caught;
735
+ }
736
+
737
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
738
+ var entry = this.tryEntries[i];
739
+ var record = entry.completion;
740
+
741
+ if (entry.tryLoc === "root") {
742
+ // Exception thrown outside of any try block that could handle
743
+ // it, so set the completion value of the entire function to
744
+ // throw the exception.
745
+ return handle("end");
746
+ }
747
+
748
+ if (entry.tryLoc <= this.prev) {
749
+ var hasCatch = hasOwn.call(entry, "catchLoc");
750
+ var hasFinally = hasOwn.call(entry, "finallyLoc");
751
+
752
+ if (hasCatch && hasFinally) {
753
+ if (this.prev < entry.catchLoc) {
754
+ return handle(entry.catchLoc, true);
755
+ } else if (this.prev < entry.finallyLoc) {
756
+ return handle(entry.finallyLoc);
757
+ }
758
+
759
+ } else if (hasCatch) {
760
+ if (this.prev < entry.catchLoc) {
761
+ return handle(entry.catchLoc, true);
762
+ }
763
+
764
+ } else if (hasFinally) {
765
+ if (this.prev < entry.finallyLoc) {
766
+ return handle(entry.finallyLoc);
767
+ }
768
+
769
+ } else {
770
+ throw new Error("try statement without catch or finally");
771
+ }
772
+ }
773
+ }
774
+ },
775
+
776
+ abrupt: function(type, arg) {
777
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
778
+ var entry = this.tryEntries[i];
779
+ if (entry.tryLoc <= this.prev &&
780
+ hasOwn.call(entry, "finallyLoc") &&
781
+ this.prev < entry.finallyLoc) {
782
+ var finallyEntry = entry;
783
+ break;
784
+ }
785
+ }
786
+
787
+ if (finallyEntry &&
788
+ (type === "break" ||
789
+ type === "continue") &&
790
+ finallyEntry.tryLoc <= arg &&
791
+ arg <= finallyEntry.finallyLoc) {
792
+ // Ignore the finally entry if control is not jumping to a
793
+ // location outside the try/catch block.
794
+ finallyEntry = null;
795
+ }
796
+
797
+ var record = finallyEntry ? finallyEntry.completion : {};
798
+ record.type = type;
799
+ record.arg = arg;
800
+
801
+ if (finallyEntry) {
802
+ this.method = "next";
803
+ this.next = finallyEntry.finallyLoc;
804
+ return ContinueSentinel;
805
+ }
806
+
807
+ return this.complete(record);
808
+ },
809
+
810
+ complete: function(record, afterLoc) {
811
+ if (record.type === "throw") {
812
+ throw record.arg;
813
+ }
814
+
815
+ if (record.type === "break" ||
816
+ record.type === "continue") {
817
+ this.next = record.arg;
818
+ } else if (record.type === "return") {
819
+ this.rval = this.arg = record.arg;
820
+ this.method = "return";
821
+ this.next = "end";
822
+ } else if (record.type === "normal" && afterLoc) {
823
+ this.next = afterLoc;
824
+ }
825
+
826
+ return ContinueSentinel;
827
+ },
828
+
829
+ finish: function(finallyLoc) {
830
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
831
+ var entry = this.tryEntries[i];
832
+ if (entry.finallyLoc === finallyLoc) {
833
+ this.complete(entry.completion, entry.afterLoc);
834
+ resetTryEntry(entry);
835
+ return ContinueSentinel;
836
+ }
837
+ }
838
+ },
839
+
840
+ "catch": function(tryLoc) {
841
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
842
+ var entry = this.tryEntries[i];
843
+ if (entry.tryLoc === tryLoc) {
844
+ var record = entry.completion;
845
+ if (record.type === "throw") {
846
+ var thrown = record.arg;
847
+ resetTryEntry(entry);
848
+ }
849
+ return thrown;
850
+ }
851
+ }
852
+
853
+ // The context.catch method must only be called with a location
854
+ // argument that corresponds to a known catch block.
855
+ throw new Error("illegal catch attempt");
856
+ },
857
+
858
+ delegateYield: function(iterable, resultName, nextLoc) {
859
+ this.delegate = {
860
+ iterator: values(iterable),
861
+ resultName: resultName,
862
+ nextLoc: nextLoc
863
+ };
864
+
865
+ if (this.method === "next") {
866
+ // Deliberately forget the last sent value so that we don't
867
+ // accidentally pass it on to the delegate.
868
+ this.arg = undefined$1;
869
+ }
870
+
871
+ return ContinueSentinel;
872
+ }
873
+ };
874
+
875
+ // Regardless of whether this script is executing as a CommonJS module
876
+ // or not, return the runtime object so that we can declare the variable
877
+ // regeneratorRuntime in the outer scope, which allows this module to be
878
+ // injected easily by `bin/regenerator --include-runtime script.js`.
879
+ return exports;
880
+
881
+ }(
882
+ // If this script is executing as a CommonJS module, use module.exports
883
+ // as the regeneratorRuntime namespace. Otherwise create a new empty
884
+ // object. Either way, the resulting object will be used to initialize
885
+ // the regeneratorRuntime variable at the top of this file.
886
+ module.exports
887
+ ));
888
+
889
+ try {
890
+ regeneratorRuntime = runtime;
891
+ } catch (accidentalStrictMode) {
892
+ // This module should not be running in strict mode, so the above
893
+ // assignment should always work unless something is misconfigured. Just
894
+ // in case runtime.js accidentally runs in strict mode, in modern engines
895
+ // we can explicitly access globalThis. In older engines we can escape
896
+ // strict mode using a global Function call. This could conceivably fail
897
+ // if a Content Security Policy forbids using Function, but in that case
898
+ // the proper solution is to fix the accidental strict mode problem. If
899
+ // you've misconfigured your bundler to force strict mode and applied a
900
+ // CSP to forbid Function, and you're not willing to fix either of those
901
+ // problems, please detail your unique predicament in a GitHub issue.
902
+ if (typeof globalThis === "object") {
903
+ globalThis.regeneratorRuntime = runtime;
904
+ } else {
905
+ Function("r", "regeneratorRuntime = r")(runtime);
906
+ }
907
+ }
908
+ });
909
+
910
+ var _TICK_SPACINGS;
911
+
912
+ var FACTORY_ADDRESS = '0xe62B3e1D1F2D58Dd9F95f3CdF847acfc8177e5ea';
913
+ var ADDRESS_ZERO = '0x0000000000000000000000000000000000000000';
914
+ var POOL_INIT_CODE_HASH = '0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54';
915
+ /**
916
+ * The default factory enabled fee amounts, denominated in hundredths of bips.
917
+ */
918
+
919
+ var FeeAmount;
920
+
921
+ (function (FeeAmount) {
922
+ FeeAmount[FeeAmount["LOWEST"] = 100] = "LOWEST";
923
+ FeeAmount[FeeAmount["LOW"] = 500] = "LOW";
924
+ FeeAmount[FeeAmount["MEDIUM"] = 3000] = "MEDIUM";
925
+ FeeAmount[FeeAmount["HIGH"] = 10000] = "HIGH";
926
+ })(FeeAmount || (FeeAmount = {}));
927
+ /**
928
+ * The default factory tick spacings by fee amount.
929
+ */
930
+
931
+
932
+ var TICK_SPACINGS = (_TICK_SPACINGS = {}, _TICK_SPACINGS[FeeAmount.LOWEST] = 1, _TICK_SPACINGS[FeeAmount.LOW] = 10, _TICK_SPACINGS[FeeAmount.MEDIUM] = 60, _TICK_SPACINGS[FeeAmount.HIGH] = 200, _TICK_SPACINGS);
933
+
934
+ var NEGATIVE_ONE = /*#__PURE__*/JSBI.BigInt(-1);
935
+ var ZERO = /*#__PURE__*/JSBI.BigInt(0);
936
+ var ONE = /*#__PURE__*/JSBI.BigInt(1); // used in liquidity amount math
937
+
938
+ var Q96 = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(96));
939
+ var Q192 = /*#__PURE__*/JSBI.exponentiate(Q96, /*#__PURE__*/JSBI.BigInt(2));
940
+
941
+ /**
942
+ * Computes a pool address
943
+ * @param factoryAddress The Uniswap V3 factory address
944
+ * @param tokenA The first token of the pair, irrespective of sort order
945
+ * @param tokenB The second token of the pair, irrespective of sort order
946
+ * @param fee The fee tier of the pool
947
+ * @param initCodeHashManualOverride Override the init code hash used to compute the pool address if necessary
948
+ * @returns The pool address
949
+ */
950
+
951
+ function computePoolAddress(_ref) {
952
+ var factoryAddress = _ref.factoryAddress,
953
+ tokenA = _ref.tokenA,
954
+ tokenB = _ref.tokenB,
955
+ fee = _ref.fee,
956
+ initCodeHashManualOverride = _ref.initCodeHashManualOverride;
957
+
958
+ var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
959
+ token0 = _ref2[0],
960
+ token1 = _ref2[1]; // does safety checks
961
+
962
+
963
+ return getCreate2Address(factoryAddress, keccak256(['bytes'], [defaultAbiCoder.encode(['address', 'address', 'uint24'], [token0.address, token1.address, fee])]), initCodeHashManualOverride != null ? initCodeHashManualOverride : POOL_INIT_CODE_HASH);
964
+ }
965
+
966
+ var LiquidityMath = /*#__PURE__*/function () {
967
+ /**
968
+ * Cannot be constructed.
969
+ */
970
+ function LiquidityMath() {}
971
+
972
+ LiquidityMath.addDelta = function addDelta(x, y) {
973
+ if (JSBI.lessThan(y, ZERO)) {
974
+ return JSBI.subtract(x, JSBI.multiply(y, NEGATIVE_ONE));
975
+ } else {
976
+ return JSBI.add(x, y);
977
+ }
978
+ };
979
+
980
+ return LiquidityMath;
981
+ }();
982
+
983
+ var FullMath = /*#__PURE__*/function () {
984
+ /**
985
+ * Cannot be constructed.
986
+ */
987
+ function FullMath() {}
988
+
989
+ FullMath.mulDivRoundingUp = function mulDivRoundingUp(a, b, denominator) {
990
+ var product = JSBI.multiply(a, b);
991
+ var result = JSBI.divide(product, denominator);
992
+ if (JSBI.notEqual(JSBI.remainder(product, denominator), ZERO)) result = JSBI.add(result, ONE);
993
+ return result;
994
+ };
995
+
996
+ return FullMath;
997
+ }();
998
+
999
+ var MaxUint160 = /*#__PURE__*/JSBI.subtract( /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(160)), ONE);
1000
+
1001
+ function multiplyIn256(x, y) {
1002
+ var product = JSBI.multiply(x, y);
1003
+ return JSBI.bitwiseAnd(product, MaxUint256);
1004
+ }
1005
+
1006
+ function addIn256(x, y) {
1007
+ var sum = JSBI.add(x, y);
1008
+ return JSBI.bitwiseAnd(sum, MaxUint256);
1009
+ }
1010
+
1011
+ var SqrtPriceMath = /*#__PURE__*/function () {
1012
+ /**
1013
+ * Cannot be constructed.
1014
+ */
1015
+ function SqrtPriceMath() {}
1016
+
1017
+ SqrtPriceMath.getAmount0Delta = function getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
1018
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
1019
+ var _ref = [sqrtRatioBX96, sqrtRatioAX96];
1020
+ sqrtRatioAX96 = _ref[0];
1021
+ sqrtRatioBX96 = _ref[1];
1022
+ }
1023
+
1024
+ var numerator1 = JSBI.leftShift(liquidity, JSBI.BigInt(96));
1025
+ var numerator2 = JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96);
1026
+ return roundUp ? FullMath.mulDivRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), ONE, sqrtRatioAX96) : JSBI.divide(JSBI.divide(JSBI.multiply(numerator1, numerator2), sqrtRatioBX96), sqrtRatioAX96);
1027
+ };
1028
+
1029
+ SqrtPriceMath.getAmount1Delta = function getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) {
1030
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
1031
+ var _ref2 = [sqrtRatioBX96, sqrtRatioAX96];
1032
+ sqrtRatioAX96 = _ref2[0];
1033
+ sqrtRatioBX96 = _ref2[1];
1034
+ }
1035
+
1036
+ return roundUp ? FullMath.mulDivRoundingUp(liquidity, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96), Q96) : JSBI.divide(JSBI.multiply(liquidity, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96)), Q96);
1037
+ };
1038
+
1039
+ SqrtPriceMath.getNextSqrtPriceFromInput = function getNextSqrtPriceFromInput(sqrtPX96, liquidity, amountIn, zeroForOne) {
1040
+ !JSBI.greaterThan(sqrtPX96, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
1041
+ !JSBI.greaterThan(liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
1042
+ return zeroForOne ? this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
1043
+ };
1044
+
1045
+ SqrtPriceMath.getNextSqrtPriceFromOutput = function getNextSqrtPriceFromOutput(sqrtPX96, liquidity, amountOut, zeroForOne) {
1046
+ !JSBI.greaterThan(sqrtPX96, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
1047
+ !JSBI.greaterThan(liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
1048
+ return zeroForOne ? this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
1049
+ };
1050
+
1051
+ SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp = function getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amount, add) {
1052
+ if (JSBI.equal(amount, ZERO)) return sqrtPX96;
1053
+ var numerator1 = JSBI.leftShift(liquidity, JSBI.BigInt(96));
1054
+
1055
+ if (add) {
1056
+ var product = multiplyIn256(amount, sqrtPX96);
1057
+
1058
+ if (JSBI.equal(JSBI.divide(product, amount), sqrtPX96)) {
1059
+ var denominator = addIn256(numerator1, product);
1060
+
1061
+ if (JSBI.greaterThanOrEqual(denominator, numerator1)) {
1062
+ return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator);
1063
+ }
1064
+ }
1065
+
1066
+ return FullMath.mulDivRoundingUp(numerator1, ONE, JSBI.add(JSBI.divide(numerator1, sqrtPX96), amount));
1067
+ } else {
1068
+ var _product = multiplyIn256(amount, sqrtPX96);
1069
+
1070
+ !JSBI.equal(JSBI.divide(_product, amount), sqrtPX96) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
1071
+ !JSBI.greaterThan(numerator1, _product) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
1072
+
1073
+ var _denominator = JSBI.subtract(numerator1, _product);
1074
+
1075
+ return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, _denominator);
1076
+ }
1077
+ };
1078
+
1079
+ SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown = function getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amount, add) {
1080
+ if (add) {
1081
+ var quotient = JSBI.lessThanOrEqual(amount, MaxUint160) ? JSBI.divide(JSBI.leftShift(amount, JSBI.BigInt(96)), liquidity) : JSBI.divide(JSBI.multiply(amount, Q96), liquidity);
1082
+ return JSBI.add(sqrtPX96, quotient);
1083
+ } else {
1084
+ var _quotient = FullMath.mulDivRoundingUp(amount, Q96, liquidity);
1085
+
1086
+ !JSBI.greaterThan(sqrtPX96, _quotient) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0;
1087
+ return JSBI.subtract(sqrtPX96, _quotient);
1088
+ }
1089
+ };
1090
+
1091
+ return SqrtPriceMath;
1092
+ }();
1093
+
1094
+ var MAX_FEE = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(10), /*#__PURE__*/JSBI.BigInt(6));
1095
+ var SwapMath = /*#__PURE__*/function () {
1096
+ /**
1097
+ * Cannot be constructed.
1098
+ */
1099
+ function SwapMath() {}
1100
+
1101
+ SwapMath.computeSwapStep = function computeSwapStep(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, amountRemaining, feePips) {
1102
+ var returnValues = {};
1103
+ var zeroForOne = JSBI.greaterThanOrEqual(sqrtRatioCurrentX96, sqrtRatioTargetX96);
1104
+ var exactIn = JSBI.greaterThanOrEqual(amountRemaining, ZERO);
1105
+
1106
+ if (exactIn) {
1107
+ var amountRemainingLessFee = JSBI.divide(JSBI.multiply(amountRemaining, JSBI.subtract(MAX_FEE, JSBI.BigInt(feePips))), MAX_FEE);
1108
+ returnValues.amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
1109
+
1110
+ if (JSBI.greaterThanOrEqual(amountRemainingLessFee, returnValues.amountIn)) {
1111
+ returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
1112
+ } else {
1113
+ returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne);
1114
+ }
1115
+ } else {
1116
+ returnValues.amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
1117
+
1118
+ if (JSBI.greaterThanOrEqual(JSBI.multiply(amountRemaining, NEGATIVE_ONE), returnValues.amountOut)) {
1119
+ returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96;
1120
+ } else {
1121
+ returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtRatioCurrentX96, liquidity, JSBI.multiply(amountRemaining, NEGATIVE_ONE), zeroForOne);
1122
+ }
1123
+ }
1124
+
1125
+ var max = JSBI.equal(sqrtRatioTargetX96, returnValues.sqrtRatioNextX96);
1126
+
1127
+ if (zeroForOne) {
1128
+ returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount0Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
1129
+ returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount1Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
1130
+ } else {
1131
+ returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, true);
1132
+ returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, false);
1133
+ }
1134
+
1135
+ if (!exactIn && JSBI.greaterThan(returnValues.amountOut, JSBI.multiply(amountRemaining, NEGATIVE_ONE))) {
1136
+ returnValues.amountOut = JSBI.multiply(amountRemaining, NEGATIVE_ONE);
1137
+ }
1138
+
1139
+ if (exactIn && JSBI.notEqual(returnValues.sqrtRatioNextX96, sqrtRatioTargetX96)) {
1140
+ // we didn't reach the target, so take the remainder of the maximum input as fee
1141
+ returnValues.feeAmount = JSBI.subtract(amountRemaining, returnValues.amountIn);
1142
+ } else {
1143
+ returnValues.feeAmount = FullMath.mulDivRoundingUp(returnValues.amountIn, JSBI.BigInt(feePips), JSBI.subtract(MAX_FEE, JSBI.BigInt(feePips)));
1144
+ }
1145
+
1146
+ return [returnValues.sqrtRatioNextX96, returnValues.amountIn, returnValues.amountOut, returnValues.feeAmount];
1147
+ };
1148
+
1149
+ return SwapMath;
1150
+ }();
1151
+
1152
+ var TWO = /*#__PURE__*/JSBI.BigInt(2);
1153
+ var POWERS_OF_2 = /*#__PURE__*/[128, 64, 32, 16, 8, 4, 2, 1].map(function (pow) {
1154
+ return [pow, JSBI.exponentiate(TWO, JSBI.BigInt(pow))];
1155
+ });
1156
+ function mostSignificantBit(x) {
1157
+ !JSBI.greaterThan(x, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO') : invariant(false) : void 0;
1158
+ !JSBI.lessThanOrEqual(x, MaxUint256) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX') : invariant(false) : void 0;
1159
+ var msb = 0;
1160
+
1161
+ for (var _iterator = _createForOfIteratorHelperLoose(POWERS_OF_2), _step; !(_step = _iterator()).done;) {
1162
+ var _step$value = _step.value,
1163
+ power = _step$value[0],
1164
+ min = _step$value[1];
1165
+
1166
+ if (JSBI.greaterThanOrEqual(x, min)) {
1167
+ x = JSBI.signedRightShift(x, JSBI.BigInt(power));
1168
+ msb += power;
1169
+ }
1170
+ }
1171
+
1172
+ return msb;
1173
+ }
1174
+
1175
+ function mulShift(val, mulBy) {
1176
+ return JSBI.signedRightShift(JSBI.multiply(val, JSBI.BigInt(mulBy)), JSBI.BigInt(128));
1177
+ }
1178
+
1179
+ var Q32 = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(32));
1180
+ var TickMath = /*#__PURE__*/function () {
1181
+ /**
1182
+ * Cannot be constructed.
1183
+ */
1184
+ function TickMath() {}
1185
+ /**
1186
+ * Returns the sqrt ratio as a Q64.96 for the given tick. The sqrt ratio is computed as sqrt(1.0001)^tick
1187
+ * @param tick the tick for which to compute the sqrt ratio
1188
+ */
1189
+
1190
+
1191
+ TickMath.getSqrtRatioAtTick = function getSqrtRatioAtTick(tick) {
1192
+ !(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK && Number.isInteger(tick)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK') : invariant(false) : void 0;
1193
+ var absTick = tick < 0 ? tick * -1 : tick;
1194
+ var ratio = (absTick & 0x1) != 0 ? JSBI.BigInt('0xfffcb933bd6fad37aa2d162d1a594001') : JSBI.BigInt('0x100000000000000000000000000000000');
1195
+ if ((absTick & 0x2) != 0) ratio = mulShift(ratio, '0xfff97272373d413259a46990580e213a');
1196
+ if ((absTick & 0x4) != 0) ratio = mulShift(ratio, '0xfff2e50f5f656932ef12357cf3c7fdcc');
1197
+ if ((absTick & 0x8) != 0) ratio = mulShift(ratio, '0xffe5caca7e10e4e61c3624eaa0941cd0');
1198
+ if ((absTick & 0x10) != 0) ratio = mulShift(ratio, '0xffcb9843d60f6159c9db58835c926644');
1199
+ if ((absTick & 0x20) != 0) ratio = mulShift(ratio, '0xff973b41fa98c081472e6896dfb254c0');
1200
+ if ((absTick & 0x40) != 0) ratio = mulShift(ratio, '0xff2ea16466c96a3843ec78b326b52861');
1201
+ if ((absTick & 0x80) != 0) ratio = mulShift(ratio, '0xfe5dee046a99a2a811c461f1969c3053');
1202
+ if ((absTick & 0x100) != 0) ratio = mulShift(ratio, '0xfcbe86c7900a88aedcffc83b479aa3a4');
1203
+ if ((absTick & 0x200) != 0) ratio = mulShift(ratio, '0xf987a7253ac413176f2b074cf7815e54');
1204
+ if ((absTick & 0x400) != 0) ratio = mulShift(ratio, '0xf3392b0822b70005940c7a398e4b70f3');
1205
+ if ((absTick & 0x800) != 0) ratio = mulShift(ratio, '0xe7159475a2c29b7443b29c7fa6e889d9');
1206
+ if ((absTick & 0x1000) != 0) ratio = mulShift(ratio, '0xd097f3bdfd2022b8845ad8f792aa5825');
1207
+ if ((absTick & 0x2000) != 0) ratio = mulShift(ratio, '0xa9f746462d870fdf8a65dc1f90e061e5');
1208
+ if ((absTick & 0x4000) != 0) ratio = mulShift(ratio, '0x70d869a156d2a1b890bb3df62baf32f7');
1209
+ if ((absTick & 0x8000) != 0) ratio = mulShift(ratio, '0x31be135f97d08fd981231505542fcfa6');
1210
+ if ((absTick & 0x10000) != 0) ratio = mulShift(ratio, '0x9aa508b5b7a84e1c677de54f3e99bc9');
1211
+ if ((absTick & 0x20000) != 0) ratio = mulShift(ratio, '0x5d6af8dedb81196699c329225ee604');
1212
+ if ((absTick & 0x40000) != 0) ratio = mulShift(ratio, '0x2216e584f5fa1ea926041bedfe98');
1213
+ if ((absTick & 0x80000) != 0) ratio = mulShift(ratio, '0x48a170391f7dc42444e8fa2');
1214
+ if (tick > 0) ratio = JSBI.divide(MaxUint256, ratio); // back to Q96
1215
+
1216
+ return JSBI.greaterThan(JSBI.remainder(ratio, Q32), ZERO) ? JSBI.add(JSBI.divide(ratio, Q32), ONE) : JSBI.divide(ratio, Q32);
1217
+ }
1218
+ /**
1219
+ * Returns the tick corresponding to a given sqrt ratio, s.t. #getSqrtRatioAtTick(tick) <= sqrtRatioX96
1220
+ * and #getSqrtRatioAtTick(tick + 1) > sqrtRatioX96
1221
+ * @param sqrtRatioX96 the sqrt ratio as a Q64.96 for which to compute the tick
1222
+ */
1223
+ ;
1224
+
1225
+ TickMath.getTickAtSqrtRatio = function getTickAtSqrtRatio(sqrtRatioX96) {
1226
+ !(JSBI.greaterThanOrEqual(sqrtRatioX96, TickMath.MIN_SQRT_RATIO) && JSBI.lessThan(sqrtRatioX96, TickMath.MAX_SQRT_RATIO)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SQRT_RATIO') : invariant(false) : void 0;
1227
+ var sqrtRatioX128 = JSBI.leftShift(sqrtRatioX96, JSBI.BigInt(32));
1228
+ var msb = mostSignificantBit(sqrtRatioX128);
1229
+ var r;
1230
+
1231
+ if (JSBI.greaterThanOrEqual(JSBI.BigInt(msb), JSBI.BigInt(128))) {
1232
+ r = JSBI.signedRightShift(sqrtRatioX128, JSBI.BigInt(msb - 127));
1233
+ } else {
1234
+ r = JSBI.leftShift(sqrtRatioX128, JSBI.BigInt(127 - msb));
1235
+ }
1236
+
1237
+ var log_2 = JSBI.leftShift(JSBI.subtract(JSBI.BigInt(msb), JSBI.BigInt(128)), JSBI.BigInt(64));
1238
+
1239
+ for (var i = 0; i < 14; i++) {
1240
+ r = JSBI.signedRightShift(JSBI.multiply(r, r), JSBI.BigInt(127));
1241
+ var f = JSBI.signedRightShift(r, JSBI.BigInt(128));
1242
+ log_2 = JSBI.bitwiseOr(log_2, JSBI.leftShift(f, JSBI.BigInt(63 - i)));
1243
+ r = JSBI.signedRightShift(r, f);
1244
+ }
1245
+
1246
+ var log_sqrt10001 = JSBI.multiply(log_2, JSBI.BigInt('255738958999603826347141'));
1247
+ var tickLow = JSBI.toNumber(JSBI.signedRightShift(JSBI.subtract(log_sqrt10001, JSBI.BigInt('3402992956809132418596140100660247210')), JSBI.BigInt(128)));
1248
+ var tickHigh = JSBI.toNumber(JSBI.signedRightShift(JSBI.add(log_sqrt10001, JSBI.BigInt('291339464771989622907027621153398088495')), JSBI.BigInt(128)));
1249
+ return tickLow === tickHigh ? tickLow : JSBI.lessThanOrEqual(TickMath.getSqrtRatioAtTick(tickHigh), sqrtRatioX96) ? tickHigh : tickLow;
1250
+ };
1251
+
1252
+ return TickMath;
1253
+ }();
1254
+ /**
1255
+ * The minimum tick that can be used on any pool.
1256
+ */
1257
+
1258
+ TickMath.MIN_TICK = -887272;
1259
+ /**
1260
+ * The maximum tick that can be used on any pool.
1261
+ */
1262
+
1263
+ TickMath.MAX_TICK = -TickMath.MIN_TICK;
1264
+ /**
1265
+ * The sqrt ratio corresponding to the minimum tick that could be used on any pool.
1266
+ */
1267
+
1268
+ TickMath.MIN_SQRT_RATIO = /*#__PURE__*/JSBI.BigInt('4295128739');
1269
+ /**
1270
+ * The sqrt ratio corresponding to the maximum tick that could be used on any pool.
1271
+ */
1272
+
1273
+ TickMath.MAX_SQRT_RATIO = /*#__PURE__*/JSBI.BigInt('1461446703485210103287273052203988822378723970342');
1274
+
1275
+ /**
1276
+ * This tick data provider does not know how to fetch any tick data. It throws whenever it is required. Useful if you
1277
+ * do not need to load tick data for your use case.
1278
+ */
1279
+ var NoTickDataProvider = /*#__PURE__*/function () {
1280
+ function NoTickDataProvider() {}
1281
+
1282
+ var _proto = NoTickDataProvider.prototype;
1283
+
1284
+ _proto.getTick = /*#__PURE__*/function () {
1285
+ var _getTick = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(_tick) {
1286
+ return runtime_1.wrap(function _callee$(_context) {
1287
+ while (1) {
1288
+ switch (_context.prev = _context.next) {
1289
+ case 0:
1290
+ throw new Error(NoTickDataProvider.ERROR_MESSAGE);
1291
+
1292
+ case 1:
1293
+ case "end":
1294
+ return _context.stop();
1295
+ }
1296
+ }
1297
+ }, _callee);
1298
+ }));
1299
+
1300
+ function getTick(_x) {
1301
+ return _getTick.apply(this, arguments);
1302
+ }
1303
+
1304
+ return getTick;
1305
+ }();
1306
+
1307
+ _proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () {
1308
+ var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(_tick, _lte, _tickSpacing) {
1309
+ return runtime_1.wrap(function _callee2$(_context2) {
1310
+ while (1) {
1311
+ switch (_context2.prev = _context2.next) {
1312
+ case 0:
1313
+ throw new Error(NoTickDataProvider.ERROR_MESSAGE);
1314
+
1315
+ case 1:
1316
+ case "end":
1317
+ return _context2.stop();
1318
+ }
1319
+ }
1320
+ }, _callee2);
1321
+ }));
1322
+
1323
+ function nextInitializedTickWithinOneWord(_x2, _x3, _x4) {
1324
+ return _nextInitializedTickWithinOneWord.apply(this, arguments);
1325
+ }
1326
+
1327
+ return nextInitializedTickWithinOneWord;
1328
+ }();
1329
+
1330
+ return NoTickDataProvider;
1331
+ }();
1332
+ NoTickDataProvider.ERROR_MESSAGE = 'No tick data provider was given';
1333
+
1334
+ /**
1335
+ * Determines if a tick list is sorted
1336
+ * @param list The tick list
1337
+ * @param comparator The comparator
1338
+ * @returns true if sorted
1339
+ */
1340
+ function isSorted(list, comparator) {
1341
+ for (var i = 0; i < list.length - 1; i++) {
1342
+ if (comparator(list[i], list[i + 1]) > 0) {
1343
+ return false;
1344
+ }
1345
+ }
1346
+
1347
+ return true;
1348
+ }
1349
+
1350
+ function tickComparator(a, b) {
1351
+ return a.index - b.index;
1352
+ }
1353
+ /**
1354
+ * Utility methods for interacting with sorted lists of ticks
1355
+ */
1356
+
1357
+
1358
+ var TickList = /*#__PURE__*/function () {
1359
+ /**
1360
+ * Cannot be constructed
1361
+ */
1362
+ function TickList() {}
1363
+
1364
+ TickList.validateList = function validateList(ticks, tickSpacing) {
1365
+ !(tickSpacing > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_SPACING_NONZERO') : invariant(false) : void 0; // ensure ticks are spaced appropriately
1366
+
1367
+ !ticks.every(function (_ref) {
1368
+ var index = _ref.index;
1369
+ return index % tickSpacing === 0;
1370
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_SPACING') : invariant(false) : void 0; // ensure tick liquidity deltas sum to 0
1371
+
1372
+ !JSBI.equal(ticks.reduce(function (accumulator, _ref2) {
1373
+ var liquidityNet = _ref2.liquidityNet;
1374
+ return JSBI.add(accumulator, liquidityNet);
1375
+ }, ZERO), ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO_NET') : invariant(false) : void 0;
1376
+ !isSorted(ticks, tickComparator) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SORTED') : invariant(false) : void 0;
1377
+ };
1378
+
1379
+ TickList.isBelowSmallest = function isBelowSmallest(ticks, tick) {
1380
+ !(ticks.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LENGTH') : invariant(false) : void 0;
1381
+ return tick < ticks[0].index;
1382
+ };
1383
+
1384
+ TickList.isAtOrAboveLargest = function isAtOrAboveLargest(ticks, tick) {
1385
+ !(ticks.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LENGTH') : invariant(false) : void 0;
1386
+ return tick >= ticks[ticks.length - 1].index;
1387
+ };
1388
+
1389
+ TickList.getTick = function getTick(ticks, index) {
1390
+ var tick = ticks[this.binarySearch(ticks, index)];
1391
+ !(tick.index === index) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NOT_CONTAINED') : invariant(false) : void 0;
1392
+ return tick;
1393
+ }
1394
+ /**
1395
+ * Finds the largest tick in the list of ticks that is less than or equal to tick
1396
+ * @param ticks list of ticks
1397
+ * @param tick tick to find the largest tick that is less than or equal to tick
1398
+ * @private
1399
+ */
1400
+ ;
1401
+
1402
+ TickList.binarySearch = function binarySearch(ticks, tick) {
1403
+ !!this.isBelowSmallest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'BELOW_SMALLEST') : invariant(false) : void 0;
1404
+ var l = 0;
1405
+ var r = ticks.length - 1;
1406
+ var i;
1407
+
1408
+ while (true) {
1409
+ i = Math.floor((l + r) / 2);
1410
+
1411
+ if (ticks[i].index <= tick && (i === ticks.length - 1 || ticks[i + 1].index > tick)) {
1412
+ return i;
1413
+ }
1414
+
1415
+ if (ticks[i].index < tick) {
1416
+ l = i + 1;
1417
+ } else {
1418
+ r = i - 1;
1419
+ }
1420
+ }
1421
+ };
1422
+
1423
+ TickList.nextInitializedTick = function nextInitializedTick(ticks, tick, lte) {
1424
+ if (lte) {
1425
+ !!TickList.isBelowSmallest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'BELOW_SMALLEST') : invariant(false) : void 0;
1426
+
1427
+ if (TickList.isAtOrAboveLargest(ticks, tick)) {
1428
+ return ticks[ticks.length - 1];
1429
+ }
1430
+
1431
+ var index = this.binarySearch(ticks, tick);
1432
+ return ticks[index];
1433
+ } else {
1434
+ !!this.isAtOrAboveLargest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'AT_OR_ABOVE_LARGEST') : invariant(false) : void 0;
1435
+
1436
+ if (this.isBelowSmallest(ticks, tick)) {
1437
+ return ticks[0];
1438
+ }
1439
+
1440
+ var _index = this.binarySearch(ticks, tick);
1441
+
1442
+ return ticks[_index + 1];
1443
+ }
1444
+ };
1445
+
1446
+ TickList.nextInitializedTickWithinOneWord = function nextInitializedTickWithinOneWord(ticks, tick, lte, tickSpacing) {
1447
+ var compressed = Math.floor(tick / tickSpacing); // matches rounding in the code
1448
+
1449
+ if (lte) {
1450
+ var wordPos = compressed >> 8;
1451
+ var minimum = (wordPos << 8) * tickSpacing;
1452
+
1453
+ if (TickList.isBelowSmallest(ticks, tick)) {
1454
+ return [minimum, false];
1455
+ }
1456
+
1457
+ var index = TickList.nextInitializedTick(ticks, tick, lte).index;
1458
+ var nextInitializedTick = Math.max(minimum, index);
1459
+ return [nextInitializedTick, nextInitializedTick === index];
1460
+ } else {
1461
+ var _wordPos = compressed + 1 >> 8;
1462
+
1463
+ var maximum = ((_wordPos + 1 << 8) - 1) * tickSpacing;
1464
+
1465
+ if (this.isAtOrAboveLargest(ticks, tick)) {
1466
+ return [maximum, false];
1467
+ }
1468
+
1469
+ var _index2 = this.nextInitializedTick(ticks, tick, lte).index;
1470
+
1471
+ var _nextInitializedTick = Math.min(maximum, _index2);
1472
+
1473
+ return [_nextInitializedTick, _nextInitializedTick === _index2];
1474
+ }
1475
+ };
1476
+
1477
+ return TickList;
1478
+ }();
1479
+
1480
+ /**
1481
+ * Converts a big int to a hex string
1482
+ * @param bigintIsh
1483
+ * @returns The hex encoded calldata
1484
+ */
1485
+
1486
+ function toHex(bigintIsh) {
1487
+ var bigInt = JSBI.BigInt(bigintIsh);
1488
+ var hex = bigInt.toString(16);
1489
+
1490
+ if (hex.length % 2 !== 0) {
1491
+ hex = "0" + hex;
1492
+ }
1493
+
1494
+ return "0x" + hex;
1495
+ }
1496
+
1497
+ /**
1498
+ * Converts a route to a hex encoded path
1499
+ * @param route the v3 path to convert to an encoded path
1500
+ * @param exactOutput whether the route should be encoded in reverse, for making exact output swaps
1501
+ */
1502
+
1503
+ function encodeRouteToPath(route, exactOutput) {
1504
+ var firstInputToken = route.input.wrapped;
1505
+
1506
+ var _route$pools$reduce = route.pools.reduce(function (_ref, pool, index) {
1507
+ var inputToken = _ref.inputToken,
1508
+ path = _ref.path,
1509
+ types = _ref.types;
1510
+ var outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0;
1511
+
1512
+ if (index === 0) {
1513
+ return {
1514
+ inputToken: outputToken,
1515
+ types: ['address', 'uint24', 'address'],
1516
+ path: [inputToken.address, pool.fee, outputToken.address]
1517
+ };
1518
+ } else {
1519
+ return {
1520
+ inputToken: outputToken,
1521
+ types: [].concat(types, ['uint24', 'address']),
1522
+ path: [].concat(path, [pool.fee, outputToken.address])
1523
+ };
1524
+ }
1525
+ }, {
1526
+ inputToken: firstInputToken,
1527
+ path: [],
1528
+ types: []
1529
+ }),
1530
+ path = _route$pools$reduce.path,
1531
+ types = _route$pools$reduce.types;
1532
+
1533
+ return exactOutput ? pack(types.reverse(), path.reverse()) : pack(types, path);
1534
+ }
1535
+
1536
+ /**
1537
+ * Returns the sqrt ratio as a Q64.96 corresponding to a given ratio of amount1 and amount0
1538
+ * @param amount1 The numerator amount i.e., the amount of token1
1539
+ * @param amount0 The denominator amount i.e., the amount of token0
1540
+ * @returns The sqrt ratio
1541
+ */
1542
+
1543
+ function encodeSqrtRatioX96(amount1, amount0) {
1544
+ var numerator = JSBI.leftShift(JSBI.BigInt(amount1), JSBI.BigInt(192));
1545
+ var denominator = JSBI.BigInt(amount0);
1546
+ var ratioX192 = JSBI.divide(numerator, denominator);
1547
+ return sqrt(ratioX192);
1548
+ }
1549
+
1550
+ /**
1551
+ * Returns an imprecise maximum amount of liquidity received for a given amount of token 0.
1552
+ * This function is available to accommodate LiquidityAmounts#getLiquidityForAmount0 in the v3 periphery,
1553
+ * which could be more precise by at least 32 bits by dividing by Q64 instead of Q96 in the intermediate step,
1554
+ * and shifting the subtracted ratio left by 32 bits. This imprecise calculation will likely be replaced in a future
1555
+ * v3 router contract.
1556
+ * @param sqrtRatioAX96 The price at the lower boundary
1557
+ * @param sqrtRatioBX96 The price at the upper boundary
1558
+ * @param amount0 The token0 amount
1559
+ * @returns liquidity for amount0, imprecise
1560
+ */
1561
+
1562
+ function maxLiquidityForAmount0Imprecise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
1563
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
1564
+ var _ref = [sqrtRatioBX96, sqrtRatioAX96];
1565
+ sqrtRatioAX96 = _ref[0];
1566
+ sqrtRatioBX96 = _ref[1];
1567
+ }
1568
+
1569
+ var intermediate = JSBI.divide(JSBI.multiply(sqrtRatioAX96, sqrtRatioBX96), Q96);
1570
+ return JSBI.divide(JSBI.multiply(JSBI.BigInt(amount0), intermediate), JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
1571
+ }
1572
+ /**
1573
+ * 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,
1574
+ * and shifting the subtracted ratio left by 32 bits.
1575
+ * @param sqrtRatioAX96 The price at the lower boundary
1576
+ * @param sqrtRatioBX96 The price at the upper boundary
1577
+ * @param amount0 The token0 amount
1578
+ * @returns liquidity for amount0, precise
1579
+ */
1580
+
1581
+
1582
+ function maxLiquidityForAmount0Precise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
1583
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
1584
+ var _ref2 = [sqrtRatioBX96, sqrtRatioAX96];
1585
+ sqrtRatioAX96 = _ref2[0];
1586
+ sqrtRatioBX96 = _ref2[1];
1587
+ }
1588
+
1589
+ var numerator = JSBI.multiply(JSBI.multiply(JSBI.BigInt(amount0), sqrtRatioAX96), sqrtRatioBX96);
1590
+ var denominator = JSBI.multiply(Q96, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
1591
+ return JSBI.divide(numerator, denominator);
1592
+ }
1593
+ /**
1594
+ * Computes the maximum amount of liquidity received for a given amount of token1
1595
+ * @param sqrtRatioAX96 The price at the lower tick boundary
1596
+ * @param sqrtRatioBX96 The price at the upper tick boundary
1597
+ * @param amount1 The token1 amount
1598
+ * @returns liquidity for amount1
1599
+ */
1600
+
1601
+
1602
+ function maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1) {
1603
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
1604
+ var _ref3 = [sqrtRatioBX96, sqrtRatioAX96];
1605
+ sqrtRatioAX96 = _ref3[0];
1606
+ sqrtRatioBX96 = _ref3[1];
1607
+ }
1608
+
1609
+ return JSBI.divide(JSBI.multiply(JSBI.BigInt(amount1), Q96), JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96));
1610
+ }
1611
+ /**
1612
+ * Computes the maximum amount of liquidity received for a given amount of token0, token1,
1613
+ * and the prices at the tick boundaries.
1614
+ * @param sqrtRatioCurrentX96 the current price
1615
+ * @param sqrtRatioAX96 price at lower boundary
1616
+ * @param sqrtRatioBX96 price at upper boundary
1617
+ * @param amount0 token0 amount
1618
+ * @param amount1 token1 amount
1619
+ * @param useFullPrecision if false, liquidity will be maximized according to what the router can calculate,
1620
+ * not what core can theoretically support
1621
+ */
1622
+
1623
+
1624
+ function maxLiquidityForAmounts(sqrtRatioCurrentX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision) {
1625
+ if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) {
1626
+ var _ref4 = [sqrtRatioBX96, sqrtRatioAX96];
1627
+ sqrtRatioAX96 = _ref4[0];
1628
+ sqrtRatioBX96 = _ref4[1];
1629
+ }
1630
+
1631
+ var maxLiquidityForAmount0 = useFullPrecision ? maxLiquidityForAmount0Precise : maxLiquidityForAmount0Imprecise;
1632
+
1633
+ if (JSBI.lessThanOrEqual(sqrtRatioCurrentX96, sqrtRatioAX96)) {
1634
+ return maxLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
1635
+ } else if (JSBI.lessThan(sqrtRatioCurrentX96, sqrtRatioBX96)) {
1636
+ var liquidity0 = maxLiquidityForAmount0(sqrtRatioCurrentX96, sqrtRatioBX96, amount0);
1637
+ var liquidity1 = maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioCurrentX96, amount1);
1638
+ return JSBI.lessThan(liquidity0, liquidity1) ? liquidity0 : liquidity1;
1639
+ } else {
1640
+ return maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
1641
+ }
1642
+ }
1643
+
1644
+ /**
1645
+ * Returns the closest tick that is nearest a given tick and usable for the given tick spacing
1646
+ * @param tick the target tick
1647
+ * @param tickSpacing the spacing of the pool
1648
+ */
1649
+
1650
+ function nearestUsableTick(tick, tickSpacing) {
1651
+ !(Number.isInteger(tick) && Number.isInteger(tickSpacing)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INTEGERS') : invariant(false) : void 0;
1652
+ !(tickSpacing > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_SPACING') : invariant(false) : void 0;
1653
+ !(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_BOUND') : invariant(false) : void 0;
1654
+ var rounded = Math.round(tick / tickSpacing) * tickSpacing;
1655
+ if (rounded < TickMath.MIN_TICK) return rounded + tickSpacing;else if (rounded > TickMath.MAX_TICK) return rounded - tickSpacing;else return rounded;
1656
+ }
1657
+
1658
+ var Q128 = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(128));
1659
+ var PositionLibrary = /*#__PURE__*/function () {
1660
+ /**
1661
+ * Cannot be constructed.
1662
+ */
1663
+ function PositionLibrary() {} // replicates the portions of Position#update required to compute unaccounted fees
1664
+
1665
+
1666
+ PositionLibrary.getTokensOwed = function getTokensOwed(feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, feeGrowthInside0X128, feeGrowthInside1X128) {
1667
+ var tokensOwed0 = JSBI.divide(JSBI.multiply(subIn256(feeGrowthInside0X128, feeGrowthInside0LastX128), liquidity), Q128);
1668
+ var tokensOwed1 = JSBI.divide(JSBI.multiply(subIn256(feeGrowthInside1X128, feeGrowthInside1LastX128), liquidity), Q128);
1669
+ return [tokensOwed0, tokensOwed1];
1670
+ };
1671
+
1672
+ return PositionLibrary;
1673
+ }();
1674
+
1675
+ /**
1676
+ * Returns a price object corresponding to the input tick and the base/quote token
1677
+ * Inputs must be tokens because the address order is used to interpret the price represented by the tick
1678
+ * @param baseToken the base token of the price
1679
+ * @param quoteToken the quote token of the price
1680
+ * @param tick the tick for which to return the price
1681
+ */
1682
+
1683
+ function tickToPrice(baseToken, quoteToken, tick) {
1684
+ var sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
1685
+ var ratioX192 = JSBI.multiply(sqrtRatioX96, sqrtRatioX96);
1686
+ return baseToken.sortsBefore(quoteToken) ? new Price(baseToken, quoteToken, Q192, ratioX192) : new Price(baseToken, quoteToken, ratioX192, Q192);
1687
+ }
1688
+ /**
1689
+ * Returns the first tick for which the given price is greater than or equal to the tick price
1690
+ * @param price for which to return the closest tick that represents a price less than or equal to the input price,
1691
+ * i.e. the price of the returned tick is less than or equal to the input price
1692
+ */
1693
+
1694
+ function priceToClosestTick(price) {
1695
+ var sorted = price.baseCurrency.sortsBefore(price.quoteCurrency);
1696
+ var sqrtRatioX96 = sorted ? encodeSqrtRatioX96(price.numerator, price.denominator) : encodeSqrtRatioX96(price.denominator, price.numerator);
1697
+ var tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1698
+ var nextTickPrice = tickToPrice(price.baseCurrency, price.quoteCurrency, tick + 1);
1699
+
1700
+ if (sorted) {
1701
+ if (!price.lessThan(nextTickPrice)) {
1702
+ tick++;
1703
+ }
1704
+ } else {
1705
+ if (!price.greaterThan(nextTickPrice)) {
1706
+ tick++;
1707
+ }
1708
+ }
1709
+
1710
+ return tick;
1711
+ }
1712
+
1713
+ var Q256 = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(256));
1714
+ function subIn256(x, y) {
1715
+ var difference = JSBI.subtract(x, y);
1716
+
1717
+ if (JSBI.lessThan(difference, ZERO)) {
1718
+ return JSBI.add(Q256, difference);
1719
+ } else {
1720
+ return difference;
1721
+ }
1722
+ }
1723
+ var TickLibrary = /*#__PURE__*/function () {
1724
+ /**
1725
+ * Cannot be constructed.
1726
+ */
1727
+ function TickLibrary() {}
1728
+
1729
+ TickLibrary.getFeeGrowthInside = function getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) {
1730
+ var feeGrowthBelow0X128;
1731
+ var feeGrowthBelow1X128;
1732
+
1733
+ if (tickCurrent >= tickLower) {
1734
+ feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128;
1735
+ feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128;
1736
+ } else {
1737
+ feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128);
1738
+ feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128);
1739
+ }
1740
+
1741
+ var feeGrowthAbove0X128;
1742
+ var feeGrowthAbove1X128;
1743
+
1744
+ if (tickCurrent < tickUpper) {
1745
+ feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128;
1746
+ feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128;
1747
+ } else {
1748
+ feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128);
1749
+ feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128);
1750
+ }
1751
+
1752
+ return [subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128), subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)];
1753
+ };
1754
+
1755
+ return TickLibrary;
1756
+ }();
1757
+
1758
+ var Tick = function Tick(_ref) {
1759
+ var index = _ref.index,
1760
+ liquidityGross = _ref.liquidityGross,
1761
+ liquidityNet = _ref.liquidityNet;
1762
+ !(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK') : invariant(false) : void 0;
1763
+ this.index = index;
1764
+ this.liquidityGross = JSBI.BigInt(liquidityGross);
1765
+ this.liquidityNet = JSBI.BigInt(liquidityNet);
1766
+ };
1767
+
1768
+ /**
1769
+ * A data provider for ticks that is backed by an in-memory array of ticks.
1770
+ */
1771
+
1772
+ var TickListDataProvider = /*#__PURE__*/function () {
1773
+ function TickListDataProvider(ticks, tickSpacing) {
1774
+ var ticksMapped = ticks.map(function (t) {
1775
+ return t instanceof Tick ? t : new Tick(t);
1776
+ });
1777
+ TickList.validateList(ticksMapped, tickSpacing);
1778
+ this.ticks = ticksMapped;
1779
+ }
1780
+
1781
+ var _proto = TickListDataProvider.prototype;
1782
+
1783
+ _proto.getTick = /*#__PURE__*/function () {
1784
+ var _getTick = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(tick) {
1785
+ return runtime_1.wrap(function _callee$(_context) {
1786
+ while (1) {
1787
+ switch (_context.prev = _context.next) {
1788
+ case 0:
1789
+ return _context.abrupt("return", TickList.getTick(this.ticks, tick));
1790
+
1791
+ case 1:
1792
+ case "end":
1793
+ return _context.stop();
1794
+ }
1795
+ }
1796
+ }, _callee, this);
1797
+ }));
1798
+
1799
+ function getTick(_x) {
1800
+ return _getTick.apply(this, arguments);
1801
+ }
1802
+
1803
+ return getTick;
1804
+ }();
1805
+
1806
+ _proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () {
1807
+ var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(tick, lte, tickSpacing) {
1808
+ return runtime_1.wrap(function _callee2$(_context2) {
1809
+ while (1) {
1810
+ switch (_context2.prev = _context2.next) {
1811
+ case 0:
1812
+ return _context2.abrupt("return", TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing));
1813
+
1814
+ case 1:
1815
+ case "end":
1816
+ return _context2.stop();
1817
+ }
1818
+ }
1819
+ }, _callee2, this);
1820
+ }));
1821
+
1822
+ function nextInitializedTickWithinOneWord(_x2, _x3, _x4) {
1823
+ return _nextInitializedTickWithinOneWord.apply(this, arguments);
1824
+ }
1825
+
1826
+ return nextInitializedTickWithinOneWord;
1827
+ }();
1828
+
1829
+ return TickListDataProvider;
1830
+ }();
1831
+
1832
+ /**
1833
+ * By default, pools will not allow operations that require ticks.
1834
+ */
1835
+
1836
+ var NO_TICK_DATA_PROVIDER_DEFAULT = /*#__PURE__*/new NoTickDataProvider();
1837
+ /**
1838
+ * Represents a V3 pool
1839
+ */
1840
+
1841
+ var Pool = /*#__PURE__*/function () {
1842
+ /**
1843
+ * Construct a pool
1844
+ * @param tokenA One of the tokens in the pool
1845
+ * @param tokenB The other token in the pool
1846
+ * @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
1847
+ * @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0
1848
+ * @param liquidity The current value of in range liquidity
1849
+ * @param tickCurrent The current tick of the pool
1850
+ * @param ticks The current state of the pool ticks or a data provider that can return tick data
1851
+ */
1852
+ function Pool(tokenA, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks) {
1853
+ if (ticks === void 0) {
1854
+ ticks = NO_TICK_DATA_PROVIDER_DEFAULT;
1855
+ }
1856
+
1857
+ !(Number.isInteger(fee) && fee < 1000000) ? process.env.NODE_ENV !== "production" ? invariant(false, 'FEE') : invariant(false) : void 0;
1858
+ var tickCurrentSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent);
1859
+ var nextTickSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent + 1);
1860
+ !(JSBI.greaterThanOrEqual(JSBI.BigInt(sqrtRatioX96), tickCurrentSqrtRatioX96) && JSBI.lessThanOrEqual(JSBI.BigInt(sqrtRatioX96), nextTickSqrtRatioX96)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PRICE_BOUNDS') : invariant(false) : void 0;
1861
+
1862
+ var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
1863
+
1864
+ this.token0 = _ref[0];
1865
+ this.token1 = _ref[1];
1866
+ this.fee = fee;
1867
+ this.sqrtRatioX96 = JSBI.BigInt(sqrtRatioX96);
1868
+ this.liquidity = JSBI.BigInt(liquidity);
1869
+ this.tickCurrent = tickCurrent;
1870
+ this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks, TICK_SPACINGS[fee]) : ticks;
1871
+ }
1872
+
1873
+ Pool.getAddress = function getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, factoryAddressOverride) {
1874
+ return computePoolAddress({
1875
+ factoryAddress: factoryAddressOverride != null ? factoryAddressOverride : FACTORY_ADDRESS,
1876
+ fee: fee,
1877
+ tokenA: tokenA,
1878
+ tokenB: tokenB,
1879
+ initCodeHashManualOverride: initCodeHashManualOverride
1880
+ });
1881
+ }
1882
+ /**
1883
+ * Returns true if the token is either token0 or token1
1884
+ * @param token The token to check
1885
+ * @returns True if token is either token0 or token
1886
+ */
1887
+ ;
1888
+
1889
+ var _proto = Pool.prototype;
1890
+
1891
+ _proto.involvesToken = function involvesToken(token) {
1892
+ return token.equals(this.token0) || token.equals(this.token1);
1893
+ }
1894
+ /**
1895
+ * Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0
1896
+ */
1897
+ ;
1898
+
1899
+ /**
1900
+ * Return the price of the given token in terms of the other token in the pool.
1901
+ * @param token The token to return price of
1902
+ * @returns The price of the given token, in terms of the other.
1903
+ */
1904
+ _proto.priceOf = function priceOf(token) {
1905
+ !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
1906
+ return token.equals(this.token0) ? this.token0Price : this.token1Price;
1907
+ }
1908
+ /**
1909
+ * Returns the chain ID of the tokens in the pool.
1910
+ */
1911
+ ;
1912
+
1913
+ /**
1914
+ * Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade
1915
+ * @param inputAmount The input amount for which to quote the output amount
1916
+ * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit
1917
+ * @returns The output amount and the pool with updated state
1918
+ */
1919
+ _proto.getOutputAmount =
1920
+ /*#__PURE__*/
1921
+ function () {
1922
+ var _getOutputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(inputAmount, sqrtPriceLimitX96) {
1923
+ var zeroForOne, _yield$this$swap, outputAmount, sqrtRatioX96, liquidity, tickCurrent, outputToken;
1924
+
1925
+ return runtime_1.wrap(function _callee$(_context) {
1926
+ while (1) {
1927
+ switch (_context.prev = _context.next) {
1928
+ case 0:
1929
+ !this.involvesToken(inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
1930
+ zeroForOne = inputAmount.currency.equals(this.token0);
1931
+ _context.next = 4;
1932
+ return this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96);
1933
+
1934
+ case 4:
1935
+ _yield$this$swap = _context.sent;
1936
+ outputAmount = _yield$this$swap.amountCalculated;
1937
+ sqrtRatioX96 = _yield$this$swap.sqrtRatioX96;
1938
+ liquidity = _yield$this$swap.liquidity;
1939
+ tickCurrent = _yield$this$swap.tickCurrent;
1940
+ outputToken = zeroForOne ? this.token1 : this.token0;
1941
+ return _context.abrupt("return", [CurrencyAmount.fromRawAmount(outputToken, JSBI.multiply(outputAmount, NEGATIVE_ONE)), new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]);
1942
+
1943
+ case 11:
1944
+ case "end":
1945
+ return _context.stop();
1946
+ }
1947
+ }
1948
+ }, _callee, this);
1949
+ }));
1950
+
1951
+ function getOutputAmount(_x, _x2) {
1952
+ return _getOutputAmount.apply(this, arguments);
1953
+ }
1954
+
1955
+ return getOutputAmount;
1956
+ }()
1957
+ /**
1958
+ * Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade
1959
+ * @param outputAmount the output amount for which to quote the input amount
1960
+ * @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
1961
+ * @returns The input amount and the pool with updated state
1962
+ */
1963
+ ;
1964
+
1965
+ _proto.getInputAmount =
1966
+ /*#__PURE__*/
1967
+ function () {
1968
+ var _getInputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(outputAmount, sqrtPriceLimitX96) {
1969
+ var zeroForOne, _yield$this$swap2, inputAmount, sqrtRatioX96, liquidity, tickCurrent, inputToken;
1970
+
1971
+ return runtime_1.wrap(function _callee2$(_context2) {
1972
+ while (1) {
1973
+ switch (_context2.prev = _context2.next) {
1974
+ case 0:
1975
+ !(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
1976
+ zeroForOne = outputAmount.currency.equals(this.token1);
1977
+ _context2.next = 4;
1978
+ return this.swap(zeroForOne, JSBI.multiply(outputAmount.quotient, NEGATIVE_ONE), sqrtPriceLimitX96);
1979
+
1980
+ case 4:
1981
+ _yield$this$swap2 = _context2.sent;
1982
+ inputAmount = _yield$this$swap2.amountCalculated;
1983
+ sqrtRatioX96 = _yield$this$swap2.sqrtRatioX96;
1984
+ liquidity = _yield$this$swap2.liquidity;
1985
+ tickCurrent = _yield$this$swap2.tickCurrent;
1986
+ inputToken = zeroForOne ? this.token0 : this.token1;
1987
+ return _context2.abrupt("return", [CurrencyAmount.fromRawAmount(inputToken, inputAmount), new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]);
1988
+
1989
+ case 11:
1990
+ case "end":
1991
+ return _context2.stop();
1992
+ }
1993
+ }
1994
+ }, _callee2, this);
1995
+ }));
1996
+
1997
+ function getInputAmount(_x3, _x4) {
1998
+ return _getInputAmount.apply(this, arguments);
1999
+ }
2000
+
2001
+ return getInputAmount;
2002
+ }()
2003
+ /**
2004
+ * Executes a swap
2005
+ * @param zeroForOne Whether the amount in is token0 or token1
2006
+ * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
2007
+ * @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
2008
+ * @returns amountCalculated
2009
+ * @returns sqrtRatioX96
2010
+ * @returns liquidity
2011
+ * @returns tickCurrent
2012
+ */
2013
+ ;
2014
+
2015
+ _proto.swap =
2016
+ /*#__PURE__*/
2017
+ function () {
2018
+ var _swap = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
2019
+ var exactInput, state, step, _yield$this$tickDataP, _SwapMath$computeSwap, liquidityNet;
2020
+
2021
+ return runtime_1.wrap(function _callee3$(_context3) {
2022
+ while (1) {
2023
+ switch (_context3.prev = _context3.next) {
2024
+ case 0:
2025
+ if (!sqrtPriceLimitX96) sqrtPriceLimitX96 = zeroForOne ? JSBI.add(TickMath.MIN_SQRT_RATIO, ONE) : JSBI.subtract(TickMath.MAX_SQRT_RATIO, ONE);
2026
+
2027
+ if (zeroForOne) {
2028
+ !JSBI.greaterThan(sqrtPriceLimitX96, TickMath.MIN_SQRT_RATIO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'RATIO_MIN') : invariant(false) : void 0;
2029
+ !JSBI.lessThan(sqrtPriceLimitX96, this.sqrtRatioX96) ? process.env.NODE_ENV !== "production" ? invariant(false, 'RATIO_CURRENT') : invariant(false) : void 0;
2030
+ } else {
2031
+ !JSBI.lessThan(sqrtPriceLimitX96, TickMath.MAX_SQRT_RATIO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'RATIO_MAX') : invariant(false) : void 0;
2032
+ !JSBI.greaterThan(sqrtPriceLimitX96, this.sqrtRatioX96) ? process.env.NODE_ENV !== "production" ? invariant(false, 'RATIO_CURRENT') : invariant(false) : void 0;
2033
+ }
2034
+
2035
+ exactInput = JSBI.greaterThanOrEqual(amountSpecified, ZERO); // keep track of swap state
2036
+
2037
+ state = {
2038
+ amountSpecifiedRemaining: amountSpecified,
2039
+ amountCalculated: ZERO,
2040
+ sqrtPriceX96: this.sqrtRatioX96,
2041
+ tick: this.tickCurrent,
2042
+ liquidity: this.liquidity
2043
+ }; // start swap while loop
2044
+
2045
+ case 4:
2046
+ if (!(JSBI.notEqual(state.amountSpecifiedRemaining, ZERO) && state.sqrtPriceX96 != sqrtPriceLimitX96)) {
2047
+ _context3.next = 35;
2048
+ break;
2049
+ }
2050
+
2051
+ step = {};
2052
+ step.sqrtPriceStartX96 = state.sqrtPriceX96;
2053
+ _context3.next = 9;
2054
+ return this.tickDataProvider.nextInitializedTickWithinOneWord(state.tick, zeroForOne, this.tickSpacing);
2055
+
2056
+ case 9:
2057
+ _yield$this$tickDataP = _context3.sent;
2058
+ step.tickNext = _yield$this$tickDataP[0];
2059
+ step.initialized = _yield$this$tickDataP[1];
2060
+
2061
+ if (step.tickNext < TickMath.MIN_TICK) {
2062
+ step.tickNext = TickMath.MIN_TICK;
2063
+ } else if (step.tickNext > TickMath.MAX_TICK) {
2064
+ step.tickNext = TickMath.MAX_TICK;
2065
+ }
2066
+
2067
+ step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
2068
+ _SwapMath$computeSwap = SwapMath.computeSwapStep(state.sqrtPriceX96, (zeroForOne ? JSBI.lessThan(step.sqrtPriceNextX96, sqrtPriceLimitX96) : JSBI.greaterThan(step.sqrtPriceNextX96, sqrtPriceLimitX96)) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96, state.liquidity, state.amountSpecifiedRemaining, this.fee);
2069
+ state.sqrtPriceX96 = _SwapMath$computeSwap[0];
2070
+ step.amountIn = _SwapMath$computeSwap[1];
2071
+ step.amountOut = _SwapMath$computeSwap[2];
2072
+ step.feeAmount = _SwapMath$computeSwap[3];
2073
+
2074
+ if (exactInput) {
2075
+ state.amountSpecifiedRemaining = JSBI.subtract(state.amountSpecifiedRemaining, JSBI.add(step.amountIn, step.feeAmount));
2076
+ state.amountCalculated = JSBI.subtract(state.amountCalculated, step.amountOut);
2077
+ } else {
2078
+ state.amountSpecifiedRemaining = JSBI.add(state.amountSpecifiedRemaining, step.amountOut);
2079
+ state.amountCalculated = JSBI.add(state.amountCalculated, JSBI.add(step.amountIn, step.feeAmount));
2080
+ } // TODO
2081
+
2082
+
2083
+ if (!JSBI.equal(state.sqrtPriceX96, step.sqrtPriceNextX96)) {
2084
+ _context3.next = 32;
2085
+ break;
2086
+ }
2087
+
2088
+ if (!step.initialized) {
2089
+ _context3.next = 29;
2090
+ break;
2091
+ }
2092
+
2093
+ _context3.t0 = JSBI;
2094
+ _context3.next = 25;
2095
+ return this.tickDataProvider.getTick(step.tickNext);
2096
+
2097
+ case 25:
2098
+ _context3.t1 = _context3.sent.liquidityNet;
2099
+ liquidityNet = _context3.t0.BigInt.call(_context3.t0, _context3.t1);
2100
+ // if we're moving leftward, we interpret liquidityNet as the opposite sign
2101
+ // safe because liquidityNet cannot be type(int128).min
2102
+ if (zeroForOne) liquidityNet = JSBI.multiply(liquidityNet, NEGATIVE_ONE);
2103
+ state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
2104
+
2105
+ case 29:
2106
+ state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
2107
+ _context3.next = 33;
2108
+ break;
2109
+
2110
+ case 32:
2111
+ if (JSBI.notEqual(state.sqrtPriceX96, step.sqrtPriceStartX96)) {
2112
+ // updated comparison function
2113
+ // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
2114
+ state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
2115
+ }
2116
+
2117
+ case 33:
2118
+ _context3.next = 4;
2119
+ break;
2120
+
2121
+ case 35:
2122
+ return _context3.abrupt("return", {
2123
+ amountCalculated: state.amountCalculated,
2124
+ sqrtRatioX96: state.sqrtPriceX96,
2125
+ liquidity: state.liquidity,
2126
+ tickCurrent: state.tick
2127
+ });
2128
+
2129
+ case 36:
2130
+ case "end":
2131
+ return _context3.stop();
2132
+ }
2133
+ }
2134
+ }, _callee3, this);
2135
+ }));
2136
+
2137
+ function swap(_x5, _x6, _x7) {
2138
+ return _swap.apply(this, arguments);
2139
+ }
2140
+
2141
+ return swap;
2142
+ }();
2143
+
2144
+ _createClass(Pool, [{
2145
+ key: "token0Price",
2146
+ get: function get() {
2147
+ var _this$_token0Price;
2148
+
2149
+ return (_this$_token0Price = this._token0Price) != null ? _this$_token0Price : this._token0Price = new Price(this.token0, this.token1, Q192, JSBI.multiply(this.sqrtRatioX96, this.sqrtRatioX96));
2150
+ }
2151
+ /**
2152
+ * Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1
2153
+ */
2154
+
2155
+ }, {
2156
+ key: "token1Price",
2157
+ get: function get() {
2158
+ var _this$_token1Price;
2159
+
2160
+ return (_this$_token1Price = this._token1Price) != null ? _this$_token1Price : this._token1Price = new Price(this.token1, this.token0, JSBI.multiply(this.sqrtRatioX96, this.sqrtRatioX96), Q192);
2161
+ }
2162
+ }, {
2163
+ key: "chainId",
2164
+ get: function get() {
2165
+ return this.token0.chainId;
2166
+ }
2167
+ }, {
2168
+ key: "tickSpacing",
2169
+ get: function get() {
2170
+ return TICK_SPACINGS[this.fee];
2171
+ }
2172
+ }]);
2173
+
2174
+ return Pool;
2175
+ }();
2176
+
2177
+ /**
2178
+ * Represents a position on a Uniswap V3 Pool
2179
+ */
2180
+
2181
+ var Position = /*#__PURE__*/function () {
2182
+ /**
2183
+ * Constructs a position for a given pool with the given liquidity
2184
+ * @param pool For which pool the liquidity is assigned
2185
+ * @param liquidity The amount of liquidity that is in the position
2186
+ * @param tickLower The lower tick of the position
2187
+ * @param tickUpper The upper tick of the position
2188
+ */
2189
+ function Position(_ref) {
2190
+ var pool = _ref.pool,
2191
+ liquidity = _ref.liquidity,
2192
+ tickLower = _ref.tickLower,
2193
+ tickUpper = _ref.tickUpper;
2194
+ // cached resuts for the getters
2195
+ this._token0Amount = null;
2196
+ this._token1Amount = null;
2197
+ this._mintAmounts = null;
2198
+ !(tickLower < tickUpper) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_ORDER') : invariant(false) : void 0;
2199
+ !(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_LOWER') : invariant(false) : void 0;
2200
+ !(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_UPPER') : invariant(false) : void 0;
2201
+ this.pool = pool;
2202
+ this.tickLower = tickLower;
2203
+ this.tickUpper = tickUpper;
2204
+ this.liquidity = JSBI.BigInt(liquidity);
2205
+ }
2206
+ /**
2207
+ * Returns the price of token0 at the lower tick
2208
+ */
2209
+
2210
+
2211
+ var _proto = Position.prototype;
2212
+
2213
+ /**
2214
+ * Returns the lower and upper sqrt ratios if the price 'slips' up to slippage tolerance percentage
2215
+ * @param slippageTolerance The amount by which the price can 'slip' before the transaction will revert
2216
+ * @returns The sqrt ratios after slippage
2217
+ */
2218
+ _proto.ratiosAfterSlippage = function ratiosAfterSlippage(slippageTolerance) {
2219
+ var priceLower = this.pool.token0Price.asFraction.multiply(new Percent(1).subtract(slippageTolerance));
2220
+ var priceUpper = this.pool.token0Price.asFraction.multiply(slippageTolerance.add(1));
2221
+ var sqrtRatioX96Lower = encodeSqrtRatioX96(priceLower.numerator, priceLower.denominator);
2222
+
2223
+ if (JSBI.lessThanOrEqual(sqrtRatioX96Lower, TickMath.MIN_SQRT_RATIO)) {
2224
+ sqrtRatioX96Lower = JSBI.add(TickMath.MIN_SQRT_RATIO, JSBI.BigInt(1));
2225
+ }
2226
+
2227
+ var sqrtRatioX96Upper = encodeSqrtRatioX96(priceUpper.numerator, priceUpper.denominator);
2228
+
2229
+ if (JSBI.greaterThanOrEqual(sqrtRatioX96Upper, TickMath.MAX_SQRT_RATIO)) {
2230
+ sqrtRatioX96Upper = JSBI.subtract(TickMath.MAX_SQRT_RATIO, JSBI.BigInt(1));
2231
+ }
2232
+
2233
+ return {
2234
+ sqrtRatioX96Lower: sqrtRatioX96Lower,
2235
+ sqrtRatioX96Upper: sqrtRatioX96Upper
2236
+ };
2237
+ }
2238
+ /**
2239
+ * Returns the minimum amounts that must be sent in order to safely mint the amount of liquidity held by the position
2240
+ * with the given slippage tolerance
2241
+ * @param slippageTolerance Tolerance of unfavorable slippage from the current price
2242
+ * @returns The amounts, with slippage
2243
+ */
2244
+ ;
2245
+
2246
+ _proto.mintAmountsWithSlippage = function mintAmountsWithSlippage(slippageTolerance) {
2247
+ // get lower/upper prices
2248
+ var _this$ratiosAfterSlip = this.ratiosAfterSlippage(slippageTolerance),
2249
+ sqrtRatioX96Upper = _this$ratiosAfterSlip.sqrtRatioX96Upper,
2250
+ sqrtRatioX96Lower = _this$ratiosAfterSlip.sqrtRatioX96Lower; // construct counterfactual pools
2251
+
2252
+
2253
+ var poolLower = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Lower, 0
2254
+ /* liquidity doesn't matter */
2255
+ , TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower));
2256
+ var poolUpper = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Upper, 0
2257
+ /* liquidity doesn't matter */
2258
+ , TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper)); // because the router is imprecise, we need to calculate the position that will be created (assuming no slippage)
2259
+
2260
+ var positionThatWillBeCreated = Position.fromAmounts(_extends({
2261
+ pool: this.pool,
2262
+ tickLower: this.tickLower,
2263
+ tickUpper: this.tickUpper
2264
+ }, this.mintAmounts, {
2265
+ useFullPrecision: false
2266
+ })); // we want the smaller amounts...
2267
+ // ...which occurs at the upper price for amount0...
2268
+
2269
+ var amount0 = new Position({
2270
+ pool: poolUpper,
2271
+ liquidity: positionThatWillBeCreated.liquidity,
2272
+ tickLower: this.tickLower,
2273
+ tickUpper: this.tickUpper
2274
+ }).mintAmounts.amount0; // ...and the lower for amount1
2275
+
2276
+ var amount1 = new Position({
2277
+ pool: poolLower,
2278
+ liquidity: positionThatWillBeCreated.liquidity,
2279
+ tickLower: this.tickLower,
2280
+ tickUpper: this.tickUpper
2281
+ }).mintAmounts.amount1;
2282
+ return {
2283
+ amount0: amount0,
2284
+ amount1: amount1
2285
+ };
2286
+ }
2287
+ /**
2288
+ * Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the
2289
+ * position with the given slippage tolerance
2290
+ * @param slippageTolerance tolerance of unfavorable slippage from the current price
2291
+ * @returns The amounts, with slippage
2292
+ */
2293
+ ;
2294
+
2295
+ _proto.burnAmountsWithSlippage = function burnAmountsWithSlippage(slippageTolerance) {
2296
+ // get lower/upper prices
2297
+ var _this$ratiosAfterSlip2 = this.ratiosAfterSlippage(slippageTolerance),
2298
+ sqrtRatioX96Upper = _this$ratiosAfterSlip2.sqrtRatioX96Upper,
2299
+ sqrtRatioX96Lower = _this$ratiosAfterSlip2.sqrtRatioX96Lower; // construct counterfactual pools
2300
+
2301
+
2302
+ var poolLower = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Lower, 0
2303
+ /* liquidity doesn't matter */
2304
+ , TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower));
2305
+ var poolUpper = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, sqrtRatioX96Upper, 0
2306
+ /* liquidity doesn't matter */
2307
+ , TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper)); // we want the smaller amounts...
2308
+ // ...which occurs at the upper price for amount0...
2309
+
2310
+ var amount0 = new Position({
2311
+ pool: poolUpper,
2312
+ liquidity: this.liquidity,
2313
+ tickLower: this.tickLower,
2314
+ tickUpper: this.tickUpper
2315
+ }).amount0; // ...and the lower for amount1
2316
+
2317
+ var amount1 = new Position({
2318
+ pool: poolLower,
2319
+ liquidity: this.liquidity,
2320
+ tickLower: this.tickLower,
2321
+ tickUpper: this.tickUpper
2322
+ }).amount1;
2323
+ return {
2324
+ amount0: amount0.quotient,
2325
+ amount1: amount1.quotient
2326
+ };
2327
+ }
2328
+ /**
2329
+ * Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at
2330
+ * the current price for the pool
2331
+ */
2332
+ ;
2333
+
2334
+ /**
2335
+ * Computes the maximum amount of liquidity received for a given amount of token0, token1,
2336
+ * and the prices at the tick boundaries.
2337
+ * @param pool The pool for which the position should be created
2338
+ * @param tickLower The lower tick of the position
2339
+ * @param tickUpper The upper tick of the position
2340
+ * @param amount0 token0 amount
2341
+ * @param amount1 token1 amount
2342
+ * @param useFullPrecision If false, liquidity will be maximized according to what the router can calculate,
2343
+ * not what core can theoretically support
2344
+ * @returns The amount of liquidity for the position
2345
+ */
2346
+ Position.fromAmounts = function fromAmounts(_ref2) {
2347
+ var pool = _ref2.pool,
2348
+ tickLower = _ref2.tickLower,
2349
+ tickUpper = _ref2.tickUpper,
2350
+ amount0 = _ref2.amount0,
2351
+ amount1 = _ref2.amount1,
2352
+ useFullPrecision = _ref2.useFullPrecision;
2353
+ var sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
2354
+ var sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
2355
+ return new Position({
2356
+ pool: pool,
2357
+ tickLower: tickLower,
2358
+ tickUpper: tickUpper,
2359
+ liquidity: maxLiquidityForAmounts(pool.sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision)
2360
+ });
2361
+ }
2362
+ /**
2363
+ * Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1
2364
+ * @param pool The pool for which the position is created
2365
+ * @param tickLower The lower tick
2366
+ * @param tickUpper The upper tick
2367
+ * @param amount0 The desired amount of token0
2368
+ * @param useFullPrecision If true, liquidity will be maximized according to what the router can calculate,
2369
+ * not what core can theoretically support
2370
+ * @returns The position
2371
+ */
2372
+ ;
2373
+
2374
+ Position.fromAmount0 = function fromAmount0(_ref3) {
2375
+ var pool = _ref3.pool,
2376
+ tickLower = _ref3.tickLower,
2377
+ tickUpper = _ref3.tickUpper,
2378
+ amount0 = _ref3.amount0,
2379
+ useFullPrecision = _ref3.useFullPrecision;
2380
+ return Position.fromAmounts({
2381
+ pool: pool,
2382
+ tickLower: tickLower,
2383
+ tickUpper: tickUpper,
2384
+ amount0: amount0,
2385
+ amount1: MaxUint256,
2386
+ useFullPrecision: useFullPrecision
2387
+ });
2388
+ }
2389
+ /**
2390
+ * Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
2391
+ * @param pool The pool for which the position is created
2392
+ * @param tickLower The lower tick
2393
+ * @param tickUpper The upper tick
2394
+ * @param amount1 The desired amount of token1
2395
+ * @returns The position
2396
+ */
2397
+ ;
2398
+
2399
+ Position.fromAmount1 = function fromAmount1(_ref4) {
2400
+ var pool = _ref4.pool,
2401
+ tickLower = _ref4.tickLower,
2402
+ tickUpper = _ref4.tickUpper,
2403
+ amount1 = _ref4.amount1;
2404
+ // this function always uses full precision,
2405
+ return Position.fromAmounts({
2406
+ pool: pool,
2407
+ tickLower: tickLower,
2408
+ tickUpper: tickUpper,
2409
+ amount0: MaxUint256,
2410
+ amount1: amount1,
2411
+ useFullPrecision: true
2412
+ });
2413
+ };
2414
+
2415
+ _createClass(Position, [{
2416
+ key: "token0PriceLower",
2417
+ get: function get() {
2418
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickLower);
2419
+ }
2420
+ /**
2421
+ * Returns the price of token0 at the upper tick
2422
+ */
2423
+
2424
+ }, {
2425
+ key: "token0PriceUpper",
2426
+ get: function get() {
2427
+ return tickToPrice(this.pool.token0, this.pool.token1, this.tickUpper);
2428
+ }
2429
+ /**
2430
+ * Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
2431
+ */
2432
+
2433
+ }, {
2434
+ key: "amount0",
2435
+ get: function get() {
2436
+ if (this._token0Amount === null) {
2437
+ if (this.pool.tickCurrent < this.tickLower) {
2438
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.token0, SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
2439
+ } else if (this.pool.tickCurrent < this.tickUpper) {
2440
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.token0, SqrtPriceMath.getAmount0Delta(this.pool.sqrtRatioX96, TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
2441
+ } else {
2442
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.token0, ZERO);
2443
+ }
2444
+ }
2445
+
2446
+ return this._token0Amount;
2447
+ }
2448
+ /**
2449
+ * Returns the amount of token1 that this position's liquidity could be burned for at the current pool price
2450
+ */
2451
+
2452
+ }, {
2453
+ key: "amount1",
2454
+ get: function get() {
2455
+ if (this._token1Amount === null) {
2456
+ if (this.pool.tickCurrent < this.tickLower) {
2457
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.token1, ZERO);
2458
+ } else if (this.pool.tickCurrent < this.tickUpper) {
2459
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.token1, SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), this.pool.sqrtRatioX96, this.liquidity, false));
2460
+ } else {
2461
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.token1, SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
2462
+ }
2463
+ }
2464
+
2465
+ return this._token1Amount;
2466
+ }
2467
+ }, {
2468
+ key: "mintAmounts",
2469
+ get: function get() {
2470
+ if (this._mintAmounts === null) {
2471
+ if (this.pool.tickCurrent < this.tickLower) {
2472
+ return {
2473
+ amount0: SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true),
2474
+ amount1: ZERO
2475
+ };
2476
+ } else if (this.pool.tickCurrent < this.tickUpper) {
2477
+ return {
2478
+ amount0: SqrtPriceMath.getAmount0Delta(this.pool.sqrtRatioX96, TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true),
2479
+ amount1: SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), this.pool.sqrtRatioX96, this.liquidity, true)
2480
+ };
2481
+ } else {
2482
+ return {
2483
+ amount0: ZERO,
2484
+ amount1: SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true)
2485
+ };
2486
+ }
2487
+ }
2488
+
2489
+ return this._mintAmounts;
2490
+ }
2491
+ }]);
2492
+
2493
+ return Position;
2494
+ }();
2495
+
2496
+ /**
2497
+ * Represents a list of pools through which a swap can occur
2498
+ * @template TInput The input token
2499
+ * @template TOutput The output token
2500
+ */
2501
+
2502
+ var Route = /*#__PURE__*/function () {
2503
+ /**
2504
+ * Creates an instance of route.
2505
+ * @param pools An array of `Pool` objects, ordered by the route the swap will take
2506
+ * @param input The input token
2507
+ * @param output The output token
2508
+ */
2509
+ function Route(pools, input, output) {
2510
+ this._midPrice = null;
2511
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
2512
+ var chainId = pools[0].chainId;
2513
+ var allOnSameChain = pools.every(function (pool) {
2514
+ return pool.chainId === chainId;
2515
+ });
2516
+ !allOnSameChain ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0;
2517
+ var wrappedInput = input.wrapped;
2518
+ !pools[0].involvesToken(wrappedInput) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
2519
+ !pools[pools.length - 1].involvesToken(output.wrapped) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
2520
+ /**
2521
+ * Normalizes token0-token1 order and selects the next token/fee step to add to the path
2522
+ * */
2523
+
2524
+ var tokenPath = [wrappedInput];
2525
+
2526
+ for (var _iterator = _createForOfIteratorHelperLoose(pools.entries()), _step; !(_step = _iterator()).done;) {
2527
+ var _step$value = _step.value,
2528
+ i = _step$value[0],
2529
+ pool = _step$value[1];
2530
+ var currentInputToken = tokenPath[i];
2531
+ !(currentInputToken.equals(pool.token0) || currentInputToken.equals(pool.token1)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PATH') : invariant(false) : void 0;
2532
+ var nextToken = currentInputToken.equals(pool.token0) ? pool.token1 : pool.token0;
2533
+ tokenPath.push(nextToken);
2534
+ }
2535
+
2536
+ this.pools = pools;
2537
+ this.tokenPath = tokenPath;
2538
+ this.input = input;
2539
+ this.output = output != null ? output : tokenPath[tokenPath.length - 1];
2540
+ }
2541
+
2542
+ _createClass(Route, [{
2543
+ key: "chainId",
2544
+ get: function get() {
2545
+ return this.pools[0].chainId;
2546
+ }
2547
+ /**
2548
+ * Returns the mid price of the route
2549
+ */
2550
+
2551
+ }, {
2552
+ key: "midPrice",
2553
+ get: function get() {
2554
+ if (this._midPrice !== null) return this._midPrice;
2555
+ var price = this.pools.slice(1).reduce(function (_ref, pool) {
2556
+ var nextInput = _ref.nextInput,
2557
+ price = _ref.price;
2558
+ return nextInput.equals(pool.token0) ? {
2559
+ nextInput: pool.token1,
2560
+ price: price.multiply(pool.token0Price)
2561
+ } : {
2562
+ nextInput: pool.token0,
2563
+ price: price.multiply(pool.token1Price)
2564
+ };
2565
+ }, this.pools[0].token0.equals(this.input.wrapped) ? {
2566
+ nextInput: this.pools[0].token1,
2567
+ price: this.pools[0].token0Price
2568
+ } : {
2569
+ nextInput: this.pools[0].token0,
2570
+ price: this.pools[0].token1Price
2571
+ }).price;
2572
+ return this._midPrice = new Price(this.input, this.output, price.denominator, price.numerator);
2573
+ }
2574
+ }]);
2575
+
2576
+ return Route;
2577
+ }();
2578
+
2579
+ /**
2580
+ * Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them
2581
+ * @template TInput The input token, either Ether or an ERC-20
2582
+ * @template TOutput The output token, either Ether or an ERC-20
2583
+ * @template TTradeType The trade type, either exact input or exact output
2584
+ * @param a The first trade to compare
2585
+ * @param b The second trade to compare
2586
+ * @returns A sorted ordering for two neighboring elements in a trade array
2587
+ */
2588
+
2589
+ function tradeComparator(a, b) {
2590
+ // must have same input and output token for comparison
2591
+ !a.inputAmount.currency.equals(b.inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY') : invariant(false) : void 0;
2592
+ !a.outputAmount.currency.equals(b.outputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY') : invariant(false) : void 0;
2593
+
2594
+ if (a.outputAmount.equalTo(b.outputAmount)) {
2595
+ if (a.inputAmount.equalTo(b.inputAmount)) {
2596
+ // consider the number of hops since each hop costs gas
2597
+ var aHops = a.swaps.reduce(function (total, cur) {
2598
+ return total + cur.route.tokenPath.length;
2599
+ }, 0);
2600
+ var bHops = b.swaps.reduce(function (total, cur) {
2601
+ return total + cur.route.tokenPath.length;
2602
+ }, 0);
2603
+ return aHops - bHops;
2604
+ } // trade A requires less input than trade B, so A should come first
2605
+
2606
+
2607
+ if (a.inputAmount.lessThan(b.inputAmount)) {
2608
+ return -1;
2609
+ } else {
2610
+ return 1;
2611
+ }
2612
+ } else {
2613
+ // tradeA has less output than trade B, so should come second
2614
+ if (a.outputAmount.lessThan(b.outputAmount)) {
2615
+ return 1;
2616
+ } else {
2617
+ return -1;
2618
+ }
2619
+ }
2620
+ }
2621
+ /**
2622
+ * Represents a trade executed against a set of routes where some percentage of the input is
2623
+ * split across each route.
2624
+ *
2625
+ * Each route has its own set of pools. Pools can not be re-used across routes.
2626
+ *
2627
+ * Does not account for slippage, i.e., changes in price environment that can occur between
2628
+ * the time the trade is submitted and when it is executed.
2629
+ * @template TInput The input token, either Ether or an ERC-20
2630
+ * @template TOutput The output token, either Ether or an ERC-20
2631
+ * @template TTradeType The trade type, either exact input or exact output
2632
+ */
2633
+
2634
+ var Trade = /*#__PURE__*/function () {
2635
+ /**
2636
+ * Construct a trade by passing in the pre-computed property values
2637
+ * @param routes The routes through which the trade occurs
2638
+ * @param tradeType The type of trade, exact input or exact output
2639
+ */
2640
+ function Trade(_ref) {
2641
+ var routes = _ref.routes,
2642
+ tradeType = _ref.tradeType;
2643
+ var inputCurrency = routes[0].inputAmount.currency;
2644
+ var outputCurrency = routes[0].outputAmount.currency;
2645
+ !routes.every(function (_ref2) {
2646
+ var route = _ref2.route;
2647
+ return inputCurrency.wrapped.equals(route.input.wrapped);
2648
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY_MATCH') : invariant(false) : void 0;
2649
+ !routes.every(function (_ref3) {
2650
+ var route = _ref3.route;
2651
+ return outputCurrency.wrapped.equals(route.output.wrapped);
2652
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY_MATCH') : invariant(false) : void 0;
2653
+ var numPools = routes.map(function (_ref4) {
2654
+ var route = _ref4.route;
2655
+ return route.pools.length;
2656
+ }).reduce(function (total, cur) {
2657
+ return total + cur;
2658
+ }, 0);
2659
+ var poolAddressSet = new Set();
2660
+
2661
+ for (var _iterator = _createForOfIteratorHelperLoose(routes), _step; !(_step = _iterator()).done;) {
2662
+ var route = _step.value.route;
2663
+
2664
+ for (var _iterator2 = _createForOfIteratorHelperLoose(route.pools), _step2; !(_step2 = _iterator2()).done;) {
2665
+ var pool = _step2.value;
2666
+ poolAddressSet.add(Pool.getAddress(pool.token0, pool.token1, pool.fee));
2667
+ }
2668
+ }
2669
+
2670
+ !(numPools == poolAddressSet.size) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS_DUPLICATED') : invariant(false) : void 0;
2671
+ this.swaps = routes;
2672
+ this.tradeType = tradeType;
2673
+ }
2674
+ /**
2675
+ * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
2676
+ * this will return an error.
2677
+ *
2678
+ * When the trade consists of just a single route, this returns the route of the trade,
2679
+ * i.e. which pools the trade goes through.
2680
+ */
2681
+
2682
+
2683
+ /**
2684
+ * Constructs an exact in trade with the given amount in and route
2685
+ * @template TInput The input token, either Ether or an ERC-20
2686
+ * @template TOutput The output token, either Ether or an ERC-20
2687
+ * @param route The route of the exact in trade
2688
+ * @param amountIn The amount being passed in
2689
+ * @returns The exact in trade
2690
+ */
2691
+ Trade.exactIn =
2692
+ /*#__PURE__*/
2693
+ function () {
2694
+ var _exactIn = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(route, amountIn) {
2695
+ return runtime_1.wrap(function _callee$(_context) {
2696
+ while (1) {
2697
+ switch (_context.prev = _context.next) {
2698
+ case 0:
2699
+ return _context.abrupt("return", Trade.fromRoute(route, amountIn, TradeType.EXACT_INPUT));
2700
+
2701
+ case 1:
2702
+ case "end":
2703
+ return _context.stop();
2704
+ }
2705
+ }
2706
+ }, _callee);
2707
+ }));
2708
+
2709
+ function exactIn(_x, _x2) {
2710
+ return _exactIn.apply(this, arguments);
2711
+ }
2712
+
2713
+ return exactIn;
2714
+ }()
2715
+ /**
2716
+ * Constructs an exact out trade with the given amount out and route
2717
+ * @template TInput The input token, either Ether or an ERC-20
2718
+ * @template TOutput The output token, either Ether or an ERC-20
2719
+ * @param route The route of the exact out trade
2720
+ * @param amountOut The amount returned by the trade
2721
+ * @returns The exact out trade
2722
+ */
2723
+ ;
2724
+
2725
+ Trade.exactOut =
2726
+ /*#__PURE__*/
2727
+ function () {
2728
+ var _exactOut = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(route, amountOut) {
2729
+ return runtime_1.wrap(function _callee2$(_context2) {
2730
+ while (1) {
2731
+ switch (_context2.prev = _context2.next) {
2732
+ case 0:
2733
+ return _context2.abrupt("return", Trade.fromRoute(route, amountOut, TradeType.EXACT_OUTPUT));
2734
+
2735
+ case 1:
2736
+ case "end":
2737
+ return _context2.stop();
2738
+ }
2739
+ }
2740
+ }, _callee2);
2741
+ }));
2742
+
2743
+ function exactOut(_x3, _x4) {
2744
+ return _exactOut.apply(this, arguments);
2745
+ }
2746
+
2747
+ return exactOut;
2748
+ }()
2749
+ /**
2750
+ * Constructs a trade by simulating swaps through the given route
2751
+ * @template TInput The input token, either Ether or an ERC-20.
2752
+ * @template TOutput The output token, either Ether or an ERC-20.
2753
+ * @template TTradeType The type of the trade, either exact in or exact out.
2754
+ * @param route route to swap through
2755
+ * @param amount the amount specified, either input or output, depending on tradeType
2756
+ * @param tradeType whether the trade is an exact input or exact output swap
2757
+ * @returns The route
2758
+ */
2759
+ ;
2760
+
2761
+ Trade.fromRoute =
2762
+ /*#__PURE__*/
2763
+ function () {
2764
+ var _fromRoute = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3(route, amount, tradeType) {
2765
+ var amounts, inputAmount, outputAmount, i, pool, _yield$pool$getOutput, _outputAmount, _i, _pool, _yield$_pool$getInput, _inputAmount;
2766
+
2767
+ return runtime_1.wrap(function _callee3$(_context3) {
2768
+ while (1) {
2769
+ switch (_context3.prev = _context3.next) {
2770
+ case 0:
2771
+ amounts = new Array(route.tokenPath.length);
2772
+
2773
+ if (!(tradeType === TradeType.EXACT_INPUT)) {
2774
+ _context3.next = 19;
2775
+ break;
2776
+ }
2777
+
2778
+ !amount.currency.equals(route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
2779
+ amounts[0] = amount.wrapped;
2780
+ i = 0;
2781
+
2782
+ case 5:
2783
+ if (!(i < route.tokenPath.length - 1)) {
2784
+ _context3.next = 15;
2785
+ break;
2786
+ }
2787
+
2788
+ pool = route.pools[i];
2789
+ _context3.next = 9;
2790
+ return pool.getOutputAmount(amounts[i]);
2791
+
2792
+ case 9:
2793
+ _yield$pool$getOutput = _context3.sent;
2794
+ _outputAmount = _yield$pool$getOutput[0];
2795
+ amounts[i + 1] = _outputAmount;
2796
+
2797
+ case 12:
2798
+ i++;
2799
+ _context3.next = 5;
2800
+ break;
2801
+
2802
+ case 15:
2803
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
2804
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amounts[amounts.length - 1].numerator, amounts[amounts.length - 1].denominator);
2805
+ _context3.next = 34;
2806
+ break;
2807
+
2808
+ case 19:
2809
+ !amount.currency.equals(route.output) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
2810
+ amounts[amounts.length - 1] = amount.wrapped;
2811
+ _i = route.tokenPath.length - 1;
2812
+
2813
+ case 22:
2814
+ if (!(_i > 0)) {
2815
+ _context3.next = 32;
2816
+ break;
2817
+ }
2818
+
2819
+ _pool = route.pools[_i - 1];
2820
+ _context3.next = 26;
2821
+ return _pool.getInputAmount(amounts[_i]);
2822
+
2823
+ case 26:
2824
+ _yield$_pool$getInput = _context3.sent;
2825
+ _inputAmount = _yield$_pool$getInput[0];
2826
+ amounts[_i - 1] = _inputAmount;
2827
+
2828
+ case 29:
2829
+ _i--;
2830
+ _context3.next = 22;
2831
+ break;
2832
+
2833
+ case 32:
2834
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
2835
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
2836
+
2837
+ case 34:
2838
+ return _context3.abrupt("return", new Trade({
2839
+ routes: [{
2840
+ inputAmount: inputAmount,
2841
+ outputAmount: outputAmount,
2842
+ route: route
2843
+ }],
2844
+ tradeType: tradeType
2845
+ }));
2846
+
2847
+ case 35:
2848
+ case "end":
2849
+ return _context3.stop();
2850
+ }
2851
+ }
2852
+ }, _callee3);
2853
+ }));
2854
+
2855
+ function fromRoute(_x5, _x6, _x7) {
2856
+ return _fromRoute.apply(this, arguments);
2857
+ }
2858
+
2859
+ return fromRoute;
2860
+ }()
2861
+ /**
2862
+ * Constructs a trade from routes by simulating swaps
2863
+ *
2864
+ * @template TInput The input token, either Ether or an ERC-20.
2865
+ * @template TOutput The output token, either Ether or an ERC-20.
2866
+ * @template TTradeType The type of the trade, either exact in or exact out.
2867
+ * @param routes the routes to swap through and how much of the amount should be routed through each
2868
+ * @param tradeType whether the trade is an exact input or exact output swap
2869
+ * @returns The trade
2870
+ */
2871
+ ;
2872
+
2873
+ Trade.fromRoutes =
2874
+ /*#__PURE__*/
2875
+ function () {
2876
+ var _fromRoutes = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee4(routes, tradeType) {
2877
+ var populatedRoutes, _iterator3, _step3, _step3$value, route, amount, amounts, inputAmount, outputAmount, i, pool, _yield$pool$getOutput2, _outputAmount2, _i2, _pool2, _yield$_pool2$getInpu, _inputAmount2;
2878
+
2879
+ return runtime_1.wrap(function _callee4$(_context4) {
2880
+ while (1) {
2881
+ switch (_context4.prev = _context4.next) {
2882
+ case 0:
2883
+ populatedRoutes = [];
2884
+ _iterator3 = _createForOfIteratorHelperLoose(routes);
2885
+
2886
+ case 2:
2887
+ if ((_step3 = _iterator3()).done) {
2888
+ _context4.next = 43;
2889
+ break;
2890
+ }
2891
+
2892
+ _step3$value = _step3.value, route = _step3$value.route, amount = _step3$value.amount;
2893
+ amounts = new Array(route.tokenPath.length);
2894
+ inputAmount = void 0;
2895
+ outputAmount = void 0;
2896
+
2897
+ if (!(tradeType === TradeType.EXACT_INPUT)) {
2898
+ _context4.next = 25;
2899
+ break;
2900
+ }
2901
+
2902
+ !amount.currency.equals(route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
2903
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
2904
+ amounts[0] = CurrencyAmount.fromFractionalAmount(route.input.wrapped, amount.numerator, amount.denominator);
2905
+ i = 0;
2906
+
2907
+ case 12:
2908
+ if (!(i < route.tokenPath.length - 1)) {
2909
+ _context4.next = 22;
2910
+ break;
2911
+ }
2912
+
2913
+ pool = route.pools[i];
2914
+ _context4.next = 16;
2915
+ return pool.getOutputAmount(amounts[i]);
2916
+
2917
+ case 16:
2918
+ _yield$pool$getOutput2 = _context4.sent;
2919
+ _outputAmount2 = _yield$pool$getOutput2[0];
2920
+ amounts[i + 1] = _outputAmount2;
2921
+
2922
+ case 19:
2923
+ i++;
2924
+ _context4.next = 12;
2925
+ break;
2926
+
2927
+ case 22:
2928
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amounts[amounts.length - 1].numerator, amounts[amounts.length - 1].denominator);
2929
+ _context4.next = 40;
2930
+ break;
2931
+
2932
+ case 25:
2933
+ !amount.currency.equals(route.output) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
2934
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
2935
+ amounts[amounts.length - 1] = CurrencyAmount.fromFractionalAmount(route.output.wrapped, amount.numerator, amount.denominator);
2936
+ _i2 = route.tokenPath.length - 1;
2937
+
2938
+ case 29:
2939
+ if (!(_i2 > 0)) {
2940
+ _context4.next = 39;
2941
+ break;
2942
+ }
2943
+
2944
+ _pool2 = route.pools[_i2 - 1];
2945
+ _context4.next = 33;
2946
+ return _pool2.getInputAmount(amounts[_i2]);
2947
+
2948
+ case 33:
2949
+ _yield$_pool2$getInpu = _context4.sent;
2950
+ _inputAmount2 = _yield$_pool2$getInpu[0];
2951
+ amounts[_i2 - 1] = _inputAmount2;
2952
+
2953
+ case 36:
2954
+ _i2--;
2955
+ _context4.next = 29;
2956
+ break;
2957
+
2958
+ case 39:
2959
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amounts[0].numerator, amounts[0].denominator);
2960
+
2961
+ case 40:
2962
+ populatedRoutes.push({
2963
+ route: route,
2964
+ inputAmount: inputAmount,
2965
+ outputAmount: outputAmount
2966
+ });
2967
+
2968
+ case 41:
2969
+ _context4.next = 2;
2970
+ break;
2971
+
2972
+ case 43:
2973
+ return _context4.abrupt("return", new Trade({
2974
+ routes: populatedRoutes,
2975
+ tradeType: tradeType
2976
+ }));
2977
+
2978
+ case 44:
2979
+ case "end":
2980
+ return _context4.stop();
2981
+ }
2982
+ }
2983
+ }, _callee4);
2984
+ }));
2985
+
2986
+ function fromRoutes(_x8, _x9) {
2987
+ return _fromRoutes.apply(this, arguments);
2988
+ }
2989
+
2990
+ return fromRoutes;
2991
+ }()
2992
+ /**
2993
+ * Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade
2994
+ * elsewhere and do not have any tick data
2995
+ * @template TInput The input token, either Ether or an ERC-20
2996
+ * @template TOutput The output token, either Ether or an ERC-20
2997
+ * @template TTradeType The type of the trade, either exact in or exact out
2998
+ * @param constructorArguments The arguments passed to the trade constructor
2999
+ * @returns The unchecked trade
3000
+ */
3001
+ ;
3002
+
3003
+ Trade.createUncheckedTrade = function createUncheckedTrade(constructorArguments) {
3004
+ return new Trade(_extends({}, constructorArguments, {
3005
+ routes: [{
3006
+ inputAmount: constructorArguments.inputAmount,
3007
+ outputAmount: constructorArguments.outputAmount,
3008
+ route: constructorArguments.route
3009
+ }]
3010
+ }));
3011
+ }
3012
+ /**
3013
+ * Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade
3014
+ * elsewhere and do not have any tick data
3015
+ * @template TInput The input token, either Ether or an ERC-20
3016
+ * @template TOutput The output token, either Ether or an ERC-20
3017
+ * @template TTradeType The type of the trade, either exact in or exact out
3018
+ * @param constructorArguments The arguments passed to the trade constructor
3019
+ * @returns The unchecked trade
3020
+ */
3021
+ ;
3022
+
3023
+ Trade.createUncheckedTradeWithMultipleRoutes = function createUncheckedTradeWithMultipleRoutes(constructorArguments) {
3024
+ return new Trade(constructorArguments);
3025
+ }
3026
+ /**
3027
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
3028
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
3029
+ * @returns The amount out
3030
+ */
3031
+ ;
3032
+
3033
+ var _proto = Trade.prototype;
3034
+
3035
+ _proto.minimumAmountOut = function minimumAmountOut(slippageTolerance, amountOut) {
3036
+ if (amountOut === void 0) {
3037
+ amountOut = this.outputAmount;
3038
+ }
3039
+
3040
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
3041
+
3042
+ if (this.tradeType === TradeType.EXACT_OUTPUT) {
3043
+ return amountOut;
3044
+ } else {
3045
+ var slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
3046
+ return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
3047
+ }
3048
+ }
3049
+ /**
3050
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
3051
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
3052
+ * @returns The amount in
3053
+ */
3054
+ ;
3055
+
3056
+ _proto.maximumAmountIn = function maximumAmountIn(slippageTolerance, amountIn) {
3057
+ if (amountIn === void 0) {
3058
+ amountIn = this.inputAmount;
3059
+ }
3060
+
3061
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
3062
+
3063
+ if (this.tradeType === TradeType.EXACT_INPUT) {
3064
+ return amountIn;
3065
+ } else {
3066
+ var slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
3067
+ return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
3068
+ }
3069
+ }
3070
+ /**
3071
+ * Return the execution price after accounting for slippage tolerance
3072
+ * @param slippageTolerance the allowed tolerated slippage
3073
+ * @returns The execution price
3074
+ */
3075
+ ;
3076
+
3077
+ _proto.worstExecutionPrice = function worstExecutionPrice(slippageTolerance) {
3078
+ return new Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
3079
+ }
3080
+ /**
3081
+ * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
3082
+ * amount to an output token, making at most `maxHops` hops.
3083
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
3084
+ * the amount in among multiple routes.
3085
+ * @param pools the pools to consider in finding the best trade
3086
+ * @param nextAmountIn exact amount of input currency to spend
3087
+ * @param currencyOut the desired currency out
3088
+ * @param maxNumResults maximum number of results to return
3089
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
3090
+ * @param currentPools used in recursion; the current list of pools
3091
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
3092
+ * @param bestTrades used in recursion; the current list of best trades
3093
+ * @returns The exact in trade
3094
+ */
3095
+ ;
3096
+
3097
+ Trade.bestTradeExactIn =
3098
+ /*#__PURE__*/
3099
+ function () {
3100
+ var _bestTradeExactIn = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee5(pools, currencyAmountIn, currencyOut, _temp, // used in recursion.
3101
+ currentPools, nextAmountIn, bestTrades) {
3102
+ var _ref5, _ref5$maxNumResults, maxNumResults, _ref5$maxHops, maxHops, amountIn, tokenOut, i, pool, amountOut, _yield$pool$getOutput3, poolsExcludingThisPool;
3103
+
3104
+ return runtime_1.wrap(function _callee5$(_context5) {
3105
+ while (1) {
3106
+ switch (_context5.prev = _context5.next) {
3107
+ case 0:
3108
+ _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;
3109
+
3110
+ if (currentPools === void 0) {
3111
+ currentPools = [];
3112
+ }
3113
+
3114
+ if (nextAmountIn === void 0) {
3115
+ nextAmountIn = currencyAmountIn;
3116
+ }
3117
+
3118
+ if (bestTrades === void 0) {
3119
+ bestTrades = [];
3120
+ }
3121
+
3122
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
3123
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
3124
+ !(currencyAmountIn === nextAmountIn || currentPools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
3125
+ amountIn = nextAmountIn.wrapped;
3126
+ tokenOut = currencyOut.wrapped;
3127
+ i = 0;
3128
+
3129
+ case 10:
3130
+ if (!(i < pools.length)) {
3131
+ _context5.next = 46;
3132
+ break;
3133
+ }
3134
+
3135
+ pool = pools[i]; // pool irrelevant
3136
+
3137
+ if (!(!pool.token0.equals(amountIn.currency) && !pool.token1.equals(amountIn.currency))) {
3138
+ _context5.next = 14;
3139
+ break;
3140
+ }
3141
+
3142
+ return _context5.abrupt("continue", 43);
3143
+
3144
+ case 14:
3145
+ amountOut = void 0;
3146
+ _context5.prev = 15;
3147
+ _context5.next = 19;
3148
+ return pool.getOutputAmount(amountIn);
3149
+
3150
+ case 19:
3151
+ _yield$pool$getOutput3 = _context5.sent;
3152
+ amountOut = _yield$pool$getOutput3[0];
3153
+ _context5.next = 28;
3154
+ break;
3155
+
3156
+ case 23:
3157
+ _context5.prev = 23;
3158
+ _context5.t0 = _context5["catch"](15);
3159
+
3160
+ if (!_context5.t0.isInsufficientInputAmountError) {
3161
+ _context5.next = 27;
3162
+ break;
3163
+ }
3164
+
3165
+ return _context5.abrupt("continue", 43);
3166
+
3167
+ case 27:
3168
+ throw _context5.t0;
3169
+
3170
+ case 28:
3171
+ if (!(amountOut.currency.isToken && amountOut.currency.equals(tokenOut))) {
3172
+ _context5.next = 39;
3173
+ break;
3174
+ }
3175
+
3176
+ _context5.t1 = sortedInsert;
3177
+ _context5.t2 = bestTrades;
3178
+ _context5.next = 33;
3179
+ return Trade.fromRoute(new Route([].concat(currentPools, [pool]), currencyAmountIn.currency, currencyOut), currencyAmountIn, TradeType.EXACT_INPUT);
3180
+
3181
+ case 33:
3182
+ _context5.t3 = _context5.sent;
3183
+ _context5.t4 = maxNumResults;
3184
+ _context5.t5 = tradeComparator;
3185
+ (0, _context5.t1)(_context5.t2, _context5.t3, _context5.t4, _context5.t5);
3186
+ _context5.next = 43;
3187
+ break;
3188
+
3189
+ case 39:
3190
+ if (!(maxHops > 1 && pools.length > 1)) {
3191
+ _context5.next = 43;
3192
+ break;
3193
+ }
3194
+
3195
+ 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
3196
+
3197
+ _context5.next = 43;
3198
+ return Trade.bestTradeExactIn(poolsExcludingThisPool, currencyAmountIn, currencyOut, {
3199
+ maxNumResults: maxNumResults,
3200
+ maxHops: maxHops - 1
3201
+ }, [].concat(currentPools, [pool]), amountOut, bestTrades);
3202
+
3203
+ case 43:
3204
+ i++;
3205
+ _context5.next = 10;
3206
+ break;
3207
+
3208
+ case 46:
3209
+ return _context5.abrupt("return", bestTrades);
3210
+
3211
+ case 47:
3212
+ case "end":
3213
+ return _context5.stop();
3214
+ }
3215
+ }
3216
+ }, _callee5, null, [[15, 23]]);
3217
+ }));
3218
+
3219
+ function bestTradeExactIn(_x10, _x11, _x12, _x13, _x14, _x15, _x16) {
3220
+ return _bestTradeExactIn.apply(this, arguments);
3221
+ }
3222
+
3223
+ return bestTradeExactIn;
3224
+ }()
3225
+ /**
3226
+ * similar to the above method but instead targets a fixed output amount
3227
+ * given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
3228
+ * to an output token amount, making at most `maxHops` hops
3229
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
3230
+ * the amount in among multiple routes.
3231
+ * @param pools the pools to consider in finding the best trade
3232
+ * @param currencyIn the currency to spend
3233
+ * @param currencyAmountOut the desired currency amount out
3234
+ * @param nextAmountOut the exact amount of currency out
3235
+ * @param maxNumResults maximum number of results to return
3236
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
3237
+ * @param currentPools used in recursion; the current list of pools
3238
+ * @param bestTrades used in recursion; the current list of best trades
3239
+ * @returns The exact out trade
3240
+ */
3241
+ ;
3242
+
3243
+ Trade.bestTradeExactOut =
3244
+ /*#__PURE__*/
3245
+ function () {
3246
+ var _bestTradeExactOut = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee6(pools, currencyIn, currencyAmountOut, _temp2, // used in recursion.
3247
+ currentPools, nextAmountOut, bestTrades) {
3248
+ var _ref6, _ref6$maxNumResults, maxNumResults, _ref6$maxHops, maxHops, amountOut, tokenIn, i, pool, amountIn, _yield$pool$getInputA, poolsExcludingThisPool;
3249
+
3250
+ return runtime_1.wrap(function _callee6$(_context6) {
3251
+ while (1) {
3252
+ switch (_context6.prev = _context6.next) {
3253
+ case 0:
3254
+ _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;
3255
+
3256
+ if (currentPools === void 0) {
3257
+ currentPools = [];
3258
+ }
3259
+
3260
+ if (nextAmountOut === void 0) {
3261
+ nextAmountOut = currencyAmountOut;
3262
+ }
3263
+
3264
+ if (bestTrades === void 0) {
3265
+ bestTrades = [];
3266
+ }
3267
+
3268
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
3269
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
3270
+ !(currencyAmountOut === nextAmountOut || currentPools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
3271
+ amountOut = nextAmountOut.wrapped;
3272
+ tokenIn = currencyIn.wrapped;
3273
+ i = 0;
3274
+
3275
+ case 10:
3276
+ if (!(i < pools.length)) {
3277
+ _context6.next = 46;
3278
+ break;
3279
+ }
3280
+
3281
+ pool = pools[i]; // pool irrelevant
3282
+
3283
+ if (!(!pool.token0.equals(amountOut.currency) && !pool.token1.equals(amountOut.currency))) {
3284
+ _context6.next = 14;
3285
+ break;
3286
+ }
3287
+
3288
+ return _context6.abrupt("continue", 43);
3289
+
3290
+ case 14:
3291
+ amountIn = void 0;
3292
+ _context6.prev = 15;
3293
+ _context6.next = 19;
3294
+ return pool.getInputAmount(amountOut);
3295
+
3296
+ case 19:
3297
+ _yield$pool$getInputA = _context6.sent;
3298
+ amountIn = _yield$pool$getInputA[0];
3299
+ _context6.next = 28;
3300
+ break;
3301
+
3302
+ case 23:
3303
+ _context6.prev = 23;
3304
+ _context6.t0 = _context6["catch"](15);
3305
+
3306
+ if (!_context6.t0.isInsufficientReservesError) {
3307
+ _context6.next = 27;
3308
+ break;
3309
+ }
3310
+
3311
+ return _context6.abrupt("continue", 43);
3312
+
3313
+ case 27:
3314
+ throw _context6.t0;
3315
+
3316
+ case 28:
3317
+ if (!amountIn.currency.equals(tokenIn)) {
3318
+ _context6.next = 39;
3319
+ break;
3320
+ }
3321
+
3322
+ _context6.t1 = sortedInsert;
3323
+ _context6.t2 = bestTrades;
3324
+ _context6.next = 33;
3325
+ return Trade.fromRoute(new Route([pool].concat(currentPools), currencyIn, currencyAmountOut.currency), currencyAmountOut, TradeType.EXACT_OUTPUT);
3326
+
3327
+ case 33:
3328
+ _context6.t3 = _context6.sent;
3329
+ _context6.t4 = maxNumResults;
3330
+ _context6.t5 = tradeComparator;
3331
+ (0, _context6.t1)(_context6.t2, _context6.t3, _context6.t4, _context6.t5);
3332
+ _context6.next = 43;
3333
+ break;
3334
+
3335
+ case 39:
3336
+ if (!(maxHops > 1 && pools.length > 1)) {
3337
+ _context6.next = 43;
3338
+ break;
3339
+ }
3340
+
3341
+ 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
3342
+
3343
+ _context6.next = 43;
3344
+ return Trade.bestTradeExactOut(poolsExcludingThisPool, currencyIn, currencyAmountOut, {
3345
+ maxNumResults: maxNumResults,
3346
+ maxHops: maxHops - 1
3347
+ }, [pool].concat(currentPools), amountIn, bestTrades);
3348
+
3349
+ case 43:
3350
+ i++;
3351
+ _context6.next = 10;
3352
+ break;
3353
+
3354
+ case 46:
3355
+ return _context6.abrupt("return", bestTrades);
3356
+
3357
+ case 47:
3358
+ case "end":
3359
+ return _context6.stop();
3360
+ }
3361
+ }
3362
+ }, _callee6, null, [[15, 23]]);
3363
+ }));
3364
+
3365
+ function bestTradeExactOut(_x17, _x18, _x19, _x20, _x21, _x22, _x23) {
3366
+ return _bestTradeExactOut.apply(this, arguments);
3367
+ }
3368
+
3369
+ return bestTradeExactOut;
3370
+ }();
3371
+
3372
+ _createClass(Trade, [{
3373
+ key: "route",
3374
+ get: function get() {
3375
+ !(this.swaps.length == 1) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MULTIPLE_ROUTES') : invariant(false) : void 0;
3376
+ return this.swaps[0].route;
3377
+ }
3378
+ /**
3379
+ * The input amount for the trade assuming no slippage.
3380
+ */
3381
+
3382
+ }, {
3383
+ key: "inputAmount",
3384
+ get: function get() {
3385
+ if (this._inputAmount) {
3386
+ return this._inputAmount;
3387
+ }
3388
+
3389
+ var inputCurrency = this.swaps[0].inputAmount.currency;
3390
+ var totalInputFromRoutes = this.swaps.map(function (_ref7) {
3391
+ var inputAmount = _ref7.inputAmount;
3392
+ return inputAmount;
3393
+ }).reduce(function (total, cur) {
3394
+ return total.add(cur);
3395
+ }, CurrencyAmount.fromRawAmount(inputCurrency, 0));
3396
+ this._inputAmount = totalInputFromRoutes;
3397
+ return this._inputAmount;
3398
+ }
3399
+ /**
3400
+ * The output amount for the trade assuming no slippage.
3401
+ */
3402
+
3403
+ }, {
3404
+ key: "outputAmount",
3405
+ get: function get() {
3406
+ if (this._outputAmount) {
3407
+ return this._outputAmount;
3408
+ }
3409
+
3410
+ var outputCurrency = this.swaps[0].outputAmount.currency;
3411
+ var totalOutputFromRoutes = this.swaps.map(function (_ref8) {
3412
+ var outputAmount = _ref8.outputAmount;
3413
+ return outputAmount;
3414
+ }).reduce(function (total, cur) {
3415
+ return total.add(cur);
3416
+ }, CurrencyAmount.fromRawAmount(outputCurrency, 0));
3417
+ this._outputAmount = totalOutputFromRoutes;
3418
+ return this._outputAmount;
3419
+ }
3420
+ /**
3421
+ * The price expressed in terms of output amount/input amount.
3422
+ */
3423
+
3424
+ }, {
3425
+ key: "executionPrice",
3426
+ get: function get() {
3427
+ var _this$_executionPrice;
3428
+
3429
+ return (_this$_executionPrice = this._executionPrice) != null ? _this$_executionPrice : this._executionPrice = new Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
3430
+ }
3431
+ /**
3432
+ * Returns the percent difference between the route's mid price and the price impact
3433
+ */
3434
+
3435
+ }, {
3436
+ key: "priceImpact",
3437
+ get: function get() {
3438
+ if (this._priceImpact) {
3439
+ return this._priceImpact;
3440
+ }
3441
+
3442
+ var spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0);
3443
+
3444
+ for (var _iterator4 = _createForOfIteratorHelperLoose(this.swaps), _step4; !(_step4 = _iterator4()).done;) {
3445
+ var _step4$value = _step4.value,
3446
+ route = _step4$value.route,
3447
+ inputAmount = _step4$value.inputAmount;
3448
+ var midPrice = route.midPrice;
3449
+ spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount));
3450
+ }
3451
+
3452
+ var priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount);
3453
+ this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator);
3454
+ return this._priceImpact;
3455
+ }
3456
+ }]);
3457
+
3458
+ return Trade;
3459
+ }();
3460
+
3461
+ var Multicall = /*#__PURE__*/function () {
3462
+ /**
3463
+ * Cannot be constructed.
3464
+ */
3465
+ function Multicall() {}
3466
+
3467
+ Multicall.encodeMulticall = function encodeMulticall(calldatas) {
3468
+ if (!Array.isArray(calldatas)) {
3469
+ calldatas = [calldatas];
3470
+ }
3471
+
3472
+ return calldatas.length === 1 ? calldatas[0] : Multicall.INTERFACE.encodeFunctionData('multicall', [calldatas]);
3473
+ };
3474
+
3475
+ return Multicall;
3476
+ }();
3477
+ Multicall.INTERFACE = /*#__PURE__*/new Interface(IMulticall.abi);
3478
+
3479
+ function isAllowedPermit(permitOptions) {
3480
+ return 'nonce' in permitOptions;
3481
+ }
3482
+
3483
+ var SelfPermit = /*#__PURE__*/function () {
3484
+ /**
3485
+ * Cannot be constructed.
3486
+ */
3487
+ function SelfPermit() {}
3488
+
3489
+ SelfPermit.encodePermit = function encodePermit(token, options) {
3490
+ 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]);
3491
+ };
3492
+
3493
+ return SelfPermit;
3494
+ }();
3495
+ SelfPermit.INTERFACE = /*#__PURE__*/new Interface(ISelfPermit.abi);
3496
+
3497
+ var Payments = /*#__PURE__*/function () {
3498
+ /**
3499
+ * Cannot be constructed.
3500
+ */
3501
+ function Payments() {}
3502
+
3503
+ Payments.encodeFeeBips = function encodeFeeBips(fee) {
3504
+ return toHex(fee.multiply(10000).quotient);
3505
+ };
3506
+
3507
+ Payments.encodeUnwrapWETH9 = function encodeUnwrapWETH9(amountMinimum, recipient, feeOptions) {
3508
+ recipient = validateAndParseAddress(recipient);
3509
+
3510
+ if (!!feeOptions) {
3511
+ var feeBips = this.encodeFeeBips(feeOptions.fee);
3512
+ var feeRecipient = validateAndParseAddress(feeOptions.recipient);
3513
+ return Payments.INTERFACE.encodeFunctionData('unwrapWETH9WithFee', [toHex(amountMinimum), recipient, feeBips, feeRecipient]);
3514
+ } else {
3515
+ return Payments.INTERFACE.encodeFunctionData('unwrapWETH9', [toHex(amountMinimum), recipient]);
3516
+ }
3517
+ };
3518
+
3519
+ Payments.encodeSweepToken = function encodeSweepToken(token, amountMinimum, recipient, feeOptions) {
3520
+ recipient = validateAndParseAddress(recipient);
3521
+
3522
+ if (!!feeOptions) {
3523
+ var feeBips = this.encodeFeeBips(feeOptions.fee);
3524
+ var feeRecipient = validateAndParseAddress(feeOptions.recipient);
3525
+ return Payments.INTERFACE.encodeFunctionData('sweepTokenWithFee', [token.address, toHex(amountMinimum), recipient, feeBips, feeRecipient]);
3526
+ } else {
3527
+ return Payments.INTERFACE.encodeFunctionData('sweepToken', [token.address, toHex(amountMinimum), recipient]);
3528
+ }
3529
+ };
3530
+
3531
+ Payments.encodeRefundETH = function encodeRefundETH() {
3532
+ return Payments.INTERFACE.encodeFunctionData('refundETH');
3533
+ };
3534
+
3535
+ return Payments;
3536
+ }();
3537
+ Payments.INTERFACE = /*#__PURE__*/new Interface(IPeripheryPaymentsWithFee.abi);
3538
+
3539
+ var MaxUint128 = /*#__PURE__*/toHex( /*#__PURE__*/JSBI.subtract( /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(128)), /*#__PURE__*/JSBI.BigInt(1))); // type guard
3540
+
3541
+ function isMint(options) {
3542
+ return Object.keys(options).some(function (k) {
3543
+ return k === 'recipient';
3544
+ });
3545
+ }
3546
+
3547
+ var NonfungiblePositionManager = /*#__PURE__*/function () {
3548
+ /**
3549
+ * Cannot be constructed.
3550
+ */
3551
+ function NonfungiblePositionManager() {}
3552
+
3553
+ NonfungiblePositionManager.encodeCreate = function encodeCreate(pool) {
3554
+ return NonfungiblePositionManager.INTERFACE.encodeFunctionData('createAndInitializePoolIfNecessary', [pool.token0.address, pool.token1.address, pool.fee, toHex(pool.sqrtRatioX96)]);
3555
+ };
3556
+
3557
+ NonfungiblePositionManager.createCallParameters = function createCallParameters(pool) {
3558
+ return {
3559
+ calldata: this.encodeCreate(pool),
3560
+ value: toHex(0)
3561
+ };
3562
+ };
3563
+
3564
+ NonfungiblePositionManager.addCallParameters = function addCallParameters(position, options) {
3565
+ !JSBI.greaterThan(position.liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO_LIQUIDITY') : invariant(false) : void 0;
3566
+ var calldatas = []; // get amounts
3567
+
3568
+ var _position$mintAmounts = position.mintAmounts,
3569
+ amount0Desired = _position$mintAmounts.amount0,
3570
+ amount1Desired = _position$mintAmounts.amount1; // adjust for slippage
3571
+
3572
+ var minimumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
3573
+ var amount0Min = toHex(minimumAmounts.amount0);
3574
+ var amount1Min = toHex(minimumAmounts.amount1);
3575
+ var deadline = toHex(options.deadline); // create pool if needed
3576
+
3577
+ if (isMint(options) && options.createPool) {
3578
+ calldatas.push(this.encodeCreate(position.pool));
3579
+ } // permits if necessary
3580
+
3581
+
3582
+ if (options.token0Permit) {
3583
+ calldatas.push(SelfPermit.encodePermit(position.pool.token0, options.token0Permit));
3584
+ }
3585
+
3586
+ if (options.token1Permit) {
3587
+ calldatas.push(SelfPermit.encodePermit(position.pool.token1, options.token1Permit));
3588
+ } // mint
3589
+
3590
+
3591
+ if (isMint(options)) {
3592
+ var recipient = validateAndParseAddress(options.recipient);
3593
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('mint', [{
3594
+ token0: position.pool.token0.address,
3595
+ token1: position.pool.token1.address,
3596
+ fee: position.pool.fee,
3597
+ tickLower: position.tickLower,
3598
+ tickUpper: position.tickUpper,
3599
+ amount0Desired: toHex(amount0Desired),
3600
+ amount1Desired: toHex(amount1Desired),
3601
+ amount0Min: amount0Min,
3602
+ amount1Min: amount1Min,
3603
+ recipient: recipient,
3604
+ deadline: deadline
3605
+ }]));
3606
+ } else {
3607
+ // increase
3608
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('increaseLiquidity', [{
3609
+ tokenId: toHex(options.tokenId),
3610
+ amount0Desired: toHex(amount0Desired),
3611
+ amount1Desired: toHex(amount1Desired),
3612
+ amount0Min: amount0Min,
3613
+ amount1Min: amount1Min,
3614
+ deadline: deadline
3615
+ }]));
3616
+ }
3617
+
3618
+ var value = toHex(0);
3619
+
3620
+ if (options.useNative) {
3621
+ var wrapped = options.useNative.wrapped;
3622
+ !(position.pool.token0.equals(wrapped) || position.pool.token1.equals(wrapped)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NO_WETH') : invariant(false) : void 0;
3623
+ var wrappedValue = position.pool.token0.equals(wrapped) ? amount0Desired : amount1Desired; // we only need to refund if we're actually sending ETH
3624
+
3625
+ if (JSBI.greaterThan(wrappedValue, ZERO)) {
3626
+ calldatas.push(Payments.encodeRefundETH());
3627
+ }
3628
+
3629
+ value = toHex(wrappedValue);
3630
+ }
3631
+
3632
+ return {
3633
+ calldata: Multicall.encodeMulticall(calldatas),
3634
+ value: value
3635
+ };
3636
+ };
3637
+
3638
+ NonfungiblePositionManager.encodeCollect = function encodeCollect(options) {
3639
+ var calldatas = [];
3640
+ var tokenId = toHex(options.tokenId);
3641
+ var involvesETH = options.expectedCurrencyOwed0.currency.isNative || options.expectedCurrencyOwed1.currency.isNative;
3642
+ var recipient = validateAndParseAddress(options.recipient); // collect
3643
+
3644
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('collect', [{
3645
+ tokenId: tokenId,
3646
+ recipient: involvesETH ? ADDRESS_ZERO : recipient,
3647
+ amount0Max: MaxUint128,
3648
+ amount1Max: MaxUint128
3649
+ }]));
3650
+
3651
+ if (involvesETH) {
3652
+ var ethAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed0.quotient : options.expectedCurrencyOwed1.quotient;
3653
+ var token = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed1.currency : options.expectedCurrencyOwed0.currency;
3654
+ var tokenAmount = options.expectedCurrencyOwed0.currency.isNative ? options.expectedCurrencyOwed1.quotient : options.expectedCurrencyOwed0.quotient;
3655
+ calldatas.push(Payments.encodeUnwrapWETH9(ethAmount, recipient));
3656
+ calldatas.push(Payments.encodeSweepToken(token, tokenAmount, recipient));
3657
+ }
3658
+
3659
+ return calldatas;
3660
+ };
3661
+
3662
+ NonfungiblePositionManager.collectCallParameters = function collectCallParameters(options) {
3663
+ var calldatas = NonfungiblePositionManager.encodeCollect(options);
3664
+ return {
3665
+ calldata: Multicall.encodeMulticall(calldatas),
3666
+ value: toHex(0)
3667
+ };
3668
+ }
3669
+ /**
3670
+ * Produces the calldata for completely or partially exiting a position
3671
+ * @param position The position to exit
3672
+ * @param options Additional information necessary for generating the calldata
3673
+ * @returns The call parameters
3674
+ */
3675
+ ;
3676
+
3677
+ NonfungiblePositionManager.removeCallParameters = function removeCallParameters(position, options) {
3678
+ var calldatas = [];
3679
+ var deadline = toHex(options.deadline);
3680
+ var tokenId = toHex(options.tokenId); // construct a partial position with a percentage of liquidity
3681
+
3682
+ var partialPosition = new Position({
3683
+ pool: position.pool,
3684
+ liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
3685
+ tickLower: position.tickLower,
3686
+ tickUpper: position.tickUpper
3687
+ });
3688
+ !JSBI.greaterThan(partialPosition.liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO_LIQUIDITY') : invariant(false) : void 0; // slippage-adjusted underlying amounts
3689
+
3690
+ var _partialPosition$burn = partialPosition.burnAmountsWithSlippage(options.slippageTolerance),
3691
+ amount0Min = _partialPosition$burn.amount0,
3692
+ amount1Min = _partialPosition$burn.amount1;
3693
+
3694
+ if (options.permit) {
3695
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('permit', [validateAndParseAddress(options.permit.spender), tokenId, toHex(options.permit.deadline), options.permit.v, options.permit.r, options.permit.s]));
3696
+ } // remove liquidity
3697
+
3698
+
3699
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('decreaseLiquidity', [{
3700
+ tokenId: tokenId,
3701
+ liquidity: toHex(partialPosition.liquidity),
3702
+ amount0Min: toHex(amount0Min),
3703
+ amount1Min: toHex(amount1Min),
3704
+ deadline: deadline
3705
+ }]));
3706
+
3707
+ var _options$collectOptio = options.collectOptions,
3708
+ expectedCurrencyOwed0 = _options$collectOptio.expectedCurrencyOwed0,
3709
+ expectedCurrencyOwed1 = _options$collectOptio.expectedCurrencyOwed1,
3710
+ rest = _objectWithoutPropertiesLoose(_options$collectOptio, ["expectedCurrencyOwed0", "expectedCurrencyOwed1"]);
3711
+
3712
+ calldatas.push.apply(calldatas, NonfungiblePositionManager.encodeCollect(_extends({
3713
+ tokenId: toHex(options.tokenId),
3714
+ // add the underlying value to the expected currency already owed
3715
+ expectedCurrencyOwed0: expectedCurrencyOwed0.add(CurrencyAmount.fromRawAmount(expectedCurrencyOwed0.currency, amount0Min)),
3716
+ expectedCurrencyOwed1: expectedCurrencyOwed1.add(CurrencyAmount.fromRawAmount(expectedCurrencyOwed1.currency, amount1Min))
3717
+ }, rest)));
3718
+
3719
+ if (options.liquidityPercentage.equalTo(ONE)) {
3720
+ if (options.burnToken) {
3721
+ calldatas.push(NonfungiblePositionManager.INTERFACE.encodeFunctionData('burn', [tokenId]));
3722
+ }
3723
+ } else {
3724
+ !(options.burnToken !== true) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CANNOT_BURN') : invariant(false) : void 0;
3725
+ }
3726
+
3727
+ return {
3728
+ calldata: Multicall.encodeMulticall(calldatas),
3729
+ value: toHex(0)
3730
+ };
3731
+ };
3732
+
3733
+ NonfungiblePositionManager.safeTransferFromParameters = function safeTransferFromParameters(options) {
3734
+ var recipient = validateAndParseAddress(options.recipient);
3735
+ var sender = validateAndParseAddress(options.sender);
3736
+ var calldata;
3737
+
3738
+ if (options.data) {
3739
+ calldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256,bytes)', [sender, recipient, toHex(options.tokenId), options.data]);
3740
+ } else {
3741
+ calldata = NonfungiblePositionManager.INTERFACE.encodeFunctionData('safeTransferFrom(address,address,uint256)', [sender, recipient, toHex(options.tokenId)]);
3742
+ }
3743
+
3744
+ return {
3745
+ calldata: calldata,
3746
+ value: toHex(0)
3747
+ };
3748
+ };
3749
+
3750
+ return NonfungiblePositionManager;
3751
+ }();
3752
+ NonfungiblePositionManager.INTERFACE = /*#__PURE__*/new Interface(INonfungiblePositionManager.abi);
3753
+
3754
+ /**
3755
+ * Represents the Uniswap V3 QuoterV1 contract with a method for returning the formatted
3756
+ * calldata needed to call the quoter contract.
3757
+ */
3758
+
3759
+ var SwapQuoter = /*#__PURE__*/function () {
3760
+ function SwapQuoter() {}
3761
+
3762
+ /**
3763
+ * Produces the on-chain method name of the appropriate function within QuoterV2,
3764
+ * and the relevant hex encoded parameters.
3765
+ * @template TInput The input token, either Ether or an ERC-20
3766
+ * @template TOutput The output token, either Ether or an ERC-20
3767
+ * @param route The swap route, a list of pools through which a swap can occur
3768
+ * @param amount The amount of the quote, either an amount in, or an amount out
3769
+ * @param tradeType The trade type, either exact input or exact output
3770
+ * @param options The optional params including price limit and Quoter contract switch
3771
+ * @returns The formatted calldata
3772
+ */
3773
+ SwapQuoter.quoteCallParameters = function quoteCallParameters(route, amount, tradeType, options) {
3774
+ if (options === void 0) {
3775
+ options = {};
3776
+ }
3777
+
3778
+ var singleHop = route.pools.length === 1;
3779
+ var quoteAmount = toHex(amount.quotient);
3780
+ var calldata;
3781
+ var swapInterface = options.useQuoterV2 ? this.V2INTERFACE : this.V1INTERFACE;
3782
+
3783
+ if (singleHop) {
3784
+ var _options$sqrtPriceLim, _options;
3785
+
3786
+ var baseQuoteParams = {
3787
+ tokenIn: route.tokenPath[0].address,
3788
+ tokenOut: route.tokenPath[1].address,
3789
+ fee: route.pools[0].fee,
3790
+ sqrtPriceLimitX96: toHex((_options$sqrtPriceLim = (_options = options) == null ? void 0 : _options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim : 0)
3791
+ };
3792
+
3793
+ var v2QuoteParams = _extends({}, baseQuoteParams, tradeType == TradeType.EXACT_INPUT ? {
3794
+ amountIn: quoteAmount
3795
+ } : {
3796
+ amount: quoteAmount
3797
+ });
3798
+
3799
+ var v1QuoteParams = [baseQuoteParams.tokenIn, baseQuoteParams.tokenOut, baseQuoteParams.fee, quoteAmount, baseQuoteParams.sqrtPriceLimitX96];
3800
+ var tradeTypeFunctionName = tradeType === TradeType.EXACT_INPUT ? 'quoteExactInputSingle' : 'quoteExactOutputSingle';
3801
+ calldata = swapInterface.encodeFunctionData(tradeTypeFunctionName, options.useQuoterV2 ? [v2QuoteParams] : v1QuoteParams);
3802
+ } else {
3803
+ var _options2;
3804
+
3805
+ !(((_options2 = options) == null ? void 0 : _options2.sqrtPriceLimitX96) === undefined) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MULTIHOP_PRICE_LIMIT') : invariant(false) : void 0;
3806
+ var path = encodeRouteToPath(route, tradeType === TradeType.EXACT_OUTPUT);
3807
+
3808
+ var _tradeTypeFunctionName = tradeType === TradeType.EXACT_INPUT ? 'quoteExactInput' : 'quoteExactOutput';
3809
+
3810
+ calldata = swapInterface.encodeFunctionData(_tradeTypeFunctionName, [path, quoteAmount]);
3811
+ }
3812
+
3813
+ return {
3814
+ calldata: calldata,
3815
+ value: toHex(0)
3816
+ };
3817
+ };
3818
+
3819
+ return SwapQuoter;
3820
+ }();
3821
+ SwapQuoter.V1INTERFACE = /*#__PURE__*/new Interface(IQuoter.abi);
3822
+ SwapQuoter.V2INTERFACE = /*#__PURE__*/new Interface(IQuoterV2.abi);
3823
+
3824
+ var Staker = /*#__PURE__*/function () {
3825
+ function Staker() {}
3826
+ /**
3827
+ * To claim rewards, must unstake and then claim.
3828
+ * @param incentiveKey The unique identifier of a staking program.
3829
+ * @param options Options for producing the calldata to claim. Can't claim unless you unstake.
3830
+ * @returns The calldatas for 'unstakeToken' and 'claimReward'.
3831
+ */
3832
+
3833
+
3834
+ Staker.encodeClaim = function encodeClaim(incentiveKey, options) {
3835
+ var _options$amount;
3836
+
3837
+ var calldatas = [];
3838
+ calldatas.push(Staker.INTERFACE.encodeFunctionData('unstakeToken', [this._encodeIncentiveKey(incentiveKey), toHex(options.tokenId)]));
3839
+ var recipient = validateAndParseAddress(options.recipient);
3840
+ var amount = (_options$amount = options.amount) != null ? _options$amount : 0;
3841
+ calldatas.push(Staker.INTERFACE.encodeFunctionData('claimReward', [incentiveKey.rewardToken.address, recipient, toHex(amount)]));
3842
+ return calldatas;
3843
+ }
3844
+ /**
3845
+ *
3846
+ * Note: A `tokenId` can be staked in many programs but to claim rewards and continue the program you must unstake, claim, and then restake.
3847
+ * @param incentiveKeys An IncentiveKey or array of IncentiveKeys that `tokenId` is staked in.
3848
+ * Input an array of IncentiveKeys to claim rewards for each program.
3849
+ * @param options ClaimOptions to specify tokenId, recipient, and amount wanting to collect.
3850
+ * Note that you can only specify one amount and one recipient across the various programs if you are collecting from multiple programs at once.
3851
+ * @returns
3852
+ */
3853
+ ;
3854
+
3855
+ Staker.collectRewards = function collectRewards(incentiveKeys, options) {
3856
+ incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
3857
+ var calldatas = [];
3858
+
3859
+ for (var i = 0; i < incentiveKeys.length; i++) {
3860
+ // the unique program tokenId is staked in
3861
+ var incentiveKey = incentiveKeys[i]; // unstakes and claims for the unique program
3862
+
3863
+ calldatas = calldatas.concat(this.encodeClaim(incentiveKey, options)); // re-stakes the position for the unique program
3864
+
3865
+ calldatas.push(Staker.INTERFACE.encodeFunctionData('stakeToken', [this._encodeIncentiveKey(incentiveKey), toHex(options.tokenId)]));
3866
+ }
3867
+
3868
+ return {
3869
+ calldata: Multicall.encodeMulticall(calldatas),
3870
+ value: toHex(0)
3871
+ };
3872
+ }
3873
+ /**
3874
+ *
3875
+ * @param incentiveKeys A list of incentiveKeys to unstake from. Should include all incentiveKeys (unique staking programs) that `options.tokenId` is staked in.
3876
+ * @param withdrawOptions Options for producing claim calldata and withdraw calldata. Can't withdraw without unstaking all programs for `tokenId`.
3877
+ * @returns Calldata for unstaking, claiming, and withdrawing.
3878
+ */
3879
+ ;
3880
+
3881
+ Staker.withdrawToken = function withdrawToken(incentiveKeys, withdrawOptions) {
3882
+ var calldatas = [];
3883
+ incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
3884
+ var claimOptions = {
3885
+ tokenId: withdrawOptions.tokenId,
3886
+ recipient: withdrawOptions.recipient,
3887
+ amount: withdrawOptions.amount
3888
+ };
3889
+
3890
+ for (var i = 0; i < incentiveKeys.length; i++) {
3891
+ var incentiveKey = incentiveKeys[i];
3892
+ calldatas = calldatas.concat(this.encodeClaim(incentiveKey, claimOptions));
3893
+ }
3894
+
3895
+ var owner = validateAndParseAddress(withdrawOptions.owner);
3896
+ calldatas.push(Staker.INTERFACE.encodeFunctionData('withdrawToken', [toHex(withdrawOptions.tokenId), owner, withdrawOptions.data ? withdrawOptions.data : toHex(0)]));
3897
+ return {
3898
+ calldata: Multicall.encodeMulticall(calldatas),
3899
+ value: toHex(0)
3900
+ };
3901
+ }
3902
+ /**
3903
+ *
3904
+ * @param incentiveKeys A single IncentiveKey or array of IncentiveKeys to be encoded and used in the data parameter in `safeTransferFrom`
3905
+ * @returns An IncentiveKey as a string
3906
+ */
3907
+ ;
3908
+
3909
+ Staker.encodeDeposit = function encodeDeposit(incentiveKeys) {
3910
+ incentiveKeys = Array.isArray(incentiveKeys) ? incentiveKeys : [incentiveKeys];
3911
+ var data;
3912
+
3913
+ if (incentiveKeys.length > 1) {
3914
+ var keys = [];
3915
+
3916
+ for (var i = 0; i < incentiveKeys.length; i++) {
3917
+ var incentiveKey = incentiveKeys[i];
3918
+ keys.push(this._encodeIncentiveKey(incentiveKey));
3919
+ }
3920
+
3921
+ data = defaultAbiCoder.encode([Staker.INCENTIVE_KEY_ABI + "[]"], [keys]);
3922
+ } else {
3923
+ data = defaultAbiCoder.encode([Staker.INCENTIVE_KEY_ABI], [this._encodeIncentiveKey(incentiveKeys[0])]);
3924
+ }
3925
+
3926
+ return data;
3927
+ }
3928
+ /**
3929
+ *
3930
+ * @param incentiveKey An `IncentiveKey` which represents a unique staking program.
3931
+ * @returns An encoded IncentiveKey to be read by ethers
3932
+ */
3933
+ ;
3934
+
3935
+ Staker._encodeIncentiveKey = function _encodeIncentiveKey(incentiveKey) {
3936
+ var _incentiveKey$pool = incentiveKey.pool,
3937
+ token0 = _incentiveKey$pool.token0,
3938
+ token1 = _incentiveKey$pool.token1,
3939
+ fee = _incentiveKey$pool.fee;
3940
+ var refundee = validateAndParseAddress(incentiveKey.refundee);
3941
+ return {
3942
+ rewardToken: incentiveKey.rewardToken.address,
3943
+ pool: Pool.getAddress(token0, token1, fee),
3944
+ startTime: toHex(incentiveKey.startTime),
3945
+ endTime: toHex(incentiveKey.endTime),
3946
+ refundee: refundee
3947
+ };
3948
+ };
3949
+
3950
+ return Staker;
3951
+ }();
3952
+ Staker.INTERFACE = /*#__PURE__*/new Interface(IUniswapV3Staker.abi);
3953
+ Staker.INCENTIVE_KEY_ABI = 'tuple(address rewardToken, address pool, uint256 startTime, uint256 endTime, address refundee)';
3954
+
3955
+ /**
3956
+ * Represents the Uniswap V3 SwapRouter, and has static methods for helping execute trades.
3957
+ */
3958
+
3959
+ var SwapRouter = /*#__PURE__*/function () {
3960
+ /**
3961
+ * Cannot be constructed.
3962
+ */
3963
+ function SwapRouter() {}
3964
+ /**
3965
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
3966
+ * @param trade to produce call parameters for
3967
+ * @param options options for the call parameters
3968
+ */
3969
+
3970
+
3971
+ SwapRouter.swapCallParameters = function swapCallParameters(trades, options) {
3972
+ if (!Array.isArray(trades)) {
3973
+ trades = [trades];
3974
+ }
3975
+
3976
+ var sampleTrade = trades[0];
3977
+ var tokenIn = sampleTrade.inputAmount.currency.wrapped;
3978
+ var tokenOut = sampleTrade.outputAmount.currency.wrapped; // All trades should have the same starting and ending token.
3979
+
3980
+ !trades.every(function (trade) {
3981
+ return trade.inputAmount.currency.wrapped.equals(tokenIn);
3982
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN_IN_DIFF') : invariant(false) : void 0;
3983
+ !trades.every(function (trade) {
3984
+ return trade.outputAmount.currency.wrapped.equals(tokenOut);
3985
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN_OUT_DIFF') : invariant(false) : void 0;
3986
+ var calldatas = [];
3987
+ var ZERO_IN = CurrencyAmount.fromRawAmount(trades[0].inputAmount.currency, 0);
3988
+ var ZERO_OUT = CurrencyAmount.fromRawAmount(trades[0].outputAmount.currency, 0);
3989
+ var totalAmountOut = trades.reduce(function (sum, trade) {
3990
+ return sum.add(trade.minimumAmountOut(options.slippageTolerance));
3991
+ }, ZERO_OUT); // flag for whether a refund needs to happen
3992
+
3993
+ var mustRefund = sampleTrade.inputAmount.currency.isNative && sampleTrade.tradeType === TradeType.EXACT_OUTPUT;
3994
+ var inputIsNative = sampleTrade.inputAmount.currency.isNative; // flags for whether funds should be send first to the router
3995
+
3996
+ var outputIsNative = sampleTrade.outputAmount.currency.isNative;
3997
+ var routerMustCustody = outputIsNative || !!options.fee;
3998
+ var totalValue = inputIsNative ? trades.reduce(function (sum, trade) {
3999
+ return sum.add(trade.maximumAmountIn(options.slippageTolerance));
4000
+ }, ZERO_IN) : ZERO_IN; // encode permit if necessary
4001
+
4002
+ if (options.inputTokenPermit) {
4003
+ !sampleTrade.inputAmount.currency.isToken ? process.env.NODE_ENV !== "production" ? invariant(false, 'NON_TOKEN_PERMIT') : invariant(false) : void 0;
4004
+ calldatas.push(SelfPermit.encodePermit(sampleTrade.inputAmount.currency, options.inputTokenPermit));
4005
+ }
4006
+
4007
+ var recipient = validateAndParseAddress(options.recipient);
4008
+ var deadline = toHex(options.deadline);
4009
+
4010
+ for (var _iterator = _createForOfIteratorHelperLoose(trades), _step; !(_step = _iterator()).done;) {
4011
+ var trade = _step.value;
4012
+
4013
+ for (var _iterator2 = _createForOfIteratorHelperLoose(trade.swaps), _step2; !(_step2 = _iterator2()).done;) {
4014
+ var _step2$value = _step2.value,
4015
+ route = _step2$value.route,
4016
+ inputAmount = _step2$value.inputAmount,
4017
+ outputAmount = _step2$value.outputAmount;
4018
+ var amountIn = toHex(trade.maximumAmountIn(options.slippageTolerance, inputAmount).quotient);
4019
+ var amountOut = toHex(trade.minimumAmountOut(options.slippageTolerance, outputAmount).quotient); // flag for whether the trade is single hop or not
4020
+
4021
+ var singleHop = route.pools.length === 1;
4022
+
4023
+ if (singleHop) {
4024
+ if (trade.tradeType === TradeType.EXACT_INPUT) {
4025
+ var _options$sqrtPriceLim;
4026
+
4027
+ var exactInputSingleParams = {
4028
+ tokenIn: route.tokenPath[0].address,
4029
+ tokenOut: route.tokenPath[1].address,
4030
+ fee: route.pools[0].fee,
4031
+ recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
4032
+ deadline: deadline,
4033
+ amountIn: amountIn,
4034
+ amountOutMinimum: amountOut,
4035
+ sqrtPriceLimitX96: toHex((_options$sqrtPriceLim = options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim : 0)
4036
+ };
4037
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInputSingle', [exactInputSingleParams]));
4038
+ } else {
4039
+ var _options$sqrtPriceLim2;
4040
+
4041
+ var exactOutputSingleParams = {
4042
+ tokenIn: route.tokenPath[0].address,
4043
+ tokenOut: route.tokenPath[1].address,
4044
+ fee: route.pools[0].fee,
4045
+ recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
4046
+ deadline: deadline,
4047
+ amountOut: amountOut,
4048
+ amountInMaximum: amountIn,
4049
+ sqrtPriceLimitX96: toHex((_options$sqrtPriceLim2 = options.sqrtPriceLimitX96) != null ? _options$sqrtPriceLim2 : 0)
4050
+ };
4051
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutputSingle', [exactOutputSingleParams]));
4052
+ }
4053
+ } else {
4054
+ !(options.sqrtPriceLimitX96 === undefined) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MULTIHOP_PRICE_LIMIT') : invariant(false) : void 0;
4055
+ var path = encodeRouteToPath(route, trade.tradeType === TradeType.EXACT_OUTPUT);
4056
+
4057
+ if (trade.tradeType === TradeType.EXACT_INPUT) {
4058
+ var exactInputParams = {
4059
+ path: path,
4060
+ recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
4061
+ deadline: deadline,
4062
+ amountIn: amountIn,
4063
+ amountOutMinimum: amountOut
4064
+ };
4065
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactInput', [exactInputParams]));
4066
+ } else {
4067
+ var exactOutputParams = {
4068
+ path: path,
4069
+ recipient: routerMustCustody ? ADDRESS_ZERO : recipient,
4070
+ deadline: deadline,
4071
+ amountOut: amountOut,
4072
+ amountInMaximum: amountIn
4073
+ };
4074
+ calldatas.push(SwapRouter.INTERFACE.encodeFunctionData('exactOutput', [exactOutputParams]));
4075
+ }
4076
+ }
4077
+ }
4078
+ } // unwrap
4079
+
4080
+
4081
+ if (routerMustCustody) {
4082
+ if (!!options.fee) {
4083
+ if (outputIsNative) {
4084
+ calldatas.push(Payments.encodeUnwrapWETH9(totalAmountOut.quotient, recipient, options.fee));
4085
+ } else {
4086
+ calldatas.push(Payments.encodeSweepToken(sampleTrade.outputAmount.currency.wrapped, totalAmountOut.quotient, recipient, options.fee));
4087
+ }
4088
+ } else {
4089
+ calldatas.push(Payments.encodeUnwrapWETH9(totalAmountOut.quotient, recipient));
4090
+ }
4091
+ } // refund
4092
+
4093
+
4094
+ if (mustRefund) {
4095
+ calldatas.push(Payments.encodeRefundETH());
4096
+ }
4097
+
4098
+ return {
4099
+ calldata: Multicall.encodeMulticall(calldatas),
4100
+ value: toHex(totalValue.quotient)
4101
+ };
4102
+ };
4103
+
4104
+ return SwapRouter;
4105
+ }();
4106
+ SwapRouter.INTERFACE = /*#__PURE__*/new Interface(ISwapRouter.abi);
4107
+
4108
+ export { ADDRESS_ZERO, FACTORY_ADDRESS, FeeAmount, FullMath, LiquidityMath, Multicall, NoTickDataProvider, NonfungiblePositionManager, POOL_INIT_CODE_HASH, Payments, Pool, Position, PositionLibrary, Route, SelfPermit, SqrtPriceMath, Staker, SwapMath, SwapQuoter, SwapRouter, TICK_SPACINGS, Tick, TickLibrary, TickList, TickListDataProvider, TickMath, Trade, computePoolAddress, encodeRouteToPath, encodeSqrtRatioX96, isSorted, maxLiquidityForAmounts, mostSignificantBit, nearestUsableTick, priceToClosestTick, subIn256, tickToPrice, toHex, tradeComparator };
4109
+ //# sourceMappingURL=elephantswapv3-sdk.esm.js.map