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