@kittycorn-labs/v4-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3721 @@
1
+ import invariant from 'tiny-invariant';
2
+ import { keccak256 } from '@ethersproject/solidity';
3
+ import { Price, CurrencyAmount, TradeType, Fraction, Percent, sortedInsert, MaxUint256, validateAndParseAddress } from '@uniswap/sdk-core';
4
+ import { TickMath, TickListDataProvider, v3Swap, NoTickDataProvider, encodeSqrtRatioX96, maxLiquidityForAmounts, SqrtPriceMath } from '@uniswap/v3-sdk';
5
+ import { isAddress, defaultAbiCoder } from 'ethers/lib/utils';
6
+ import JSBI from 'jsbi';
7
+ import { constants, ethers } from 'ethers';
8
+ import { Interface } from '@ethersproject/abi';
9
+ import IMulticall from '@uniswap/v3-periphery/artifacts/contracts/interfaces/IMulticall.sol/IMulticall.json';
10
+
11
+ function _arrayLikeToArray(r, a) {
12
+ (null == a || a > r.length) && (a = r.length);
13
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
14
+ return n;
15
+ }
16
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
17
+ try {
18
+ var i = n[a](c),
19
+ u = i.value;
20
+ } catch (n) {
21
+ return void e(n);
22
+ }
23
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
24
+ }
25
+ function _asyncToGenerator(n) {
26
+ return function () {
27
+ var t = this,
28
+ e = arguments;
29
+ return new Promise(function (r, o) {
30
+ var a = n.apply(t, e);
31
+ function _next(n) {
32
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
33
+ }
34
+ function _throw(n) {
35
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
36
+ }
37
+ _next(void 0);
38
+ });
39
+ };
40
+ }
41
+ function _defineProperties(e, r) {
42
+ for (var t = 0; t < r.length; t++) {
43
+ var o = r[t];
44
+ o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
45
+ }
46
+ }
47
+ function _createClass(e, r, t) {
48
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
49
+ writable: !1
50
+ }), e;
51
+ }
52
+ function _createForOfIteratorHelperLoose(r, e) {
53
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
54
+ if (t) return (t = t.call(r)).next.bind(t);
55
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
56
+ t && (r = t);
57
+ var o = 0;
58
+ return function () {
59
+ return o >= r.length ? {
60
+ done: !0
61
+ } : {
62
+ done: !1,
63
+ value: r[o++]
64
+ };
65
+ };
66
+ }
67
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
68
+ }
69
+ function _extends() {
70
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
71
+ for (var e = 1; e < arguments.length; e++) {
72
+ var t = arguments[e];
73
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
74
+ }
75
+ return n;
76
+ }, _extends.apply(null, arguments);
77
+ }
78
+ function _inheritsLoose(t, o) {
79
+ t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
80
+ }
81
+ function _regeneratorRuntime() {
82
+ _regeneratorRuntime = function () {
83
+ return e;
84
+ };
85
+ var t,
86
+ e = {},
87
+ r = Object.prototype,
88
+ n = r.hasOwnProperty,
89
+ o = Object.defineProperty || function (t, e, r) {
90
+ t[e] = r.value;
91
+ },
92
+ i = "function" == typeof Symbol ? Symbol : {},
93
+ a = i.iterator || "@@iterator",
94
+ c = i.asyncIterator || "@@asyncIterator",
95
+ u = i.toStringTag || "@@toStringTag";
96
+ function define(t, e, r) {
97
+ return Object.defineProperty(t, e, {
98
+ value: r,
99
+ enumerable: !0,
100
+ configurable: !0,
101
+ writable: !0
102
+ }), t[e];
103
+ }
104
+ try {
105
+ define({}, "");
106
+ } catch (t) {
107
+ define = function (t, e, r) {
108
+ return t[e] = r;
109
+ };
110
+ }
111
+ function wrap(t, e, r, n) {
112
+ var i = e && e.prototype instanceof Generator ? e : Generator,
113
+ a = Object.create(i.prototype),
114
+ c = new Context(n || []);
115
+ return o(a, "_invoke", {
116
+ value: makeInvokeMethod(t, r, c)
117
+ }), a;
118
+ }
119
+ function tryCatch(t, e, r) {
120
+ try {
121
+ return {
122
+ type: "normal",
123
+ arg: t.call(e, r)
124
+ };
125
+ } catch (t) {
126
+ return {
127
+ type: "throw",
128
+ arg: t
129
+ };
130
+ }
131
+ }
132
+ e.wrap = wrap;
133
+ var h = "suspendedStart",
134
+ l = "suspendedYield",
135
+ f = "executing",
136
+ s = "completed",
137
+ y = {};
138
+ function Generator() {}
139
+ function GeneratorFunction() {}
140
+ function GeneratorFunctionPrototype() {}
141
+ var p = {};
142
+ define(p, a, function () {
143
+ return this;
144
+ });
145
+ var d = Object.getPrototypeOf,
146
+ v = d && d(d(values([])));
147
+ v && v !== r && n.call(v, a) && (p = v);
148
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
149
+ function defineIteratorMethods(t) {
150
+ ["next", "throw", "return"].forEach(function (e) {
151
+ define(t, e, function (t) {
152
+ return this._invoke(e, t);
153
+ });
154
+ });
155
+ }
156
+ function AsyncIterator(t, e) {
157
+ function invoke(r, o, i, a) {
158
+ var c = tryCatch(t[r], t, o);
159
+ if ("throw" !== c.type) {
160
+ var u = c.arg,
161
+ h = u.value;
162
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
163
+ invoke("next", t, i, a);
164
+ }, function (t) {
165
+ invoke("throw", t, i, a);
166
+ }) : e.resolve(h).then(function (t) {
167
+ u.value = t, i(u);
168
+ }, function (t) {
169
+ return invoke("throw", t, i, a);
170
+ });
171
+ }
172
+ a(c.arg);
173
+ }
174
+ var r;
175
+ o(this, "_invoke", {
176
+ value: function (t, n) {
177
+ function callInvokeWithMethodAndArg() {
178
+ return new e(function (e, r) {
179
+ invoke(t, n, e, r);
180
+ });
181
+ }
182
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
183
+ }
184
+ });
185
+ }
186
+ function makeInvokeMethod(e, r, n) {
187
+ var o = h;
188
+ return function (i, a) {
189
+ if (o === f) throw Error("Generator is already running");
190
+ if (o === s) {
191
+ if ("throw" === i) throw a;
192
+ return {
193
+ value: t,
194
+ done: !0
195
+ };
196
+ }
197
+ for (n.method = i, n.arg = a;;) {
198
+ var c = n.delegate;
199
+ if (c) {
200
+ var u = maybeInvokeDelegate(c, n);
201
+ if (u) {
202
+ if (u === y) continue;
203
+ return u;
204
+ }
205
+ }
206
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
207
+ if (o === h) throw o = s, n.arg;
208
+ n.dispatchException(n.arg);
209
+ } else "return" === n.method && n.abrupt("return", n.arg);
210
+ o = f;
211
+ var p = tryCatch(e, r, n);
212
+ if ("normal" === p.type) {
213
+ if (o = n.done ? s : l, p.arg === y) continue;
214
+ return {
215
+ value: p.arg,
216
+ done: n.done
217
+ };
218
+ }
219
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
220
+ }
221
+ };
222
+ }
223
+ function maybeInvokeDelegate(e, r) {
224
+ var n = r.method,
225
+ o = e.iterator[n];
226
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
227
+ var i = tryCatch(o, e.iterator, r.arg);
228
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
229
+ var a = i.arg;
230
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
231
+ }
232
+ function pushTryEntry(t) {
233
+ var e = {
234
+ tryLoc: t[0]
235
+ };
236
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
237
+ }
238
+ function resetTryEntry(t) {
239
+ var e = t.completion || {};
240
+ e.type = "normal", delete e.arg, t.completion = e;
241
+ }
242
+ function Context(t) {
243
+ this.tryEntries = [{
244
+ tryLoc: "root"
245
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
246
+ }
247
+ function values(e) {
248
+ if (e || "" === e) {
249
+ var r = e[a];
250
+ if (r) return r.call(e);
251
+ if ("function" == typeof e.next) return e;
252
+ if (!isNaN(e.length)) {
253
+ var o = -1,
254
+ i = function next() {
255
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
256
+ return next.value = t, next.done = !0, next;
257
+ };
258
+ return i.next = i;
259
+ }
260
+ }
261
+ throw new TypeError(typeof e + " is not iterable");
262
+ }
263
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
264
+ value: GeneratorFunctionPrototype,
265
+ configurable: !0
266
+ }), o(GeneratorFunctionPrototype, "constructor", {
267
+ value: GeneratorFunction,
268
+ configurable: !0
269
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
270
+ var e = "function" == typeof t && t.constructor;
271
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
272
+ }, e.mark = function (t) {
273
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
274
+ }, e.awrap = function (t) {
275
+ return {
276
+ __await: t
277
+ };
278
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
279
+ return this;
280
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
281
+ void 0 === i && (i = Promise);
282
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
283
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
284
+ return t.done ? t.value : a.next();
285
+ });
286
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
287
+ return this;
288
+ }), define(g, "toString", function () {
289
+ return "[object Generator]";
290
+ }), e.keys = function (t) {
291
+ var e = Object(t),
292
+ r = [];
293
+ for (var n in e) r.push(n);
294
+ return r.reverse(), function next() {
295
+ for (; r.length;) {
296
+ var t = r.pop();
297
+ if (t in e) return next.value = t, next.done = !1, next;
298
+ }
299
+ return next.done = !0, next;
300
+ };
301
+ }, e.values = values, Context.prototype = {
302
+ constructor: Context,
303
+ reset: function (e) {
304
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
305
+ },
306
+ stop: function () {
307
+ this.done = !0;
308
+ var t = this.tryEntries[0].completion;
309
+ if ("throw" === t.type) throw t.arg;
310
+ return this.rval;
311
+ },
312
+ dispatchException: function (e) {
313
+ if (this.done) throw e;
314
+ var r = this;
315
+ function handle(n, o) {
316
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
317
+ }
318
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
319
+ var i = this.tryEntries[o],
320
+ a = i.completion;
321
+ if ("root" === i.tryLoc) return handle("end");
322
+ if (i.tryLoc <= this.prev) {
323
+ var c = n.call(i, "catchLoc"),
324
+ u = n.call(i, "finallyLoc");
325
+ if (c && u) {
326
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
327
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
328
+ } else if (c) {
329
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
330
+ } else {
331
+ if (!u) throw Error("try statement without catch or finally");
332
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
333
+ }
334
+ }
335
+ }
336
+ },
337
+ abrupt: function (t, e) {
338
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
339
+ var o = this.tryEntries[r];
340
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
341
+ var i = o;
342
+ break;
343
+ }
344
+ }
345
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
346
+ var a = i ? i.completion : {};
347
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
348
+ },
349
+ complete: function (t, e) {
350
+ if ("throw" === t.type) throw t.arg;
351
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
352
+ },
353
+ finish: function (t) {
354
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
355
+ var r = this.tryEntries[e];
356
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
357
+ }
358
+ },
359
+ catch: function (t) {
360
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
361
+ var r = this.tryEntries[e];
362
+ if (r.tryLoc === t) {
363
+ var n = r.completion;
364
+ if ("throw" === n.type) {
365
+ var o = n.arg;
366
+ resetTryEntry(r);
367
+ }
368
+ return o;
369
+ }
370
+ }
371
+ throw Error("illegal catch attempt");
372
+ },
373
+ delegateYield: function (e, r, n) {
374
+ return this.delegate = {
375
+ iterator: values(e),
376
+ resultName: r,
377
+ nextLoc: n
378
+ }, "next" === this.method && (this.arg = t), y;
379
+ }
380
+ }, e;
381
+ }
382
+ function _setPrototypeOf(t, e) {
383
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
384
+ return t.__proto__ = e, t;
385
+ }, _setPrototypeOf(t, e);
386
+ }
387
+ function _toPrimitive(t, r) {
388
+ if ("object" != typeof t || !t) return t;
389
+ var e = t[Symbol.toPrimitive];
390
+ if (void 0 !== e) {
391
+ var i = e.call(t, r || "default");
392
+ if ("object" != typeof i) return i;
393
+ throw new TypeError("@@toPrimitive must return a primitive value.");
394
+ }
395
+ return ("string" === r ? String : Number)(t);
396
+ }
397
+ function _toPropertyKey(t) {
398
+ var i = _toPrimitive(t, "string");
399
+ return "symbol" == typeof i ? i : i + "";
400
+ }
401
+ function _unsupportedIterableToArray(r, a) {
402
+ if (r) {
403
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
404
+ var t = {}.toString.call(r).slice(8, -1);
405
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
406
+ }
407
+ }
408
+
409
+ function sortsBefore(currencyA, currencyB) {
410
+ if (currencyA.isNative) return true;
411
+ if (currencyB.isNative) return false;
412
+ return currencyA.wrapped.sortsBefore(currencyB.wrapped);
413
+ }
414
+
415
+ var _hookFlagIndex;
416
+ var HookOptions;
417
+ (function (HookOptions) {
418
+ HookOptions["AfterRemoveLiquidityReturnsDelta"] = "afterRemoveLiquidityReturnsDelta";
419
+ HookOptions["AfterAddLiquidityReturnsDelta"] = "afterAddLiquidityReturnsDelta";
420
+ HookOptions["AfterSwapReturnsDelta"] = "afterSwapReturnsDelta";
421
+ HookOptions["BeforeSwapReturnsDelta"] = "beforeSwapReturnsDelta";
422
+ HookOptions["AfterDonate"] = "afterDonate";
423
+ HookOptions["BeforeDonate"] = "beforeDonate";
424
+ HookOptions["AfterSwap"] = "afterSwap";
425
+ HookOptions["BeforeSwap"] = "beforeSwap";
426
+ HookOptions["AfterRemoveLiquidity"] = "afterRemoveLiquidity";
427
+ HookOptions["BeforeRemoveLiquidity"] = "beforeRemoveLiquidity";
428
+ HookOptions["AfterAddLiquidity"] = "afterAddLiquidity";
429
+ HookOptions["BeforeAddLiquidity"] = "beforeAddLiquidity";
430
+ HookOptions["AfterInitialize"] = "afterInitialize";
431
+ HookOptions["BeforeInitialize"] = "beforeInitialize";
432
+ })(HookOptions || (HookOptions = {}));
433
+ var hookFlagIndex = (_hookFlagIndex = {}, _hookFlagIndex[HookOptions.AfterRemoveLiquidityReturnsDelta] = 0, _hookFlagIndex[HookOptions.AfterAddLiquidityReturnsDelta] = 1, _hookFlagIndex[HookOptions.AfterSwapReturnsDelta] = 2, _hookFlagIndex[HookOptions.BeforeSwapReturnsDelta] = 3, _hookFlagIndex[HookOptions.AfterDonate] = 4, _hookFlagIndex[HookOptions.BeforeDonate] = 5, _hookFlagIndex[HookOptions.AfterSwap] = 6, _hookFlagIndex[HookOptions.BeforeSwap] = 7, _hookFlagIndex[HookOptions.AfterRemoveLiquidity] = 8, _hookFlagIndex[HookOptions.BeforeRemoveLiquidity] = 9, _hookFlagIndex[HookOptions.AfterAddLiquidity] = 10, _hookFlagIndex[HookOptions.BeforeAddLiquidity] = 11, _hookFlagIndex[HookOptions.AfterInitialize] = 12, _hookFlagIndex[HookOptions.BeforeInitialize] = 13, _hookFlagIndex);
434
+ var Hook = /*#__PURE__*/function () {
435
+ function Hook() {}
436
+ Hook.permissions = function permissions(address) {
437
+ this._checkAddress(address);
438
+ return {
439
+ beforeInitialize: this._hasPermission(address, HookOptions.BeforeInitialize),
440
+ afterInitialize: this._hasPermission(address, HookOptions.AfterInitialize),
441
+ beforeAddLiquidity: this._hasPermission(address, HookOptions.BeforeAddLiquidity),
442
+ afterAddLiquidity: this._hasPermission(address, HookOptions.AfterAddLiquidity),
443
+ beforeRemoveLiquidity: this._hasPermission(address, HookOptions.BeforeRemoveLiquidity),
444
+ afterRemoveLiquidity: this._hasPermission(address, HookOptions.AfterRemoveLiquidity),
445
+ beforeSwap: this._hasPermission(address, HookOptions.BeforeSwap),
446
+ afterSwap: this._hasPermission(address, HookOptions.AfterSwap),
447
+ beforeDonate: this._hasPermission(address, HookOptions.BeforeDonate),
448
+ afterDonate: this._hasPermission(address, HookOptions.AfterDonate),
449
+ beforeSwapReturnsDelta: this._hasPermission(address, HookOptions.BeforeSwapReturnsDelta),
450
+ afterSwapReturnsDelta: this._hasPermission(address, HookOptions.AfterSwapReturnsDelta),
451
+ afterAddLiquidityReturnsDelta: this._hasPermission(address, HookOptions.AfterAddLiquidityReturnsDelta),
452
+ afterRemoveLiquidityReturnsDelta: this._hasPermission(address, HookOptions.AfterRemoveLiquidityReturnsDelta)
453
+ };
454
+ };
455
+ Hook.hasPermission = function hasPermission(address, hookOption) {
456
+ this._checkAddress(address);
457
+ return this._hasPermission(address, hookOption);
458
+ };
459
+ Hook.hasInitializePermissions = function hasInitializePermissions(address) {
460
+ this._checkAddress(address);
461
+ return this._hasPermission(address, HookOptions.BeforeInitialize) || Hook._hasPermission(address, HookOptions.AfterInitialize);
462
+ };
463
+ Hook.hasLiquidityPermissions = function hasLiquidityPermissions(address) {
464
+ this._checkAddress(address);
465
+ // this implicitly encapsulates liquidity delta permissions
466
+ return this._hasPermission(address, HookOptions.BeforeAddLiquidity) || Hook._hasPermission(address, HookOptions.AfterAddLiquidity) || Hook._hasPermission(address, HookOptions.BeforeRemoveLiquidity) || Hook._hasPermission(address, HookOptions.AfterRemoveLiquidity);
467
+ };
468
+ Hook.hasSwapPermissions = function hasSwapPermissions(address) {
469
+ this._checkAddress(address);
470
+ // this implicitly encapsulates swap delta permissions
471
+ return this._hasPermission(address, HookOptions.BeforeSwap) || Hook._hasPermission(address, HookOptions.AfterSwap);
472
+ };
473
+ Hook.hasDonatePermissions = function hasDonatePermissions(address) {
474
+ this._checkAddress(address);
475
+ return this._hasPermission(address, HookOptions.BeforeDonate) || Hook._hasPermission(address, HookOptions.AfterDonate);
476
+ };
477
+ Hook._hasPermission = function _hasPermission(address, hookOption) {
478
+ return !!(parseInt(address, 16) & 1 << hookFlagIndex[hookOption]);
479
+ };
480
+ Hook._checkAddress = function _checkAddress(address) {
481
+ !isAddress(address) ? process.env.NODE_ENV !== "production" ? invariant(false, 'invalid address') : invariant(false) : void 0;
482
+ };
483
+ return Hook;
484
+ }();
485
+
486
+ var _TICK_SPACINGS;
487
+ // constants used internally but not expected to be used externally
488
+ var ADDRESS_ZERO = constants.AddressZero;
489
+ var NEGATIVE_ONE = /*#__PURE__*/JSBI.BigInt(-1);
490
+ var ZERO = /*#__PURE__*/JSBI.BigInt(0);
491
+ var ONE = /*#__PURE__*/JSBI.BigInt(1);
492
+ var EMPTY_BYTES = '0x';
493
+ // used in liquidity amount math
494
+ var Q96 = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(96));
495
+ var Q192 = /*#__PURE__*/JSBI.exponentiate(Q96, /*#__PURE__*/JSBI.BigInt(2));
496
+ // used when unwrapping weth in positon manager
497
+ var OPEN_DELTA = constants.Zero;
498
+ // error constants
499
+ var NATIVE_NOT_SET = 'NATIVE_NOT_SET';
500
+ var ZERO_LIQUIDITY = 'ZERO_LIQUIDITY';
501
+ var NO_SQRT_PRICE = 'NO_SQRT_PRICE';
502
+ var CANNOT_BURN = 'CANNOT_BURN';
503
+ /**
504
+ * Function fragments that exist on the PositionManager contract.
505
+ */
506
+ var PositionFunctions;
507
+ (function (PositionFunctions) {
508
+ PositionFunctions["INITIALIZE_POOL"] = "initializePool";
509
+ PositionFunctions["MODIFY_LIQUIDITIES"] = "modifyLiquidities";
510
+ // Inherited from PermitForwarder
511
+ PositionFunctions["PERMIT_BATCH"] = "0x002a3e3a";
512
+ // Inherited from ERC721Permit
513
+ PositionFunctions["ERC721PERMIT_PERMIT"] = "0x0f5730f1";
514
+ })(PositionFunctions || (PositionFunctions = {}));
515
+ /**
516
+ * The default factory enabled fee amounts, denominated in hundredths of bips.
517
+ */
518
+ var FeeAmount;
519
+ (function (FeeAmount) {
520
+ FeeAmount[FeeAmount["LOWEST"] = 100] = "LOWEST";
521
+ FeeAmount[FeeAmount["LOW"] = 500] = "LOW";
522
+ FeeAmount[FeeAmount["MEDIUM"] = 3000] = "MEDIUM";
523
+ FeeAmount[FeeAmount["HIGH"] = 10000] = "HIGH";
524
+ })(FeeAmount || (FeeAmount = {}));
525
+ /**
526
+ * The default factory tick spacings by fee amount.
527
+ */
528
+ var TICK_SPACINGS = (_TICK_SPACINGS = {}, _TICK_SPACINGS[FeeAmount.LOWEST] = 1, _TICK_SPACINGS[FeeAmount.LOW] = 10, _TICK_SPACINGS[FeeAmount.MEDIUM] = 60, _TICK_SPACINGS[FeeAmount.HIGH] = 200, _TICK_SPACINGS);
529
+
530
+ var DYNAMIC_FEE_FLAG = 0x800000;
531
+ var NO_TICK_DATA_PROVIDER_DEFAULT = /*#__PURE__*/new NoTickDataProvider();
532
+ /**
533
+ * Represents a V4 pool
534
+ */
535
+ var Pool = /*#__PURE__*/function () {
536
+ /**
537
+ * Construct a pool
538
+ * @param currencyA One of the currencys in the pool
539
+ * @param currencyB The other currency in the pool
540
+ * @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool
541
+ * @param tickSpacing The tickSpacing of the pool
542
+ * @param hooks The address of the hook contract
543
+ * @param sqrtRatioX96 The sqrt of the current ratio of amounts of currency1 to currency0
544
+ * @param liquidity The current value of in range liquidity
545
+ * @param tickCurrent The current tick of the pool
546
+ */
547
+ function Pool(currencyA, currencyB, fee, tickSpacing, hooks, sqrtRatioX96, liquidity, tickCurrent, ticks) {
548
+ if (ticks === void 0) {
549
+ ticks = NO_TICK_DATA_PROVIDER_DEFAULT;
550
+ }
551
+ !isAddress(hooks) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Invalid hook address') : invariant(false) : void 0;
552
+ !(Number.isInteger(fee) && (fee === DYNAMIC_FEE_FLAG || fee < 1000000)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'FEE') : invariant(false) : void 0;
553
+ if (fee === DYNAMIC_FEE_FLAG) {
554
+ !(Number(hooks) > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Dynamic fee pool requires a hook') : invariant(false) : void 0;
555
+ }
556
+ var tickCurrentSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent);
557
+ var nextTickSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent + 1);
558
+ !(JSBI.greaterThanOrEqual(JSBI.BigInt(sqrtRatioX96), tickCurrentSqrtRatioX96) && JSBI.lessThanOrEqual(JSBI.BigInt(sqrtRatioX96), nextTickSqrtRatioX96)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PRICE_BOUNDS') : invariant(false) : void 0;
559
+ var _ref = sortsBefore(currencyA, currencyB) ? [currencyA, currencyB] : [currencyB, currencyA];
560
+ this.currency0 = _ref[0];
561
+ this.currency1 = _ref[1];
562
+ this.fee = fee;
563
+ this.sqrtRatioX96 = JSBI.BigInt(sqrtRatioX96);
564
+ this.tickSpacing = tickSpacing;
565
+ this.hooks = hooks;
566
+ this.liquidity = JSBI.BigInt(liquidity);
567
+ this.tickCurrent = tickCurrent;
568
+ this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks, tickSpacing) : ticks;
569
+ this.poolKey = Pool.getPoolKey(this.currency0, this.currency1, this.fee, this.tickSpacing, this.hooks);
570
+ this.poolId = Pool.getPoolId(this.currency0, this.currency1, this.fee, this.tickSpacing, this.hooks);
571
+ }
572
+ Pool.getPoolKey = function getPoolKey(currencyA, currencyB, fee, tickSpacing, hooks) {
573
+ !isAddress(hooks) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Invalid hook address') : invariant(false) : void 0;
574
+ var _ref2 = sortsBefore(currencyA, currencyB) ? [currencyA, currencyB] : [currencyB, currencyA],
575
+ currency0 = _ref2[0],
576
+ currency1 = _ref2[1];
577
+ var currency0Addr = currency0.isNative ? ADDRESS_ZERO : currency0.wrapped.address;
578
+ var currency1Addr = currency1.isNative ? ADDRESS_ZERO : currency1.wrapped.address;
579
+ return {
580
+ currency0: currency0Addr,
581
+ currency1: currency1Addr,
582
+ fee: fee,
583
+ tickSpacing: tickSpacing,
584
+ hooks: hooks
585
+ };
586
+ };
587
+ Pool.getPoolId = function getPoolId(currencyA, currencyB, fee, tickSpacing, hooks) {
588
+ var _ref3 = sortsBefore(currencyA, currencyB) ? [currencyA, currencyB] : [currencyB, currencyA],
589
+ currency0 = _ref3[0],
590
+ currency1 = _ref3[1];
591
+ var currency0Addr = currency0.isNative ? ADDRESS_ZERO : currency0.wrapped.address;
592
+ var currency1Addr = currency1.isNative ? ADDRESS_ZERO : currency1.wrapped.address;
593
+ return keccak256(['bytes'], [defaultAbiCoder.encode(['address', 'address', 'uint24', 'int24', 'address'], [currency0Addr, currency1Addr, fee, tickSpacing, hooks])]);
594
+ }
595
+ /** backwards compatibility with v2/3 sdks */;
596
+ var _proto = Pool.prototype;
597
+ /**
598
+ * Returns true if the currency is either currency0 or currency1
599
+ * @param currency The currency to check
600
+ * @returns True if currency is either currency0 or currency1
601
+ */
602
+ _proto.involvesCurrency = function involvesCurrency(currency) {
603
+ return currency.equals(this.currency0) || currency.equals(this.currency1);
604
+ }
605
+ /** backwards compatibility with v2/3 sdks */;
606
+ _proto.involvesToken = function involvesToken(currency) {
607
+ return this.involvesCurrency(currency);
608
+ }
609
+ /**
610
+ * v4-only involvesToken convenience method, used for mixed route ETH <-> WETH connection only
611
+ * @param currency
612
+ */;
613
+ _proto.v4InvolvesToken = function v4InvolvesToken(currency) {
614
+ return this.involvesCurrency(currency) || currency.wrapped.equals(this.currency0) || currency.wrapped.equals(this.currency1) || currency.wrapped.equals(this.currency0.wrapped) || currency.wrapped.equals(this.currency1.wrapped);
615
+ }
616
+ /**
617
+ * Returns the current mid price of the pool in terms of currency0, i.e. the ratio of currency1 over currency0
618
+ */;
619
+ /**
620
+ * Return the price of the given currency in terms of the other currency in the pool.
621
+ * @param currency The currency to return price of
622
+ * @returns The price of the given currency, in terms of the other.
623
+ */
624
+ _proto.priceOf = function priceOf(currency) {
625
+ !this.involvesCurrency(currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) : void 0;
626
+ return currency.equals(this.currency0) ? this.currency0Price : this.currency1Price;
627
+ }
628
+ /**
629
+ * Returns the chain ID of the currencies in the pool.
630
+ */;
631
+ /** Works only for vanilla hookless v3 pools, otherwise throws an error */
632
+ _proto.getOutputAmount =
633
+ /*#__PURE__*/
634
+ function () {
635
+ var _getOutputAmount = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(inputAmount, sqrtPriceLimitX96) {
636
+ var zeroForOne, _yield$this$swap, outputAmount, sqrtRatioX96, liquidity, tickCurrent, outputCurrency;
637
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
638
+ while (1) switch (_context.prev = _context.next) {
639
+ case 0:
640
+ !this.involvesCurrency(inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) : void 0;
641
+ zeroForOne = inputAmount.currency.equals(this.currency0);
642
+ _context.next = 4;
643
+ return this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96);
644
+ case 4:
645
+ _yield$this$swap = _context.sent;
646
+ outputAmount = _yield$this$swap.amountCalculated;
647
+ sqrtRatioX96 = _yield$this$swap.sqrtRatioX96;
648
+ liquidity = _yield$this$swap.liquidity;
649
+ tickCurrent = _yield$this$swap.tickCurrent;
650
+ outputCurrency = zeroForOne ? this.currency1 : this.currency0;
651
+ return _context.abrupt("return", [CurrencyAmount.fromRawAmount(outputCurrency, JSBI.multiply(outputAmount, NEGATIVE_ONE)), new Pool(this.currency0, this.currency1, this.fee, this.tickSpacing, this.hooks, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]);
652
+ case 11:
653
+ case "end":
654
+ return _context.stop();
655
+ }
656
+ }, _callee, this);
657
+ }));
658
+ function getOutputAmount(_x, _x2) {
659
+ return _getOutputAmount.apply(this, arguments);
660
+ }
661
+ return getOutputAmount;
662
+ }()
663
+ /**
664
+ * Given a desired output amount of a currency, return the computed input amount and a pool with state updated after the trade
665
+ * Works only for vanilla hookless v3 pools, otherwise throws an error
666
+ * @param outputAmount the output amount for which to quote the input amount
667
+ * @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
668
+ * @returns The input amount and the pool with updated state
669
+ */
670
+ ;
671
+ _proto.getInputAmount =
672
+ /*#__PURE__*/
673
+ function () {
674
+ var _getInputAmount = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(outputAmount, sqrtPriceLimitX96) {
675
+ var zeroForOne, _yield$this$swap2, inputAmount, sqrtRatioX96, liquidity, tickCurrent, inputCurrency;
676
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
677
+ while (1) switch (_context2.prev = _context2.next) {
678
+ case 0:
679
+ !this.involvesCurrency(outputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) : void 0;
680
+ zeroForOne = outputAmount.currency.equals(this.currency1);
681
+ _context2.next = 4;
682
+ return this.swap(zeroForOne, JSBI.multiply(outputAmount.quotient, NEGATIVE_ONE), sqrtPriceLimitX96);
683
+ case 4:
684
+ _yield$this$swap2 = _context2.sent;
685
+ inputAmount = _yield$this$swap2.amountCalculated;
686
+ sqrtRatioX96 = _yield$this$swap2.sqrtRatioX96;
687
+ liquidity = _yield$this$swap2.liquidity;
688
+ tickCurrent = _yield$this$swap2.tickCurrent;
689
+ inputCurrency = zeroForOne ? this.currency0 : this.currency1;
690
+ return _context2.abrupt("return", [CurrencyAmount.fromRawAmount(inputCurrency, inputAmount), new Pool(this.currency0, this.currency1, this.fee, this.tickSpacing, this.hooks, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]);
691
+ case 11:
692
+ case "end":
693
+ return _context2.stop();
694
+ }
695
+ }, _callee2, this);
696
+ }));
697
+ function getInputAmount(_x3, _x4) {
698
+ return _getInputAmount.apply(this, arguments);
699
+ }
700
+ return getInputAmount;
701
+ }()
702
+ /**
703
+ * Executes a swap
704
+ * @param zeroForOne Whether the amount in is token0 or token1
705
+ * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
706
+ * @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
707
+ * @returns amountCalculated
708
+ * @returns sqrtRatioX96
709
+ * @returns liquidity
710
+ * @returns tickCurrent
711
+ */
712
+ ;
713
+ _proto.swap =
714
+ /*#__PURE__*/
715
+ function () {
716
+ var _swap = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(zeroForOne, amountSpecified, sqrtPriceLimitX96) {
717
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
718
+ while (1) switch (_context3.prev = _context3.next) {
719
+ case 0:
720
+ if (this.hookImpactsSwap()) {
721
+ _context3.next = 4;
722
+ break;
723
+ }
724
+ return _context3.abrupt("return", v3Swap(JSBI.BigInt(this.fee), this.sqrtRatioX96, this.tickCurrent, this.liquidity, this.tickSpacing, this.tickDataProvider, zeroForOne, amountSpecified, sqrtPriceLimitX96));
725
+ case 4:
726
+ throw new Error('Unsupported hook');
727
+ case 5:
728
+ case "end":
729
+ return _context3.stop();
730
+ }
731
+ }, _callee3, this);
732
+ }));
733
+ function swap(_x5, _x6, _x7) {
734
+ return _swap.apply(this, arguments);
735
+ }
736
+ return swap;
737
+ }();
738
+ _proto.hookImpactsSwap = function hookImpactsSwap() {
739
+ // could use this function to clear certain hooks that may have swap Permissions, but we know they don't interfere
740
+ // in the swap outcome
741
+ return Hook.hasSwapPermissions(this.hooks);
742
+ };
743
+ return _createClass(Pool, [{
744
+ key: "token0",
745
+ get: function get() {
746
+ return this.currency0;
747
+ }
748
+ }, {
749
+ key: "token1",
750
+ get: function get() {
751
+ return this.currency1;
752
+ }
753
+ }, {
754
+ key: "currency0Price",
755
+ get: function get() {
756
+ var _this$_currency0Price;
757
+ return (_this$_currency0Price = this._currency0Price) != null ? _this$_currency0Price : this._currency0Price = new Price(this.currency0, this.currency1, Q192, JSBI.multiply(this.sqrtRatioX96, this.sqrtRatioX96));
758
+ }
759
+ /** backwards compatibility with v2/3 sdks */
760
+ }, {
761
+ key: "token0Price",
762
+ get: function get() {
763
+ return this.currency0Price;
764
+ }
765
+ /**
766
+ * Returns the current mid price of the pool in terms of currency1, i.e. the ratio of currency0 over currency1
767
+ */
768
+ }, {
769
+ key: "currency1Price",
770
+ get: function get() {
771
+ var _this$_currency1Price;
772
+ return (_this$_currency1Price = this._currency1Price) != null ? _this$_currency1Price : this._currency1Price = new Price(this.currency1, this.currency0, JSBI.multiply(this.sqrtRatioX96, this.sqrtRatioX96), Q192);
773
+ }
774
+ /** backwards compatibility with v2/3 sdks */
775
+ }, {
776
+ key: "token1Price",
777
+ get: function get() {
778
+ return this.currency1Price;
779
+ }
780
+ }, {
781
+ key: "chainId",
782
+ get: function get() {
783
+ return this.currency0.chainId;
784
+ }
785
+ }]);
786
+ }();
787
+
788
+ function amountWithPathCurrency(amount, pool) {
789
+ return CurrencyAmount.fromFractionalAmount(getPathCurrency(amount.currency, pool), amount.numerator, amount.denominator);
790
+ }
791
+ function getPathCurrency(currency, pool) {
792
+ if (pool.involvesCurrency(currency)) {
793
+ return currency;
794
+ } else if (pool.involvesCurrency(currency.wrapped)) {
795
+ return currency.wrapped;
796
+ } else if (pool.currency0.wrapped.equals(currency)) {
797
+ return pool.currency0;
798
+ } else if (pool.currency1.wrapped.equals(currency)) {
799
+ return pool.currency1;
800
+ } else {
801
+ throw new Error("Expected currency " + currency.symbol + " to be either " + pool.currency0.symbol + " or " + pool.currency1.symbol);
802
+ }
803
+ }
804
+
805
+ /**
806
+ * Represents a list of pools through which a swap can occur
807
+ * @template TInput The input currency
808
+ * @template TOutput The output currency
809
+ */
810
+ var Route = /*#__PURE__*/function () {
811
+ /**
812
+ * Creates an instance of route.
813
+ * @param pools An array of `Pool` objects, ordered by the route the swap will take
814
+ * @param input The input currency
815
+ * @param output The output currency
816
+ */
817
+ function Route(pools, input, output) {
818
+ this._midPrice = null;
819
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
820
+ var chainId = pools[0].chainId;
821
+ var allOnSameChain = pools.every(function (pool) {
822
+ return pool.chainId === chainId;
823
+ });
824
+ !allOnSameChain ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0;
825
+ /**
826
+ * function throws if pools do not involve the input and output currency or the native/wrapped equivalent
827
+ **/
828
+ this.pathInput = getPathCurrency(input, pools[0]);
829
+ this.pathOutput = getPathCurrency(output, pools[pools.length - 1]);
830
+ /**
831
+ * Normalizes currency0-currency1 order and selects the next currency/fee step to add to the path
832
+ * */
833
+ var currencyPath = [this.pathInput];
834
+ for (var _iterator = _createForOfIteratorHelperLoose(pools.entries()), _step; !(_step = _iterator()).done;) {
835
+ var _step$value = _step.value,
836
+ i = _step$value[0],
837
+ pool = _step$value[1];
838
+ var currentInputCurrency = currencyPath[i];
839
+ !(currentInputCurrency.equals(pool.currency0) || currentInputCurrency.equals(pool.currency1)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PATH') : invariant(false) : void 0;
840
+ var nextCurrency = currentInputCurrency.equals(pool.currency0) ? pool.currency1 : pool.currency0;
841
+ currencyPath.push(nextCurrency);
842
+ }
843
+ this.pools = pools;
844
+ this.currencyPath = currencyPath;
845
+ this.input = input;
846
+ this.output = output != null ? output : currencyPath[currencyPath.length - 1];
847
+ }
848
+ return _createClass(Route, [{
849
+ key: "chainId",
850
+ get: function get() {
851
+ return this.pools[0].chainId;
852
+ }
853
+ /**
854
+ * Returns the mid price of the route
855
+ */
856
+ }, {
857
+ key: "midPrice",
858
+ get: function get() {
859
+ if (this._midPrice !== null) return this._midPrice;
860
+ var price = this.pools.slice(1).reduce(function (_ref, pool) {
861
+ var nextInput = _ref.nextInput,
862
+ price = _ref.price;
863
+ return nextInput.equals(pool.currency0) ? {
864
+ nextInput: pool.currency1,
865
+ price: price.multiply(pool.currency0Price)
866
+ } : {
867
+ nextInput: pool.currency0,
868
+ price: price.multiply(pool.currency1Price)
869
+ };
870
+ }, this.pools[0].currency0.equals(this.input) ? {
871
+ nextInput: this.pools[0].currency1,
872
+ price: this.pools[0].currency0Price
873
+ } : {
874
+ nextInput: this.pools[0].currency0,
875
+ price: this.pools[0].currency1Price
876
+ }).price;
877
+ return this._midPrice = new Price(this.input, this.output, price.denominator, price.numerator);
878
+ }
879
+ }]);
880
+ }();
881
+
882
+ /**
883
+ * Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them
884
+ * @template TInput The input currency, either Ether or an ERC-20
885
+ * @template TOutput The output currency, either Ether or an ERC-20
886
+ * @template TTradeType The trade type, either exact input or exact output
887
+ * @param a The first trade to compare
888
+ * @param b The second trade to compare
889
+ * @returns A sorted ordering for two neighboring elements in a trade array
890
+ */
891
+ function tradeComparator(a, b) {
892
+ // must have same input and output currency for comparison
893
+ !a.inputAmount.currency.equals(b.inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY') : invariant(false) : void 0;
894
+ !a.outputAmount.currency.equals(b.outputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY') : invariant(false) : void 0;
895
+ if (a.outputAmount.equalTo(b.outputAmount)) {
896
+ if (a.inputAmount.equalTo(b.inputAmount)) {
897
+ // consider the number of hops since each hop costs gas
898
+ var aHops = a.swaps.reduce(function (total, cur) {
899
+ return total + cur.route.currencyPath.length;
900
+ }, 0);
901
+ var bHops = b.swaps.reduce(function (total, cur) {
902
+ return total + cur.route.currencyPath.length;
903
+ }, 0);
904
+ return aHops - bHops;
905
+ }
906
+ // trade A requires less input than trade B, so A should come first
907
+ if (a.inputAmount.lessThan(b.inputAmount)) {
908
+ return -1;
909
+ } else {
910
+ return 1;
911
+ }
912
+ } else {
913
+ // tradeA has less output than trade B, so should come second
914
+ if (a.outputAmount.lessThan(b.outputAmount)) {
915
+ return 1;
916
+ } else {
917
+ return -1;
918
+ }
919
+ }
920
+ }
921
+ /**
922
+ * Represents a trade executed against a set of routes where some percentage of the input is
923
+ * split across each route.
924
+ *
925
+ * Each route has its own set of pools. Pools can not be re-used across routes.
926
+ *
927
+ * Does not account for slippage, i.e., changes in price environment that can occur between
928
+ * the time the trade is submitted and when it is executed.
929
+ * @template TInput The input currency, either Ether or an ERC-20
930
+ * @template TOutput The output currency, either Ether or an ERC-20
931
+ * @template TTradeType The trade type, either exact input or exact output
932
+ */
933
+ var Trade = /*#__PURE__*/function () {
934
+ /**
935
+ * Construct a trade by passing in the pre-computed property values
936
+ * @param routes The routes through which the trade occurs
937
+ * @param tradeType The type of trade, exact input or exact output
938
+ */
939
+ function Trade(_ref) {
940
+ var routes = _ref.routes,
941
+ tradeType = _ref.tradeType;
942
+ var inputCurrency = routes[0].inputAmount.currency;
943
+ var outputCurrency = routes[0].outputAmount.currency;
944
+ !routes.every(function (_ref2) {
945
+ var route = _ref2.route;
946
+ return inputCurrency.equals(route.input);
947
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY_MATCH') : invariant(false) : void 0;
948
+ !routes.every(function (_ref3) {
949
+ var route = _ref3.route;
950
+ return outputCurrency.equals(route.output);
951
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY_MATCH') : invariant(false) : void 0;
952
+ var numPools = routes.map(function (_ref4) {
953
+ var route = _ref4.route;
954
+ return route.pools.length;
955
+ }).reduce(function (total, cur) {
956
+ return total + cur;
957
+ }, 0);
958
+ var poolIDSet = new Set();
959
+ for (var _iterator = _createForOfIteratorHelperLoose(routes), _step; !(_step = _iterator()).done;) {
960
+ var route = _step.value.route;
961
+ for (var _iterator2 = _createForOfIteratorHelperLoose(route.pools), _step2; !(_step2 = _iterator2()).done;) {
962
+ var pool = _step2.value;
963
+ poolIDSet.add(Pool.getPoolId(pool.currency0, pool.currency1, pool.fee, pool.tickSpacing, pool.hooks));
964
+ }
965
+ }
966
+ !(numPools === poolIDSet.size) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS_DUPLICATED') : invariant(false) : void 0;
967
+ this.swaps = routes;
968
+ this.tradeType = tradeType;
969
+ }
970
+ /**
971
+ * @deprecated Deprecated in favor of 'swaps' property. If the trade consists of multiple routes
972
+ * this will return an error.
973
+ *
974
+ * When the trade consists of just a single route, this returns the route of the trade,
975
+ * i.e. which pools the trade goes through.
976
+ */
977
+ /**
978
+ * Constructs an exact in trade with the given amount in and route
979
+ * @template TInput The input currency, either Ether or an ERC-20
980
+ * @template TOutput The output currency, either Ether or an ERC-20
981
+ * @param route The route of the exact in trade
982
+ * @param amountIn The amount being passed in
983
+ * @returns The exact in trade
984
+ */
985
+ Trade.exactIn =
986
+ /*#__PURE__*/
987
+ function () {
988
+ var _exactIn = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(route, amountIn) {
989
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
990
+ while (1) switch (_context.prev = _context.next) {
991
+ case 0:
992
+ return _context.abrupt("return", Trade.fromRoute(route, amountIn, TradeType.EXACT_INPUT));
993
+ case 1:
994
+ case "end":
995
+ return _context.stop();
996
+ }
997
+ }, _callee);
998
+ }));
999
+ function exactIn(_x, _x2) {
1000
+ return _exactIn.apply(this, arguments);
1001
+ }
1002
+ return exactIn;
1003
+ }()
1004
+ /**
1005
+ * Constructs an exact out trade with the given amount out and route
1006
+ * @template TInput The input currency, either Ether or an ERC-20
1007
+ * @template TOutput The output currency, either Ether or an ERC-20
1008
+ * @param route The route of the exact out trade
1009
+ * @param amountOut The amount returned by the trade
1010
+ * @returns The exact out trade
1011
+ */
1012
+ ;
1013
+ Trade.exactOut =
1014
+ /*#__PURE__*/
1015
+ function () {
1016
+ var _exactOut = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(route, amountOut) {
1017
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1018
+ while (1) switch (_context2.prev = _context2.next) {
1019
+ case 0:
1020
+ return _context2.abrupt("return", Trade.fromRoute(route, amountOut, TradeType.EXACT_OUTPUT));
1021
+ case 1:
1022
+ case "end":
1023
+ return _context2.stop();
1024
+ }
1025
+ }, _callee2);
1026
+ }));
1027
+ function exactOut(_x3, _x4) {
1028
+ return _exactOut.apply(this, arguments);
1029
+ }
1030
+ return exactOut;
1031
+ }()
1032
+ /**
1033
+ * Constructs a trade by simulating swaps through the given route
1034
+ * @template TInput The input currency, either Ether or an ERC-20.
1035
+ * @template TOutput The output currency, either Ether or an ERC-20.
1036
+ * @template TTradeType The type of the trade, either exact in or exact out.
1037
+ * @param route route to swap through
1038
+ * @param amount the amount specified, either input or output, depending on tradeType
1039
+ * @param tradeType whether the trade is an exact input or exact output swap
1040
+ * @returns The route
1041
+ */
1042
+ ;
1043
+ Trade.fromRoute =
1044
+ /*#__PURE__*/
1045
+ function () {
1046
+ var _fromRoute = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(route, amount, tradeType) {
1047
+ var inputAmount, outputAmount, tokenAmount, i, pool, _yield$pool$getOutput, _tokenAmount, _i, _pool, _yield$_pool$getInput;
1048
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1049
+ while (1) switch (_context3.prev = _context3.next) {
1050
+ case 0:
1051
+ if (!(tradeType === TradeType.EXACT_INPUT)) {
1052
+ _context3.next = 17;
1053
+ break;
1054
+ }
1055
+ !amount.currency.equals(route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
1056
+ // Account for trades that wrap/unwrap as a first step
1057
+ tokenAmount = amountWithPathCurrency(amount, route.pools[0]);
1058
+ i = 0;
1059
+ case 4:
1060
+ if (!(i < route.pools.length)) {
1061
+ _context3.next = 13;
1062
+ break;
1063
+ }
1064
+ pool = route.pools[i];
1065
+ _context3.next = 8;
1066
+ return pool.getOutputAmount(tokenAmount);
1067
+ case 8:
1068
+ _yield$pool$getOutput = _context3.sent;
1069
+ tokenAmount = _yield$pool$getOutput[0];
1070
+ case 10:
1071
+ i++;
1072
+ _context3.next = 4;
1073
+ break;
1074
+ case 13:
1075
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
1076
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, tokenAmount.numerator, tokenAmount.denominator);
1077
+ _context3.next = 31;
1078
+ break;
1079
+ case 17:
1080
+ !amount.currency.equals(route.output) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
1081
+ // Account for trades that wrap/unwrap as a last step
1082
+ _tokenAmount = amountWithPathCurrency(amount, route.pools[route.pools.length - 1]);
1083
+ _i = route.pools.length - 1;
1084
+ case 20:
1085
+ if (!(_i >= 0)) {
1086
+ _context3.next = 29;
1087
+ break;
1088
+ }
1089
+ _pool = route.pools[_i];
1090
+ _context3.next = 24;
1091
+ return _pool.getInputAmount(_tokenAmount);
1092
+ case 24:
1093
+ _yield$_pool$getInput = _context3.sent;
1094
+ _tokenAmount = _yield$_pool$getInput[0];
1095
+ case 26:
1096
+ _i--;
1097
+ _context3.next = 20;
1098
+ break;
1099
+ case 29:
1100
+ inputAmount = CurrencyAmount.fromFractionalAmount(route.input, _tokenAmount.numerator, _tokenAmount.denominator);
1101
+ outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
1102
+ case 31:
1103
+ return _context3.abrupt("return", new Trade({
1104
+ routes: [{
1105
+ inputAmount: inputAmount,
1106
+ outputAmount: outputAmount,
1107
+ route: route
1108
+ }],
1109
+ tradeType: tradeType
1110
+ }));
1111
+ case 32:
1112
+ case "end":
1113
+ return _context3.stop();
1114
+ }
1115
+ }, _callee3);
1116
+ }));
1117
+ function fromRoute(_x5, _x6, _x7) {
1118
+ return _fromRoute.apply(this, arguments);
1119
+ }
1120
+ return fromRoute;
1121
+ }()
1122
+ /**
1123
+ * Constructs a trade from routes by simulating swaps
1124
+ *
1125
+ * @template TInput The input currency, either Ether or an ERC-20.
1126
+ * @template TOutput The output currency, either Ether or an ERC-20.
1127
+ * @template TTradeType The type of the trade, either exact in or exact out.
1128
+ * @param routes the routes to swap through and how much of the amount should be routed through each
1129
+ * @param tradeType whether the trade is an exact input or exact output swap
1130
+ * @returns The trade
1131
+ */
1132
+ ;
1133
+ Trade.fromRoutes =
1134
+ /*#__PURE__*/
1135
+ function () {
1136
+ var _fromRoutes = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(routes, tradeType) {
1137
+ var swaps;
1138
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1139
+ while (1) switch (_context5.prev = _context5.next) {
1140
+ case 0:
1141
+ _context5.next = 2;
1142
+ return Promise.all(routes.map(/*#__PURE__*/function () {
1143
+ var _ref6 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref5) {
1144
+ var amount, route, trade;
1145
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1146
+ while (1) switch (_context4.prev = _context4.next) {
1147
+ case 0:
1148
+ amount = _ref5.amount, route = _ref5.route;
1149
+ _context4.next = 3;
1150
+ return Trade.fromRoute(route, amount, tradeType);
1151
+ case 3:
1152
+ trade = _context4.sent;
1153
+ return _context4.abrupt("return", trade.swaps[0]);
1154
+ case 5:
1155
+ case "end":
1156
+ return _context4.stop();
1157
+ }
1158
+ }, _callee4);
1159
+ }));
1160
+ return function (_x10) {
1161
+ return _ref6.apply(this, arguments);
1162
+ };
1163
+ }()));
1164
+ case 2:
1165
+ swaps = _context5.sent;
1166
+ return _context5.abrupt("return", new Trade({
1167
+ routes: swaps,
1168
+ tradeType: tradeType
1169
+ }));
1170
+ case 4:
1171
+ case "end":
1172
+ return _context5.stop();
1173
+ }
1174
+ }, _callee5);
1175
+ }));
1176
+ function fromRoutes(_x8, _x9) {
1177
+ return _fromRoutes.apply(this, arguments);
1178
+ }
1179
+ return fromRoutes;
1180
+ }()
1181
+ /**
1182
+ * Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade
1183
+ * elsewhere and do not have any tick data
1184
+ * @template TInput The input currency, either Ether or an ERC-20
1185
+ * @template TOutput The output currency, either Ether or an ERC-20
1186
+ * @template TTradeType The type of the trade, either exact in or exact out
1187
+ * @param constructorArguments The arguments passed to the trade constructor
1188
+ * @returns The unchecked trade
1189
+ */
1190
+ ;
1191
+ Trade.createUncheckedTrade = function createUncheckedTrade(constructorArguments) {
1192
+ return new Trade(_extends({}, constructorArguments, {
1193
+ routes: [{
1194
+ inputAmount: constructorArguments.inputAmount,
1195
+ outputAmount: constructorArguments.outputAmount,
1196
+ route: constructorArguments.route
1197
+ }]
1198
+ }));
1199
+ }
1200
+ /**
1201
+ * Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade
1202
+ * elsewhere and do not have any tick data
1203
+ * @template TInput The input currency, either Ether or an ERC-20
1204
+ * @template TOutput The output currency, either Ether or an ERC-20
1205
+ * @template TTradeType The type of the trade, either exact in or exact out
1206
+ * @param constructorArguments The arguments passed to the trade constructor
1207
+ * @returns The unchecked trade
1208
+ */;
1209
+ Trade.createUncheckedTradeWithMultipleRoutes = function createUncheckedTradeWithMultipleRoutes(constructorArguments) {
1210
+ return new Trade(constructorArguments);
1211
+ }
1212
+ /**
1213
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
1214
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
1215
+ * @returns The amount out
1216
+ */;
1217
+ var _proto = Trade.prototype;
1218
+ _proto.minimumAmountOut = function minimumAmountOut(slippageTolerance, amountOut) {
1219
+ if (amountOut === void 0) {
1220
+ amountOut = this.outputAmount;
1221
+ }
1222
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
1223
+ if (this.tradeType === TradeType.EXACT_OUTPUT) {
1224
+ return amountOut;
1225
+ } else {
1226
+ var slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(amountOut.quotient).quotient;
1227
+ return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut);
1228
+ }
1229
+ }
1230
+ /**
1231
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
1232
+ * @param slippageTolerance The tolerance of unfavorable slippage from the execution price of this trade
1233
+ * @returns The amount in
1234
+ */;
1235
+ _proto.maximumAmountIn = function maximumAmountIn(slippageTolerance, amountIn) {
1236
+ if (amountIn === void 0) {
1237
+ amountIn = this.inputAmount;
1238
+ }
1239
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
1240
+ if (this.tradeType === TradeType.EXACT_INPUT) {
1241
+ return amountIn;
1242
+ } else {
1243
+ var slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient;
1244
+ return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn);
1245
+ }
1246
+ }
1247
+ /**
1248
+ * Return the execution price after accounting for slippage tolerance
1249
+ * @param slippageTolerance the allowed tolerated slippage
1250
+ * @returns The execution price
1251
+ */;
1252
+ _proto.worstExecutionPrice = function worstExecutionPrice(slippageTolerance) {
1253
+ return new Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
1254
+ }
1255
+ /**
1256
+ * Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input currency
1257
+ * amount to an output currency, making at most `maxHops` hops.
1258
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
1259
+ * the amount in among multiple routes.
1260
+ * @param pools the pools to consider in finding the best trade
1261
+ * @param nextAmountIn exact amount of input currency to spend
1262
+ * @param currencyOut the desired currency out
1263
+ * @param maxNumResults maximum number of results to return
1264
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1265
+ * @param currentPools used in recursion; the current list of pools
1266
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
1267
+ * @param bestTrades used in recursion; the current list of best trades
1268
+ * @returns The exact in trade
1269
+ */;
1270
+ Trade.bestTradeExactIn =
1271
+ /*#__PURE__*/
1272
+ function () {
1273
+ var _bestTradeExactIn = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(pools, currencyAmountIn, currencyOut, _temp,
1274
+ // used in recursion.
1275
+ currentPools, nextAmountIn, bestTrades) {
1276
+ var _ref7, _ref7$maxNumResults, maxNumResults, _ref7$maxHops, maxHops, amountIn, i, pool, amountOut, _yield$pool$getOutput2, poolsExcludingThisPool;
1277
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1278
+ while (1) switch (_context6.prev = _context6.next) {
1279
+ case 0:
1280
+ _ref7 = _temp === void 0 ? {} : _temp, _ref7$maxNumResults = _ref7.maxNumResults, maxNumResults = _ref7$maxNumResults === void 0 ? 3 : _ref7$maxNumResults, _ref7$maxHops = _ref7.maxHops, maxHops = _ref7$maxHops === void 0 ? 3 : _ref7$maxHops;
1281
+ if (currentPools === void 0) {
1282
+ currentPools = [];
1283
+ }
1284
+ if (nextAmountIn === void 0) {
1285
+ nextAmountIn = currencyAmountIn;
1286
+ }
1287
+ if (bestTrades === void 0) {
1288
+ bestTrades = [];
1289
+ }
1290
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
1291
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
1292
+ !(currencyAmountIn === nextAmountIn || currentPools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
1293
+ amountIn = nextAmountIn;
1294
+ i = 0;
1295
+ case 9:
1296
+ if (!(i < pools.length)) {
1297
+ _context6.next = 45;
1298
+ break;
1299
+ }
1300
+ pool = pools[i]; // pool irrelevant
1301
+ if (!(!pool.currency0.equals(amountIn.currency) && !pool.currency1.equals(amountIn.currency))) {
1302
+ _context6.next = 13;
1303
+ break;
1304
+ }
1305
+ return _context6.abrupt("continue", 42);
1306
+ case 13:
1307
+ amountOut = void 0;
1308
+ _context6.prev = 14;
1309
+ _context6.next = 18;
1310
+ return pool.getOutputAmount(amountIn);
1311
+ case 18:
1312
+ _yield$pool$getOutput2 = _context6.sent;
1313
+ amountOut = _yield$pool$getOutput2[0];
1314
+ _context6.next = 27;
1315
+ break;
1316
+ case 22:
1317
+ _context6.prev = 22;
1318
+ _context6.t0 = _context6["catch"](14);
1319
+ if (!_context6.t0.isInsufficientInputAmountError) {
1320
+ _context6.next = 26;
1321
+ break;
1322
+ }
1323
+ return _context6.abrupt("continue", 42);
1324
+ case 26:
1325
+ throw _context6.t0;
1326
+ case 27:
1327
+ if (!amountOut.currency.equals(currencyOut)) {
1328
+ _context6.next = 38;
1329
+ break;
1330
+ }
1331
+ _context6.t1 = sortedInsert;
1332
+ _context6.t2 = bestTrades;
1333
+ _context6.next = 32;
1334
+ return Trade.fromRoute(new Route([].concat(currentPools, [pool]), currencyAmountIn.currency, currencyOut), currencyAmountIn, TradeType.EXACT_INPUT);
1335
+ case 32:
1336
+ _context6.t3 = _context6.sent;
1337
+ _context6.t4 = maxNumResults;
1338
+ _context6.t5 = tradeComparator;
1339
+ (0, _context6.t1)(_context6.t2, _context6.t3, _context6.t4, _context6.t5);
1340
+ _context6.next = 42;
1341
+ break;
1342
+ case 38:
1343
+ if (!(maxHops > 1 && pools.length > 1)) {
1344
+ _context6.next = 42;
1345
+ break;
1346
+ }
1347
+ poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length)); // otherwise, consider all the other paths that lead from this currency as long as we have not exceeded maxHops
1348
+ _context6.next = 42;
1349
+ return Trade.bestTradeExactIn(poolsExcludingThisPool, currencyAmountIn, currencyOut, {
1350
+ maxNumResults: maxNumResults,
1351
+ maxHops: maxHops - 1
1352
+ }, [].concat(currentPools, [pool]), amountOut, bestTrades);
1353
+ case 42:
1354
+ i++;
1355
+ _context6.next = 9;
1356
+ break;
1357
+ case 45:
1358
+ return _context6.abrupt("return", bestTrades);
1359
+ case 46:
1360
+ case "end":
1361
+ return _context6.stop();
1362
+ }
1363
+ }, _callee6, null, [[14, 22]]);
1364
+ }));
1365
+ function bestTradeExactIn(_x11, _x12, _x13, _x14, _x15, _x16, _x17) {
1366
+ return _bestTradeExactIn.apply(this, arguments);
1367
+ }
1368
+ return bestTradeExactIn;
1369
+ }()
1370
+ /**
1371
+ * similar to the above method but instead targets a fixed output amount
1372
+ * given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input currency
1373
+ * to an output currency amount, making at most `maxHops` hops
1374
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
1375
+ * the amount in among multiple routes.
1376
+ * @param pools the pools to consider in finding the best trade
1377
+ * @param currencyIn the currency to spend
1378
+ * @param currencyAmountOut the desired currency amount out
1379
+ * @param nextAmountOut the exact amount of currency out
1380
+ * @param maxNumResults maximum number of results to return
1381
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pool
1382
+ * @param currentPools used in recursion; the current list of pools
1383
+ * @param bestTrades used in recursion; the current list of best trades
1384
+ * @returns The exact out trade
1385
+ */
1386
+ ;
1387
+ Trade.bestTradeExactOut =
1388
+ /*#__PURE__*/
1389
+ function () {
1390
+ var _bestTradeExactOut = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(pools, currencyIn, currencyAmountOut, _temp2,
1391
+ // used in recursion.
1392
+ currentPools, nextAmountOut, bestTrades) {
1393
+ var _ref8, _ref8$maxNumResults, maxNumResults, _ref8$maxHops, maxHops, amountOut, i, pool, amountIn, _yield$pool$getInputA, poolsExcludingThisPool;
1394
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1395
+ while (1) switch (_context7.prev = _context7.next) {
1396
+ case 0:
1397
+ _ref8 = _temp2 === void 0 ? {} : _temp2, _ref8$maxNumResults = _ref8.maxNumResults, maxNumResults = _ref8$maxNumResults === void 0 ? 3 : _ref8$maxNumResults, _ref8$maxHops = _ref8.maxHops, maxHops = _ref8$maxHops === void 0 ? 3 : _ref8$maxHops;
1398
+ if (currentPools === void 0) {
1399
+ currentPools = [];
1400
+ }
1401
+ if (nextAmountOut === void 0) {
1402
+ nextAmountOut = currencyAmountOut;
1403
+ }
1404
+ if (bestTrades === void 0) {
1405
+ bestTrades = [];
1406
+ }
1407
+ !(pools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'POOLS') : invariant(false) : void 0;
1408
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
1409
+ !(currencyAmountOut === nextAmountOut || currentPools.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
1410
+ amountOut = nextAmountOut;
1411
+ i = 0;
1412
+ case 9:
1413
+ if (!(i < pools.length)) {
1414
+ _context7.next = 45;
1415
+ break;
1416
+ }
1417
+ pool = pools[i]; // pool irrelevant
1418
+ if (!(!pool.currency0.equals(amountOut.currency) && !pool.currency1.equals(amountOut.currency))) {
1419
+ _context7.next = 13;
1420
+ break;
1421
+ }
1422
+ return _context7.abrupt("continue", 42);
1423
+ case 13:
1424
+ amountIn = void 0;
1425
+ _context7.prev = 14;
1426
+ _context7.next = 18;
1427
+ return pool.getInputAmount(amountOut);
1428
+ case 18:
1429
+ _yield$pool$getInputA = _context7.sent;
1430
+ amountIn = _yield$pool$getInputA[0];
1431
+ _context7.next = 27;
1432
+ break;
1433
+ case 22:
1434
+ _context7.prev = 22;
1435
+ _context7.t0 = _context7["catch"](14);
1436
+ if (!_context7.t0.isInsufficientReservesError) {
1437
+ _context7.next = 26;
1438
+ break;
1439
+ }
1440
+ return _context7.abrupt("continue", 42);
1441
+ case 26:
1442
+ throw _context7.t0;
1443
+ case 27:
1444
+ if (!amountIn.currency.equals(currencyIn)) {
1445
+ _context7.next = 38;
1446
+ break;
1447
+ }
1448
+ _context7.t1 = sortedInsert;
1449
+ _context7.t2 = bestTrades;
1450
+ _context7.next = 32;
1451
+ return Trade.fromRoute(new Route([pool].concat(currentPools), currencyIn, currencyAmountOut.currency), currencyAmountOut, TradeType.EXACT_OUTPUT);
1452
+ case 32:
1453
+ _context7.t3 = _context7.sent;
1454
+ _context7.t4 = maxNumResults;
1455
+ _context7.t5 = tradeComparator;
1456
+ (0, _context7.t1)(_context7.t2, _context7.t3, _context7.t4, _context7.t5);
1457
+ _context7.next = 42;
1458
+ break;
1459
+ case 38:
1460
+ if (!(maxHops > 1 && pools.length > 1)) {
1461
+ _context7.next = 42;
1462
+ break;
1463
+ }
1464
+ poolsExcludingThisPool = pools.slice(0, i).concat(pools.slice(i + 1, pools.length)); // otherwise, consider all the other paths that arrive at this currency as long as we have not exceeded maxHops
1465
+ _context7.next = 42;
1466
+ return Trade.bestTradeExactOut(poolsExcludingThisPool, currencyIn, currencyAmountOut, {
1467
+ maxNumResults: maxNumResults,
1468
+ maxHops: maxHops - 1
1469
+ }, [pool].concat(currentPools), amountIn, bestTrades);
1470
+ case 42:
1471
+ i++;
1472
+ _context7.next = 9;
1473
+ break;
1474
+ case 45:
1475
+ return _context7.abrupt("return", bestTrades);
1476
+ case 46:
1477
+ case "end":
1478
+ return _context7.stop();
1479
+ }
1480
+ }, _callee7, null, [[14, 22]]);
1481
+ }));
1482
+ function bestTradeExactOut(_x18, _x19, _x20, _x21, _x22, _x23, _x24) {
1483
+ return _bestTradeExactOut.apply(this, arguments);
1484
+ }
1485
+ return bestTradeExactOut;
1486
+ }();
1487
+ return _createClass(Trade, [{
1488
+ key: "route",
1489
+ get: function get() {
1490
+ !(this.swaps.length === 1) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MULTIPLE_ROUTES') : invariant(false) : void 0;
1491
+ return this.swaps[0].route;
1492
+ }
1493
+ /**
1494
+ * The input amount for the trade assuming no slippage.
1495
+ */
1496
+ }, {
1497
+ key: "inputAmount",
1498
+ get: function get() {
1499
+ if (this._inputAmount) {
1500
+ return this._inputAmount;
1501
+ }
1502
+ var inputCurrency = this.swaps[0].inputAmount.currency;
1503
+ var totalInputFromRoutes = this.swaps.map(function (_ref9) {
1504
+ var inputAmount = _ref9.inputAmount;
1505
+ return inputAmount;
1506
+ }).reduce(function (total, cur) {
1507
+ return total.add(cur);
1508
+ }, CurrencyAmount.fromRawAmount(inputCurrency, 0));
1509
+ this._inputAmount = totalInputFromRoutes;
1510
+ return this._inputAmount;
1511
+ }
1512
+ /**
1513
+ * The output amount for the trade assuming no slippage.
1514
+ */
1515
+ }, {
1516
+ key: "outputAmount",
1517
+ get: function get() {
1518
+ if (this._outputAmount) {
1519
+ return this._outputAmount;
1520
+ }
1521
+ var outputCurrency = this.swaps[0].outputAmount.currency;
1522
+ var totalOutputFromRoutes = this.swaps.map(function (_ref10) {
1523
+ var outputAmount = _ref10.outputAmount;
1524
+ return outputAmount;
1525
+ }).reduce(function (total, cur) {
1526
+ return total.add(cur);
1527
+ }, CurrencyAmount.fromRawAmount(outputCurrency, 0));
1528
+ this._outputAmount = totalOutputFromRoutes;
1529
+ return this._outputAmount;
1530
+ }
1531
+ /**
1532
+ * The price expressed in terms of output amount/input amount.
1533
+ */
1534
+ }, {
1535
+ key: "executionPrice",
1536
+ get: function get() {
1537
+ var _this$_executionPrice;
1538
+ return (_this$_executionPrice = this._executionPrice) != null ? _this$_executionPrice : this._executionPrice = new Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
1539
+ }
1540
+ /**
1541
+ * Returns the percent difference between the route's mid price and the price impact
1542
+ */
1543
+ }, {
1544
+ key: "priceImpact",
1545
+ get: function get() {
1546
+ if (this._priceImpact) {
1547
+ return this._priceImpact;
1548
+ }
1549
+ var spotOutputAmount = CurrencyAmount.fromRawAmount(this.outputAmount.currency, 0);
1550
+ for (var _iterator3 = _createForOfIteratorHelperLoose(this.swaps), _step3; !(_step3 = _iterator3()).done;) {
1551
+ var _step3$value = _step3.value,
1552
+ route = _step3$value.route,
1553
+ inputAmount = _step3$value.inputAmount;
1554
+ var midPrice = route.midPrice;
1555
+ spotOutputAmount = spotOutputAmount.add(midPrice.quote(inputAmount));
1556
+ }
1557
+ var priceImpact = spotOutputAmount.subtract(this.outputAmount).divide(spotOutputAmount);
1558
+ this._priceImpact = new Percent(priceImpact.numerator, priceImpact.denominator);
1559
+ return this._priceImpact;
1560
+ }
1561
+ }]);
1562
+ }();
1563
+
1564
+ /**
1565
+ * This library is the almost the same as v3-sdk priceTickConversion except
1566
+ * that it accepts a Currency type instead of a Token type,
1567
+ * and thus uses some helper functions defined for the Currency type over the Token type.
1568
+ */
1569
+ /**
1570
+ * Returns a price object corresponding to the input tick and the base/quote token
1571
+ * Inputs must be tokens because the address order is used to interpret the price represented by the tick
1572
+ * @param baseToken the base token of the price
1573
+ * @param quoteToken the quote token of the price
1574
+ * @param tick the tick for which to return the price
1575
+ */
1576
+ function tickToPrice(baseCurrency, quoteCurrency, tick) {
1577
+ var sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
1578
+ var ratioX192 = JSBI.multiply(sqrtRatioX96, sqrtRatioX96);
1579
+ return sortsBefore(baseCurrency, quoteCurrency) ? new Price(baseCurrency, quoteCurrency, Q192, ratioX192) : new Price(baseCurrency, quoteCurrency, ratioX192, Q192);
1580
+ }
1581
+ /**
1582
+ * Returns the first tick for which the given price is greater than or equal to the tick price
1583
+ * @param price for which to return the closest tick that represents a price less than or equal to the input price,
1584
+ * i.e. the price of the returned tick is less than or equal to the input price
1585
+ */
1586
+ function priceToClosestTick(price) {
1587
+ var sorted = sortsBefore(price.baseCurrency, price.quoteCurrency);
1588
+ var sqrtRatioX96 = sorted ? encodeSqrtRatioX96(price.numerator, price.denominator) : encodeSqrtRatioX96(price.denominator, price.numerator);
1589
+ var tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96);
1590
+ var nextTickPrice = tickToPrice(price.baseCurrency, price.quoteCurrency, tick + 1);
1591
+ if (sorted) {
1592
+ if (!price.lessThan(nextTickPrice)) {
1593
+ tick++;
1594
+ }
1595
+ } else {
1596
+ if (!price.greaterThan(nextTickPrice)) {
1597
+ tick++;
1598
+ }
1599
+ }
1600
+ return tick;
1601
+ }
1602
+
1603
+ /**
1604
+ * Represents a position on a Uniswap V4 Pool
1605
+ * @dev Similar to the V3 implementation
1606
+ * - using Currency instead of Token
1607
+ * - keep in mind that Pool and liquidity must be fetched from the pool manager
1608
+ */
1609
+ var Position = /*#__PURE__*/function () {
1610
+ /**
1611
+ * Constructs a position for a given pool with the given liquidity
1612
+ * @param pool For which pool the liquidity is assigned
1613
+ * @param liquidity The amount of liquidity that is in the position
1614
+ * @param tickLower The lower tick of the position
1615
+ * @param tickUpper The upper tick of the position
1616
+ */
1617
+ function Position(_ref) {
1618
+ var pool = _ref.pool,
1619
+ liquidity = _ref.liquidity,
1620
+ tickLower = _ref.tickLower,
1621
+ tickUpper = _ref.tickUpper;
1622
+ // cached resuts for the getters
1623
+ this._token0Amount = null;
1624
+ this._token1Amount = null;
1625
+ this._mintAmounts = null;
1626
+ !(tickLower < tickUpper) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_ORDER') : invariant(false) : void 0;
1627
+ !(tickLower >= TickMath.MIN_TICK && tickLower % pool.tickSpacing === 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_LOWER') : invariant(false) : void 0;
1628
+ !(tickUpper <= TickMath.MAX_TICK && tickUpper % pool.tickSpacing === 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_UPPER') : invariant(false) : void 0;
1629
+ this.pool = pool;
1630
+ this.tickLower = tickLower;
1631
+ this.tickUpper = tickUpper;
1632
+ this.liquidity = JSBI.BigInt(liquidity);
1633
+ }
1634
+ /**
1635
+ * Returns the price of token0 at the lower tick
1636
+ */
1637
+ var _proto = Position.prototype;
1638
+ /**
1639
+ * Returns the lower and upper sqrt ratios if the price 'slips' up to slippage tolerance percentage
1640
+ * @param slippageTolerance The amount by which the price can 'slip' before the transaction will revert
1641
+ * @returns The sqrt ratios after slippage
1642
+ */
1643
+ _proto.ratiosAfterSlippage = function ratiosAfterSlippage(slippageTolerance) {
1644
+ var priceLower = this.pool.token0Price.asFraction.multiply(new Percent(1).subtract(slippageTolerance));
1645
+ var priceUpper = this.pool.token0Price.asFraction.multiply(slippageTolerance.add(1));
1646
+ var sqrtRatioX96Lower = encodeSqrtRatioX96(priceLower.numerator, priceLower.denominator);
1647
+ if (JSBI.lessThanOrEqual(sqrtRatioX96Lower, TickMath.MIN_SQRT_RATIO)) {
1648
+ sqrtRatioX96Lower = JSBI.add(TickMath.MIN_SQRT_RATIO, JSBI.BigInt(1));
1649
+ }
1650
+ var sqrtRatioX96Upper = encodeSqrtRatioX96(priceUpper.numerator, priceUpper.denominator);
1651
+ if (JSBI.greaterThanOrEqual(sqrtRatioX96Upper, TickMath.MAX_SQRT_RATIO)) {
1652
+ sqrtRatioX96Upper = JSBI.subtract(TickMath.MAX_SQRT_RATIO, JSBI.BigInt(1));
1653
+ }
1654
+ return {
1655
+ sqrtRatioX96Lower: sqrtRatioX96Lower,
1656
+ sqrtRatioX96Upper: sqrtRatioX96Upper
1657
+ };
1658
+ }
1659
+ /**
1660
+ * Returns the maximum amount of token0 and token1 that must be sent in order to safely mint the amount of liquidity held by the position
1661
+ * with the given slippage tolerance
1662
+ * @param slippageTolerance Tolerance of unfavorable slippage from the current price
1663
+ * @returns The amounts, with slippage
1664
+ * @dev In v4, minting and increasing is protected by maximum amounts of token0 and token1.
1665
+ */;
1666
+ _proto.mintAmountsWithSlippage = function mintAmountsWithSlippage(slippageTolerance) {
1667
+ // get lower/upper prices
1668
+ // these represent the lowest and highest prices that the pool is allowed to "slip" to
1669
+ var _this$ratiosAfterSlip = this.ratiosAfterSlippage(slippageTolerance),
1670
+ sqrtRatioX96Upper = _this$ratiosAfterSlip.sqrtRatioX96Upper,
1671
+ sqrtRatioX96Lower = _this$ratiosAfterSlip.sqrtRatioX96Lower;
1672
+ // construct counterfactual pools from the lower bounded price and the upper bounded price
1673
+ var poolLower = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, this.pool.tickSpacing, this.pool.hooks, sqrtRatioX96Lower, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower));
1674
+ var poolUpper = new Pool(this.pool.token0, this.pool.token1, this.pool.fee, this.pool.tickSpacing, this.pool.hooks, sqrtRatioX96Upper, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper));
1675
+ // Note: Slippage derivation in v4 is different from v3.
1676
+ // When creating a position (minting) or adding to a position (increasing) slippage is bounded by the MAXIMUM amount in in token0 and token1.
1677
+ // The largest amount of token1 will happen when the price slips up, so we use the poolUpper to get amount1.
1678
+ // The largest amount of token0 will happen when the price slips down, so we use the poolLower to get amount0.
1679
+ // Ie...We want the larger amounts, which occurs at the upper price for amount1...
1680
+ var amount1 = new Position({
1681
+ pool: poolUpper,
1682
+ liquidity: this.liquidity,
1683
+ tickLower: this.tickLower,
1684
+ tickUpper: this.tickUpper
1685
+ }).mintAmounts.amount1;
1686
+ // ...and the lower for amount0
1687
+ var amount0 = new Position({
1688
+ pool: poolLower,
1689
+ liquidity: this.liquidity,
1690
+ tickLower: this.tickLower,
1691
+ tickUpper: this.tickUpper
1692
+ }).mintAmounts.amount0;
1693
+ return {
1694
+ amount0: amount0,
1695
+ amount1: amount1
1696
+ };
1697
+ }
1698
+ /**
1699
+ * Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the
1700
+ * position with the given slippage tolerance
1701
+ * @param slippageTolerance tolerance of unfavorable slippage from the current price
1702
+ * @returns The amounts, with slippage
1703
+ */;
1704
+ _proto.burnAmountsWithSlippage = function burnAmountsWithSlippage(slippageTolerance) {
1705
+ // get lower/upper prices
1706
+ var _this$ratiosAfterSlip2 = this.ratiosAfterSlippage(slippageTolerance),
1707
+ sqrtRatioX96Upper = _this$ratiosAfterSlip2.sqrtRatioX96Upper,
1708
+ sqrtRatioX96Lower = _this$ratiosAfterSlip2.sqrtRatioX96Lower;
1709
+ // construct counterfactual pools
1710
+ var poolLower = new Pool(this.pool.currency0, this.pool.currency1, this.pool.fee, this.pool.tickSpacing, this.pool.hooks, sqrtRatioX96Lower, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Lower));
1711
+ var poolUpper = new Pool(this.pool.currency0, this.pool.currency1, this.pool.fee, this.pool.tickSpacing, this.pool.hooks, sqrtRatioX96Upper, 0 /* liquidity doesn't matter */, TickMath.getTickAtSqrtRatio(sqrtRatioX96Upper));
1712
+ // we want the smaller amounts...
1713
+ // ...which occurs at the upper price for amount0...
1714
+ var amount0 = new Position({
1715
+ pool: poolUpper,
1716
+ liquidity: this.liquidity,
1717
+ tickLower: this.tickLower,
1718
+ tickUpper: this.tickUpper
1719
+ }).amount0;
1720
+ // ...and the lower for amount1
1721
+ var amount1 = new Position({
1722
+ pool: poolLower,
1723
+ liquidity: this.liquidity,
1724
+ tickLower: this.tickLower,
1725
+ tickUpper: this.tickUpper
1726
+ }).amount1;
1727
+ return {
1728
+ amount0: amount0.quotient,
1729
+ amount1: amount1.quotient
1730
+ };
1731
+ }
1732
+ /**
1733
+ * Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at
1734
+ * the current price for the pool
1735
+ */;
1736
+ /**
1737
+ * Returns the AllowanceTransferPermitBatch for adding liquidity to a position
1738
+ * @param slippageTolerance The amount by which the price can 'slip' before the transaction will revert
1739
+ * @param spender The spender of the permit (should usually be the PositionManager)
1740
+ * @param nonce A valid permit2 nonce
1741
+ * @param deadline The deadline for the permit
1742
+ */
1743
+ _proto.permitBatchData = function permitBatchData(slippageTolerance, spender, nonce, deadline) {
1744
+ var _this$mintAmountsWith = this.mintAmountsWithSlippage(slippageTolerance),
1745
+ amount0 = _this$mintAmountsWith.amount0,
1746
+ amount1 = _this$mintAmountsWith.amount1;
1747
+ return {
1748
+ details: [{
1749
+ token: this.pool.currency0.wrapped.address,
1750
+ amount: amount0,
1751
+ expiration: deadline,
1752
+ nonce: nonce
1753
+ }, {
1754
+ token: this.pool.currency1.wrapped.address,
1755
+ amount: amount1,
1756
+ expiration: deadline,
1757
+ nonce: nonce
1758
+ }],
1759
+ spender: spender,
1760
+ sigDeadline: deadline
1761
+ };
1762
+ }
1763
+ /**
1764
+ * Computes the maximum amount of liquidity received for a given amount of token0, token1,
1765
+ * and the prices at the tick boundaries.
1766
+ * @param pool The pool for which the position should be created
1767
+ * @param tickLower The lower tick of the position
1768
+ * @param tickUpper The upper tick of the position
1769
+ * @param amount0 token0 amountzw
1770
+ * @param amount1 token1 amount
1771
+ * @param useFullPrecision If false, liquidity will be maximized according to what the router can calculate,
1772
+ * not what core can theoretically support
1773
+ * @returns The amount of liquidity for the position
1774
+ */;
1775
+ Position.fromAmounts = function fromAmounts(_ref2) {
1776
+ var pool = _ref2.pool,
1777
+ tickLower = _ref2.tickLower,
1778
+ tickUpper = _ref2.tickUpper,
1779
+ amount0 = _ref2.amount0,
1780
+ amount1 = _ref2.amount1,
1781
+ useFullPrecision = _ref2.useFullPrecision;
1782
+ var sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
1783
+ var sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
1784
+ return new Position({
1785
+ pool: pool,
1786
+ tickLower: tickLower,
1787
+ tickUpper: tickUpper,
1788
+ liquidity: maxLiquidityForAmounts(pool.sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision)
1789
+ });
1790
+ }
1791
+ /**
1792
+ * Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1
1793
+ * @param pool The pool for which the position is created
1794
+ * @param tickLower The lower tick
1795
+ * @param tickUpper The upper tick
1796
+ * @param amount0 The desired amount of token0
1797
+ * @param useFullPrecision If true, liquidity will be maximized according to what the router can calculate,
1798
+ * not what core can theoretically support
1799
+ * @returns The position
1800
+ */;
1801
+ Position.fromAmount0 = function fromAmount0(_ref3) {
1802
+ var pool = _ref3.pool,
1803
+ tickLower = _ref3.tickLower,
1804
+ tickUpper = _ref3.tickUpper,
1805
+ amount0 = _ref3.amount0,
1806
+ useFullPrecision = _ref3.useFullPrecision;
1807
+ return Position.fromAmounts({
1808
+ pool: pool,
1809
+ tickLower: tickLower,
1810
+ tickUpper: tickUpper,
1811
+ amount0: amount0,
1812
+ amount1: MaxUint256,
1813
+ useFullPrecision: useFullPrecision
1814
+ });
1815
+ }
1816
+ /**
1817
+ * Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0
1818
+ * @param pool The pool for which the position is created
1819
+ * @param tickLower The lower tick
1820
+ * @param tickUpper The upper tick
1821
+ * @param amount1 The desired amount of token1
1822
+ * @returns The position
1823
+ */;
1824
+ Position.fromAmount1 = function fromAmount1(_ref4) {
1825
+ var pool = _ref4.pool,
1826
+ tickLower = _ref4.tickLower,
1827
+ tickUpper = _ref4.tickUpper,
1828
+ amount1 = _ref4.amount1;
1829
+ // this function always uses full precision,
1830
+ return Position.fromAmounts({
1831
+ pool: pool,
1832
+ tickLower: tickLower,
1833
+ tickUpper: tickUpper,
1834
+ amount0: MaxUint256,
1835
+ amount1: amount1,
1836
+ useFullPrecision: true
1837
+ });
1838
+ };
1839
+ return _createClass(Position, [{
1840
+ key: "token0PriceLower",
1841
+ get: function get() {
1842
+ return tickToPrice(this.pool.currency0, this.pool.currency1, this.tickLower);
1843
+ }
1844
+ /**
1845
+ * Returns the price of token0 at the upper tick
1846
+ */
1847
+ }, {
1848
+ key: "token0PriceUpper",
1849
+ get: function get() {
1850
+ return tickToPrice(this.pool.currency0, this.pool.currency1, this.tickUpper);
1851
+ }
1852
+ /**
1853
+ * Returns the amount of token0 that this position's liquidity could be burned for at the current pool price
1854
+ */
1855
+ }, {
1856
+ key: "amount0",
1857
+ get: function get() {
1858
+ if (!this._token0Amount) {
1859
+ if (this.pool.tickCurrent < this.tickLower) {
1860
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.currency0, SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
1861
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1862
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.currency0, SqrtPriceMath.getAmount0Delta(this.pool.sqrtRatioX96, TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
1863
+ } else {
1864
+ this._token0Amount = CurrencyAmount.fromRawAmount(this.pool.currency0, ZERO);
1865
+ }
1866
+ }
1867
+ return this._token0Amount;
1868
+ }
1869
+ /**
1870
+ * Returns the amount of token1 that this position's liquidity could be burned for at the current pool price
1871
+ */
1872
+ }, {
1873
+ key: "amount1",
1874
+ get: function get() {
1875
+ if (!this._token1Amount) {
1876
+ if (this.pool.tickCurrent < this.tickLower) {
1877
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.currency1, ZERO);
1878
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1879
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.currency1, SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), this.pool.sqrtRatioX96, this.liquidity, false));
1880
+ } else {
1881
+ this._token1Amount = CurrencyAmount.fromRawAmount(this.pool.currency1, SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, false));
1882
+ }
1883
+ }
1884
+ return this._token1Amount;
1885
+ }
1886
+ }, {
1887
+ key: "mintAmounts",
1888
+ get: function get() {
1889
+ if (this._mintAmounts === null) {
1890
+ if (this.pool.tickCurrent < this.tickLower) {
1891
+ return {
1892
+ amount0: SqrtPriceMath.getAmount0Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true),
1893
+ amount1: ZERO
1894
+ };
1895
+ } else if (this.pool.tickCurrent < this.tickUpper) {
1896
+ return {
1897
+ amount0: SqrtPriceMath.getAmount0Delta(this.pool.sqrtRatioX96, TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true),
1898
+ amount1: SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), this.pool.sqrtRatioX96, this.liquidity, true)
1899
+ };
1900
+ } else {
1901
+ return {
1902
+ amount0: ZERO,
1903
+ amount1: SqrtPriceMath.getAmount1Delta(TickMath.getSqrtRatioAtTick(this.tickLower), TickMath.getSqrtRatioAtTick(this.tickUpper), this.liquidity, true)
1904
+ };
1905
+ }
1906
+ }
1907
+ return this._mintAmounts;
1908
+ }
1909
+ }]);
1910
+ }();
1911
+
1912
+ var encodeRouteToPath = function encodeRouteToPath(route, exactOutput) {
1913
+ // create a deep copy of pools so that we don't tamper with pool array on route
1914
+ var pools = route.pools.map(function (p) {
1915
+ return p;
1916
+ });
1917
+ if (exactOutput) pools = pools.reverse();
1918
+ var startingCurrency = exactOutput ? route.pathOutput : route.pathInput;
1919
+ var pathKeys = [];
1920
+ for (var _iterator = _createForOfIteratorHelperLoose(pools), _step; !(_step = _iterator()).done;) {
1921
+ var pool = _step.value;
1922
+ var nextCurrency = startingCurrency.equals(pool.currency0) ? pool.currency1 : pool.currency0;
1923
+ pathKeys.push({
1924
+ intermediateCurrency: nextCurrency.isNative ? ADDRESS_ZERO : nextCurrency.address,
1925
+ fee: pool.fee,
1926
+ tickSpacing: pool.tickSpacing,
1927
+ hooks: pool.hooks,
1928
+ hookData: '0x'
1929
+ });
1930
+ startingCurrency = nextCurrency;
1931
+ }
1932
+ return exactOutput ? pathKeys.reverse() : pathKeys;
1933
+ };
1934
+
1935
+ var _V4_BASE_ACTIONS_ABI_;
1936
+ /**
1937
+ * Actions
1938
+ * @description Constants that define what action to perform
1939
+ * Not all actions are supported yet.
1940
+ * @enum {number}
1941
+ */
1942
+ var Actions;
1943
+ (function (Actions) {
1944
+ // pool actions
1945
+ // liquidity actions
1946
+ Actions[Actions["INCREASE_LIQUIDITY"] = 0] = "INCREASE_LIQUIDITY";
1947
+ Actions[Actions["DECREASE_LIQUIDITY"] = 1] = "DECREASE_LIQUIDITY";
1948
+ Actions[Actions["MINT_POSITION"] = 2] = "MINT_POSITION";
1949
+ Actions[Actions["BURN_POSITION"] = 3] = "BURN_POSITION";
1950
+ // for fee on transfer tokens
1951
+ // INCREASE_LIQUIDITY_FROM_DELTAS = 0x04,
1952
+ // MINT_POSITION_FROM_DELTAS = 0x05,
1953
+ // swapping
1954
+ Actions[Actions["SWAP_EXACT_IN_SINGLE"] = 6] = "SWAP_EXACT_IN_SINGLE";
1955
+ Actions[Actions["SWAP_EXACT_IN"] = 7] = "SWAP_EXACT_IN";
1956
+ Actions[Actions["SWAP_EXACT_OUT_SINGLE"] = 8] = "SWAP_EXACT_OUT_SINGLE";
1957
+ Actions[Actions["SWAP_EXACT_OUT"] = 9] = "SWAP_EXACT_OUT";
1958
+ // closing deltas on the pool manager
1959
+ // settling
1960
+ Actions[Actions["SETTLE"] = 11] = "SETTLE";
1961
+ Actions[Actions["SETTLE_ALL"] = 12] = "SETTLE_ALL";
1962
+ Actions[Actions["SETTLE_PAIR"] = 13] = "SETTLE_PAIR";
1963
+ // taking
1964
+ Actions[Actions["TAKE"] = 14] = "TAKE";
1965
+ Actions[Actions["TAKE_ALL"] = 15] = "TAKE_ALL";
1966
+ Actions[Actions["TAKE_PORTION"] = 16] = "TAKE_PORTION";
1967
+ Actions[Actions["TAKE_PAIR"] = 17] = "TAKE_PAIR";
1968
+ Actions[Actions["CLOSE_CURRENCY"] = 18] = "CLOSE_CURRENCY";
1969
+ // CLEAR_OR_TAKE = 0x13,
1970
+ Actions[Actions["SWEEP"] = 20] = "SWEEP";
1971
+ // for wrapping/unwrapping native
1972
+ // WRAP = 0x15,
1973
+ Actions[Actions["UNWRAP"] = 22] = "UNWRAP";
1974
+ })(Actions || (Actions = {}));
1975
+ var Subparser;
1976
+ (function (Subparser) {
1977
+ Subparser[Subparser["V4SwapExactInSingle"] = 0] = "V4SwapExactInSingle";
1978
+ Subparser[Subparser["V4SwapExactIn"] = 1] = "V4SwapExactIn";
1979
+ Subparser[Subparser["V4SwapExactOutSingle"] = 2] = "V4SwapExactOutSingle";
1980
+ Subparser[Subparser["V4SwapExactOut"] = 3] = "V4SwapExactOut";
1981
+ Subparser[Subparser["PoolKey"] = 4] = "PoolKey";
1982
+ })(Subparser || (Subparser = {}));
1983
+ var POOL_KEY_STRUCT = '(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)';
1984
+ var PATH_KEY_STRUCT = '(address intermediateCurrency,uint256 fee,int24 tickSpacing,address hooks,bytes hookData)';
1985
+ var SWAP_EXACT_IN_SINGLE_STRUCT = '(' + POOL_KEY_STRUCT + ' poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,bytes hookData)';
1986
+ var SWAP_EXACT_IN_STRUCT = '(address currencyIn,' + PATH_KEY_STRUCT + '[] path,uint128 amountIn,uint128 amountOutMinimum)';
1987
+ var SWAP_EXACT_OUT_SINGLE_STRUCT = '(' + POOL_KEY_STRUCT + ' poolKey,bool zeroForOne,uint128 amountOut,uint128 amountInMaximum,bytes hookData)';
1988
+ var SWAP_EXACT_OUT_STRUCT = '(address currencyOut,' + PATH_KEY_STRUCT + '[] path,uint128 amountOut,uint128 amountInMaximum)';
1989
+ var V4_BASE_ACTIONS_ABI_DEFINITION = (_V4_BASE_ACTIONS_ABI_ = {}, _V4_BASE_ACTIONS_ABI_[Actions.INCREASE_LIQUIDITY] = [{
1990
+ name: 'tokenId',
1991
+ type: 'uint256'
1992
+ }, {
1993
+ name: 'liquidity',
1994
+ type: 'uint256'
1995
+ }, {
1996
+ name: 'amount0Max',
1997
+ type: 'uint128'
1998
+ }, {
1999
+ name: 'amount1Max',
2000
+ type: 'uint128'
2001
+ }, {
2002
+ name: 'hookData',
2003
+ type: 'bytes'
2004
+ }], _V4_BASE_ACTIONS_ABI_[Actions.DECREASE_LIQUIDITY] = [{
2005
+ name: 'tokenId',
2006
+ type: 'uint256'
2007
+ }, {
2008
+ name: 'liquidity',
2009
+ type: 'uint256'
2010
+ }, {
2011
+ name: 'amount0Min',
2012
+ type: 'uint128'
2013
+ }, {
2014
+ name: 'amount1Min',
2015
+ type: 'uint128'
2016
+ }, {
2017
+ name: 'hookData',
2018
+ type: 'bytes'
2019
+ }], _V4_BASE_ACTIONS_ABI_[Actions.MINT_POSITION] = [{
2020
+ name: 'poolKey',
2021
+ type: POOL_KEY_STRUCT,
2022
+ subparser: Subparser.PoolKey
2023
+ }, {
2024
+ name: 'tickLower',
2025
+ type: 'int24'
2026
+ }, {
2027
+ name: 'tickUpper',
2028
+ type: 'int24'
2029
+ }, {
2030
+ name: 'liquidity',
2031
+ type: 'uint256'
2032
+ }, {
2033
+ name: 'amount0Max',
2034
+ type: 'uint128'
2035
+ }, {
2036
+ name: 'amount1Max',
2037
+ type: 'uint128'
2038
+ }, {
2039
+ name: 'owner',
2040
+ type: 'address'
2041
+ }, {
2042
+ name: 'hookData',
2043
+ type: 'bytes'
2044
+ }], _V4_BASE_ACTIONS_ABI_[Actions.BURN_POSITION] = [{
2045
+ name: 'tokenId',
2046
+ type: 'uint256'
2047
+ }, {
2048
+ name: 'amount0Min',
2049
+ type: 'uint128'
2050
+ }, {
2051
+ name: 'amount1Min',
2052
+ type: 'uint128'
2053
+ }, {
2054
+ name: 'hookData',
2055
+ type: 'bytes'
2056
+ }], _V4_BASE_ACTIONS_ABI_[Actions.SWAP_EXACT_IN_SINGLE] = [{
2057
+ name: 'swap',
2058
+ type: SWAP_EXACT_IN_SINGLE_STRUCT,
2059
+ subparser: Subparser.V4SwapExactInSingle
2060
+ }], _V4_BASE_ACTIONS_ABI_[Actions.SWAP_EXACT_IN] = [{
2061
+ name: 'swap',
2062
+ type: SWAP_EXACT_IN_STRUCT,
2063
+ subparser: Subparser.V4SwapExactIn
2064
+ }], _V4_BASE_ACTIONS_ABI_[Actions.SWAP_EXACT_OUT_SINGLE] = [{
2065
+ name: 'swap',
2066
+ type: SWAP_EXACT_OUT_SINGLE_STRUCT,
2067
+ subparser: Subparser.V4SwapExactOutSingle
2068
+ }], _V4_BASE_ACTIONS_ABI_[Actions.SWAP_EXACT_OUT] = [{
2069
+ name: 'swap',
2070
+ type: SWAP_EXACT_OUT_STRUCT,
2071
+ subparser: Subparser.V4SwapExactOut
2072
+ }], _V4_BASE_ACTIONS_ABI_[Actions.SETTLE] = [{
2073
+ name: 'currency',
2074
+ type: 'address'
2075
+ }, {
2076
+ name: 'amount',
2077
+ type: 'uint256'
2078
+ }, {
2079
+ name: 'payerIsUser',
2080
+ type: 'bool'
2081
+ }], _V4_BASE_ACTIONS_ABI_[Actions.SETTLE_ALL] = [{
2082
+ name: 'currency',
2083
+ type: 'address'
2084
+ }, {
2085
+ name: 'maxAmount',
2086
+ type: 'uint256'
2087
+ }], _V4_BASE_ACTIONS_ABI_[Actions.SETTLE_PAIR] = [{
2088
+ name: 'currency0',
2089
+ type: 'address'
2090
+ }, {
2091
+ name: 'currency1',
2092
+ type: 'address'
2093
+ }], _V4_BASE_ACTIONS_ABI_[Actions.TAKE] = [{
2094
+ name: 'currency',
2095
+ type: 'address'
2096
+ }, {
2097
+ name: 'recipient',
2098
+ type: 'address'
2099
+ }, {
2100
+ name: 'amount',
2101
+ type: 'uint256'
2102
+ }], _V4_BASE_ACTIONS_ABI_[Actions.TAKE_ALL] = [{
2103
+ name: 'currency',
2104
+ type: 'address'
2105
+ }, {
2106
+ name: 'minAmount',
2107
+ type: 'uint256'
2108
+ }], _V4_BASE_ACTIONS_ABI_[Actions.TAKE_PORTION] = [{
2109
+ name: 'currency',
2110
+ type: 'address'
2111
+ }, {
2112
+ name: 'recipient',
2113
+ type: 'address'
2114
+ }, {
2115
+ name: 'bips',
2116
+ type: 'uint256'
2117
+ }], _V4_BASE_ACTIONS_ABI_[Actions.TAKE_PAIR] = [{
2118
+ name: 'currency0',
2119
+ type: 'address'
2120
+ }, {
2121
+ name: 'currency1',
2122
+ type: 'address'
2123
+ }, {
2124
+ name: 'recipient',
2125
+ type: 'address'
2126
+ }], _V4_BASE_ACTIONS_ABI_[Actions.CLOSE_CURRENCY] = [{
2127
+ name: 'currency',
2128
+ type: 'address'
2129
+ }], _V4_BASE_ACTIONS_ABI_[Actions.SWEEP] = [{
2130
+ name: 'currency',
2131
+ type: 'address'
2132
+ }, {
2133
+ name: 'recipient',
2134
+ type: 'address'
2135
+ }], _V4_BASE_ACTIONS_ABI_[Actions.UNWRAP] = [{
2136
+ name: 'amount',
2137
+ type: 'uint256'
2138
+ }], _V4_BASE_ACTIONS_ABI_);
2139
+ var FULL_DELTA_AMOUNT = 0;
2140
+ var V4Planner = /*#__PURE__*/function () {
2141
+ function V4Planner() {
2142
+ this.actions = EMPTY_BYTES;
2143
+ this.params = [];
2144
+ }
2145
+ var _proto = V4Planner.prototype;
2146
+ _proto.addAction = function addAction(type, parameters) {
2147
+ var command = createAction(type, parameters);
2148
+ this.params.push(command.encodedInput);
2149
+ this.actions = this.actions.concat(command.action.toString(16).padStart(2, '0'));
2150
+ return this;
2151
+ };
2152
+ _proto.addTrade = function addTrade(trade, slippageTolerance) {
2153
+ var exactOutput = trade.tradeType === TradeType.EXACT_OUTPUT;
2154
+ // exactInput we sometimes perform aggregated slippage checks, but not with exactOutput
2155
+ if (exactOutput) !!!slippageTolerance ? process.env.NODE_ENV !== "production" ? invariant(false, 'ExactOut requires slippageTolerance') : invariant(false) : void 0;
2156
+ !(trade.swaps.length === 1) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Only accepts Trades with 1 swap (must break swaps into individual trades)') : invariant(false) : void 0;
2157
+ var actionType = exactOutput ? Actions.SWAP_EXACT_OUT : Actions.SWAP_EXACT_IN;
2158
+ var currencyIn = currencyAddress(trade.route.pathInput);
2159
+ var currencyOut = currencyAddress(trade.route.pathOutput);
2160
+ this.addAction(actionType, [exactOutput ? {
2161
+ currencyOut: currencyOut,
2162
+ path: encodeRouteToPath(trade.route, exactOutput),
2163
+ amountInMaximum: trade.maximumAmountIn(slippageTolerance != null ? slippageTolerance : new Percent(0)).quotient.toString(),
2164
+ amountOut: trade.outputAmount.quotient.toString()
2165
+ } : {
2166
+ currencyIn: currencyIn,
2167
+ path: encodeRouteToPath(trade.route, exactOutput),
2168
+ amountIn: trade.inputAmount.quotient.toString(),
2169
+ amountOutMinimum: slippageTolerance ? trade.minimumAmountOut(slippageTolerance).quotient.toString() : 0
2170
+ }]);
2171
+ return this;
2172
+ };
2173
+ _proto.addSettle = function addSettle(currency, payerIsUser, amount) {
2174
+ this.addAction(Actions.SETTLE, [currencyAddress(currency), amount != null ? amount : FULL_DELTA_AMOUNT, payerIsUser]);
2175
+ return this;
2176
+ };
2177
+ _proto.addTake = function addTake(currency, recipient, amount) {
2178
+ var takeAmount = amount != null ? amount : FULL_DELTA_AMOUNT;
2179
+ this.addAction(Actions.TAKE, [currencyAddress(currency), recipient, takeAmount]);
2180
+ return this;
2181
+ };
2182
+ _proto.addUnwrap = function addUnwrap(amount) {
2183
+ this.addAction(Actions.UNWRAP, [amount]);
2184
+ return this;
2185
+ };
2186
+ _proto.finalize = function finalize() {
2187
+ return defaultAbiCoder.encode(['bytes', 'bytes[]'], [this.actions, this.params]);
2188
+ };
2189
+ return V4Planner;
2190
+ }();
2191
+ function currencyAddress(currency) {
2192
+ return currency.isNative ? ADDRESS_ZERO : currency.wrapped.address;
2193
+ }
2194
+ function createAction(action, parameters) {
2195
+ var encodedInput = defaultAbiCoder.encode(V4_BASE_ACTIONS_ABI_DEFINITION[action].map(function (v) {
2196
+ return v.type;
2197
+ }), parameters);
2198
+ return {
2199
+ action: action,
2200
+ encodedInput: encodedInput
2201
+ };
2202
+ }
2203
+
2204
+ // Uniswap v4 supports native pools. Those currencies are represented by the zero address.
2205
+ // TODO: Figure out if this is how we should be handling weird edge case tokens like CELO/Polygon/etc..
2206
+ // Does interface treat those like ERC20 tokens or NATIVE tokens?
2207
+ function toAddress(currency) {
2208
+ if (currency.isNative) return ADDRESS_ZERO;else return currency.wrapped.address;
2209
+ }
2210
+
2211
+ // A wrapper around V4Planner to help handle PositionManager actions
2212
+ var V4PositionPlanner = /*#__PURE__*/function (_V4Planner) {
2213
+ function V4PositionPlanner() {
2214
+ return _V4Planner.apply(this, arguments) || this;
2215
+ }
2216
+ _inheritsLoose(V4PositionPlanner, _V4Planner);
2217
+ var _proto = V4PositionPlanner.prototype;
2218
+ // MINT_POSITION
2219
+ _proto.addMint = function addMint(pool, tickLower, tickUpper, liquidity, amount0Max, amount1Max, owner, hookData) {
2220
+ if (hookData === void 0) {
2221
+ hookData = EMPTY_BYTES;
2222
+ }
2223
+ var inputs = [Pool.getPoolKey(pool.currency0, pool.currency1, pool.fee, pool.tickSpacing, pool.hooks), tickLower, tickUpper, liquidity.toString(), amount0Max.toString(), amount1Max.toString(), owner, hookData];
2224
+ this.addAction(Actions.MINT_POSITION, inputs);
2225
+ }
2226
+ // INCREASE_LIQUIDITY
2227
+ ;
2228
+ _proto.addIncrease = function addIncrease(tokenId, liquidity, amount0Max, amount1Max, hookData) {
2229
+ if (hookData === void 0) {
2230
+ hookData = EMPTY_BYTES;
2231
+ }
2232
+ var inputs = [tokenId.toString(), liquidity.toString(), amount0Max.toString(), amount1Max.toString(), hookData];
2233
+ this.addAction(Actions.INCREASE_LIQUIDITY, inputs);
2234
+ }
2235
+ // DECREASE_LIQUIDITY
2236
+ ;
2237
+ _proto.addDecrease = function addDecrease(tokenId, liquidity, amount0Min, amount1Min, hookData) {
2238
+ if (hookData === void 0) {
2239
+ hookData = EMPTY_BYTES;
2240
+ }
2241
+ var inputs = [tokenId.toString(), liquidity.toString(), amount0Min.toString(), amount1Min.toString(), hookData];
2242
+ this.addAction(Actions.DECREASE_LIQUIDITY, inputs);
2243
+ }
2244
+ // BURN_POSITION
2245
+ ;
2246
+ _proto.addBurn = function addBurn(tokenId, amount0Min, amount1Min, hookData) {
2247
+ if (hookData === void 0) {
2248
+ hookData = EMPTY_BYTES;
2249
+ }
2250
+ var inputs = [tokenId.toString(), amount0Min.toString(), amount1Min.toString(), hookData];
2251
+ this.addAction(Actions.BURN_POSITION, inputs);
2252
+ }
2253
+ // SETTLE_PAIR
2254
+ ;
2255
+ _proto.addSettlePair = function addSettlePair(currency0, currency1) {
2256
+ var inputs = [toAddress(currency0), toAddress(currency1)];
2257
+ this.addAction(Actions.SETTLE_PAIR, inputs);
2258
+ }
2259
+ // TAKE_PAIR
2260
+ ;
2261
+ _proto.addTakePair = function addTakePair(currency0, currency1, recipient) {
2262
+ var inputs = [toAddress(currency0), toAddress(currency1), recipient];
2263
+ this.addAction(Actions.TAKE_PAIR, inputs);
2264
+ }
2265
+ // SWEEP
2266
+ ;
2267
+ _proto.addSweep = function addSweep(currency, to) {
2268
+ var inputs = [toAddress(currency), to];
2269
+ this.addAction(Actions.SWEEP, inputs);
2270
+ };
2271
+ return V4PositionPlanner;
2272
+ }(V4Planner);
2273
+
2274
+ /**
2275
+ * Converts a big int to a hex string
2276
+ * @param bigintIsh
2277
+ * @returns The hex encoded calldata
2278
+ */
2279
+ function toHex(bigintIsh) {
2280
+ var bigInt = JSBI.BigInt(bigintIsh);
2281
+ var hex = bigInt.toString(16);
2282
+ if (hex.length % 2 !== 0) {
2283
+ hex = "0" + hex;
2284
+ }
2285
+ return "0x" + hex;
2286
+ }
2287
+
2288
+ // Parses V4Router actions
2289
+ var V4BaseActionsParser = /*#__PURE__*/function () {
2290
+ function V4BaseActionsParser() {}
2291
+ V4BaseActionsParser.parseCalldata = function parseCalldata(calldata) {
2292
+ var _ethers$utils$default = ethers.utils.defaultAbiCoder.decode(['bytes', 'bytes[]'], calldata),
2293
+ actions = _ethers$utils$default[0],
2294
+ inputs = _ethers$utils$default[1];
2295
+ var actionTypes = V4BaseActionsParser.getActions(actions);
2296
+ return {
2297
+ actions: actionTypes.map(function (actionType, i) {
2298
+ var abiDef = V4_BASE_ACTIONS_ABI_DEFINITION[actionType];
2299
+ var rawParams = ethers.utils.defaultAbiCoder.decode(abiDef.map(function (command) {
2300
+ return command.type;
2301
+ }), inputs[i]);
2302
+ var params = rawParams.map(function (param, j) {
2303
+ switch (abiDef[j].subparser) {
2304
+ case Subparser.V4SwapExactInSingle:
2305
+ return {
2306
+ name: abiDef[j].name,
2307
+ value: parseV4ExactInSingle(param)
2308
+ };
2309
+ case Subparser.V4SwapExactIn:
2310
+ return {
2311
+ name: abiDef[j].name,
2312
+ value: parseV4ExactIn(param)
2313
+ };
2314
+ case Subparser.V4SwapExactOutSingle:
2315
+ return {
2316
+ name: abiDef[j].name,
2317
+ value: parseV4ExactOutSingle(param)
2318
+ };
2319
+ case Subparser.V4SwapExactOut:
2320
+ return {
2321
+ name: abiDef[j].name,
2322
+ value: parseV4ExactOut(param)
2323
+ };
2324
+ case Subparser.PoolKey:
2325
+ return {
2326
+ name: abiDef[j].name,
2327
+ value: parsePoolKey(param)
2328
+ };
2329
+ default:
2330
+ return {
2331
+ name: abiDef[j].name,
2332
+ value: param
2333
+ };
2334
+ }
2335
+ });
2336
+ return {
2337
+ actionName: Actions[actionType],
2338
+ actionType: actionType,
2339
+ params: params
2340
+ };
2341
+ })
2342
+ };
2343
+ }
2344
+ // parse command types from bytes string
2345
+ ;
2346
+ V4BaseActionsParser.getActions = function getActions(actions) {
2347
+ var actionTypes = [];
2348
+ for (var i = 2; i < actions.length; i += 2) {
2349
+ var _byte = actions.substring(i, i + 2);
2350
+ actionTypes.push(parseInt(_byte, 16));
2351
+ }
2352
+ return actionTypes;
2353
+ };
2354
+ return V4BaseActionsParser;
2355
+ }();
2356
+ function parsePoolKey(data) {
2357
+ var currency0 = data[0],
2358
+ currency1 = data[1],
2359
+ fee = data[2],
2360
+ tickSpacing = data[3],
2361
+ hooks = data[4];
2362
+ return {
2363
+ currency0: currency0,
2364
+ currency1: currency1,
2365
+ fee: parseInt(fee),
2366
+ tickSpacing: parseInt(tickSpacing),
2367
+ hooks: hooks
2368
+ };
2369
+ }
2370
+ function parsePathKey(data) {
2371
+ var intermediateCurrency = data[0],
2372
+ fee = data[1],
2373
+ tickSpacing = data[2],
2374
+ hooks = data[3],
2375
+ hookData = data[4];
2376
+ return {
2377
+ intermediateCurrency: intermediateCurrency,
2378
+ fee: parseInt(fee),
2379
+ tickSpacing: parseInt(tickSpacing),
2380
+ hooks: hooks,
2381
+ hookData: hookData
2382
+ };
2383
+ }
2384
+ function parseV4ExactInSingle(data) {
2385
+ var poolKey = data[0],
2386
+ zeroForOne = data[1],
2387
+ amountIn = data[2],
2388
+ amountOutMinimum = data[3],
2389
+ hookData = data[4];
2390
+ var currency0 = poolKey[0],
2391
+ currency1 = poolKey[1],
2392
+ fee = poolKey[2],
2393
+ tickSpacing = poolKey[3],
2394
+ hooks = poolKey[4];
2395
+ return {
2396
+ poolKey: {
2397
+ currency0: currency0,
2398
+ currency1: currency1,
2399
+ fee: fee,
2400
+ tickSpacing: tickSpacing,
2401
+ hooks: hooks
2402
+ },
2403
+ zeroForOne: zeroForOne,
2404
+ amountIn: amountIn,
2405
+ amountOutMinimum: amountOutMinimum,
2406
+ hookData: hookData
2407
+ };
2408
+ }
2409
+ function parseV4ExactIn(data) {
2410
+ var currencyIn = data[0],
2411
+ path = data[1],
2412
+ amountIn = data[2],
2413
+ amountOutMinimum = data[3];
2414
+ var paths = path.map(function (pathKey) {
2415
+ return parsePathKey(pathKey);
2416
+ });
2417
+ return {
2418
+ path: paths,
2419
+ currencyIn: currencyIn,
2420
+ amountIn: amountIn,
2421
+ amountOutMinimum: amountOutMinimum
2422
+ };
2423
+ }
2424
+ function parseV4ExactOutSingle(data) {
2425
+ var poolKey = data[0],
2426
+ zeroForOne = data[1],
2427
+ amountOut = data[2],
2428
+ amountInMaximum = data[3],
2429
+ hookData = data[4];
2430
+ var currency0 = poolKey.currency0,
2431
+ currency1 = poolKey.currency1,
2432
+ fee = poolKey.fee,
2433
+ tickSpacing = poolKey.tickSpacing,
2434
+ hooks = poolKey.hooks;
2435
+ return {
2436
+ poolKey: {
2437
+ currency0: currency0,
2438
+ currency1: currency1,
2439
+ fee: fee,
2440
+ tickSpacing: tickSpacing,
2441
+ hooks: hooks
2442
+ },
2443
+ zeroForOne: zeroForOne,
2444
+ amountOut: amountOut,
2445
+ amountInMaximum: amountInMaximum,
2446
+ hookData: hookData
2447
+ };
2448
+ }
2449
+ function parseV4ExactOut(data) {
2450
+ var currencyOut = data[0],
2451
+ path = data[1],
2452
+ amountOut = data[2],
2453
+ amountInMaximum = data[3];
2454
+ var paths = path.map(function (pathKey) {
2455
+ return parsePathKey(pathKey);
2456
+ });
2457
+ return {
2458
+ path: paths,
2459
+ currencyOut: currencyOut,
2460
+ amountOut: amountOut,
2461
+ amountInMaximum: amountInMaximum
2462
+ };
2463
+ }
2464
+
2465
+ // Shared Action Constants used in the v4 Router and v4 position manager
2466
+ var MSG_SENDER = '0x0000000000000000000000000000000000000001';
2467
+
2468
+ var Multicall = /*#__PURE__*/function () {
2469
+ /**
2470
+ * Cannot be constructed.
2471
+ */
2472
+ function Multicall() {}
2473
+ Multicall.encodeMulticall = function encodeMulticall(calldataList) {
2474
+ if (!Array.isArray(calldataList)) {
2475
+ calldataList = [calldataList];
2476
+ }
2477
+ return calldataList.length === 1 ? calldataList[0] : Multicall.INTERFACE.encodeFunctionData('multicall', [calldataList]);
2478
+ };
2479
+ Multicall.decodeMulticall = function decodeMulticall(encodedCalldata) {
2480
+ return Multicall.INTERFACE.decodeFunctionData('multicall', encodedCalldata)[0];
2481
+ };
2482
+ return Multicall;
2483
+ }();
2484
+ Multicall.INTERFACE = /*#__PURE__*/new Interface(IMulticall.abi);
2485
+
2486
+ // TODO: import this from npm
2487
+ var positionManagerAbi = [{
2488
+ type: 'constructor',
2489
+ inputs: [{
2490
+ name: '_poolManager',
2491
+ type: 'address',
2492
+ internalType: 'contract IPoolManager'
2493
+ }, {
2494
+ name: '_permit2',
2495
+ type: 'address',
2496
+ internalType: 'contract IAllowanceTransfer'
2497
+ }, {
2498
+ name: '_unsubscribeGasLimit',
2499
+ type: 'uint256',
2500
+ internalType: 'uint256'
2501
+ }, {
2502
+ name: '_tokenDescriptor',
2503
+ type: 'address',
2504
+ internalType: 'contract IPositionDescriptor'
2505
+ }, {
2506
+ name: '_weth9',
2507
+ type: 'address',
2508
+ internalType: 'contract IWETH9'
2509
+ }],
2510
+ stateMutability: 'nonpayable'
2511
+ }, {
2512
+ type: 'receive',
2513
+ stateMutability: 'payable'
2514
+ }, {
2515
+ type: 'function',
2516
+ name: 'DOMAIN_SEPARATOR',
2517
+ inputs: [],
2518
+ outputs: [{
2519
+ name: '',
2520
+ type: 'bytes32',
2521
+ internalType: 'bytes32'
2522
+ }],
2523
+ stateMutability: 'view'
2524
+ }, {
2525
+ type: 'function',
2526
+ name: 'WETH9',
2527
+ inputs: [],
2528
+ outputs: [{
2529
+ name: '',
2530
+ type: 'address',
2531
+ internalType: 'contract IWETH9'
2532
+ }],
2533
+ stateMutability: 'view'
2534
+ }, {
2535
+ type: 'function',
2536
+ name: 'approve',
2537
+ inputs: [{
2538
+ name: 'spender',
2539
+ type: 'address',
2540
+ internalType: 'address'
2541
+ }, {
2542
+ name: 'id',
2543
+ type: 'uint256',
2544
+ internalType: 'uint256'
2545
+ }],
2546
+ outputs: [],
2547
+ stateMutability: 'nonpayable'
2548
+ }, {
2549
+ type: 'function',
2550
+ name: 'balanceOf',
2551
+ inputs: [{
2552
+ name: 'owner',
2553
+ type: 'address',
2554
+ internalType: 'address'
2555
+ }],
2556
+ outputs: [{
2557
+ name: '',
2558
+ type: 'uint256',
2559
+ internalType: 'uint256'
2560
+ }],
2561
+ stateMutability: 'view'
2562
+ }, {
2563
+ type: 'function',
2564
+ name: 'getApproved',
2565
+ inputs: [{
2566
+ name: '',
2567
+ type: 'uint256',
2568
+ internalType: 'uint256'
2569
+ }],
2570
+ outputs: [{
2571
+ name: '',
2572
+ type: 'address',
2573
+ internalType: 'address'
2574
+ }],
2575
+ stateMutability: 'view'
2576
+ }, {
2577
+ type: 'function',
2578
+ name: 'getPoolAndPositionInfo',
2579
+ inputs: [{
2580
+ name: 'tokenId',
2581
+ type: 'uint256',
2582
+ internalType: 'uint256'
2583
+ }],
2584
+ outputs: [{
2585
+ name: 'poolKey',
2586
+ type: 'tuple',
2587
+ internalType: 'struct PoolKey',
2588
+ components: [{
2589
+ name: 'currency0',
2590
+ type: 'address',
2591
+ internalType: 'Currency'
2592
+ }, {
2593
+ name: 'currency1',
2594
+ type: 'address',
2595
+ internalType: 'Currency'
2596
+ }, {
2597
+ name: 'fee',
2598
+ type: 'uint24',
2599
+ internalType: 'uint24'
2600
+ }, {
2601
+ name: 'tickSpacing',
2602
+ type: 'int24',
2603
+ internalType: 'int24'
2604
+ }, {
2605
+ name: 'hooks',
2606
+ type: 'address',
2607
+ internalType: 'contract IHooks'
2608
+ }]
2609
+ }, {
2610
+ name: 'info',
2611
+ type: 'uint256',
2612
+ internalType: 'PositionInfo'
2613
+ }],
2614
+ stateMutability: 'view'
2615
+ }, {
2616
+ type: 'function',
2617
+ name: 'getPositionLiquidity',
2618
+ inputs: [{
2619
+ name: 'tokenId',
2620
+ type: 'uint256',
2621
+ internalType: 'uint256'
2622
+ }],
2623
+ outputs: [{
2624
+ name: 'liquidity',
2625
+ type: 'uint128',
2626
+ internalType: 'uint128'
2627
+ }],
2628
+ stateMutability: 'view'
2629
+ }, {
2630
+ type: 'function',
2631
+ name: 'initializePool',
2632
+ inputs: [{
2633
+ name: 'key',
2634
+ type: 'tuple',
2635
+ internalType: 'struct PoolKey',
2636
+ components: [{
2637
+ name: 'currency0',
2638
+ type: 'address',
2639
+ internalType: 'Currency'
2640
+ }, {
2641
+ name: 'currency1',
2642
+ type: 'address',
2643
+ internalType: 'Currency'
2644
+ }, {
2645
+ name: 'fee',
2646
+ type: 'uint24',
2647
+ internalType: 'uint24'
2648
+ }, {
2649
+ name: 'tickSpacing',
2650
+ type: 'int24',
2651
+ internalType: 'int24'
2652
+ }, {
2653
+ name: 'hooks',
2654
+ type: 'address',
2655
+ internalType: 'contract IHooks'
2656
+ }]
2657
+ }, {
2658
+ name: 'sqrtPriceX96',
2659
+ type: 'uint160',
2660
+ internalType: 'uint160'
2661
+ }],
2662
+ outputs: [{
2663
+ name: '',
2664
+ type: 'int24',
2665
+ internalType: 'int24'
2666
+ }],
2667
+ stateMutability: 'payable'
2668
+ }, {
2669
+ type: 'function',
2670
+ name: 'isApprovedForAll',
2671
+ inputs: [{
2672
+ name: '',
2673
+ type: 'address',
2674
+ internalType: 'address'
2675
+ }, {
2676
+ name: '',
2677
+ type: 'address',
2678
+ internalType: 'address'
2679
+ }],
2680
+ outputs: [{
2681
+ name: '',
2682
+ type: 'bool',
2683
+ internalType: 'bool'
2684
+ }],
2685
+ stateMutability: 'view'
2686
+ }, {
2687
+ type: 'function',
2688
+ name: 'modifyLiquidities',
2689
+ inputs: [{
2690
+ name: 'unlockData',
2691
+ type: 'bytes',
2692
+ internalType: 'bytes'
2693
+ }, {
2694
+ name: 'deadline',
2695
+ type: 'uint256',
2696
+ internalType: 'uint256'
2697
+ }],
2698
+ outputs: [],
2699
+ stateMutability: 'payable'
2700
+ }, {
2701
+ type: 'function',
2702
+ name: 'modifyLiquiditiesWithoutUnlock',
2703
+ inputs: [{
2704
+ name: 'actions',
2705
+ type: 'bytes',
2706
+ internalType: 'bytes'
2707
+ }, {
2708
+ name: 'params',
2709
+ type: 'bytes[]',
2710
+ internalType: 'bytes[]'
2711
+ }],
2712
+ outputs: [],
2713
+ stateMutability: 'payable'
2714
+ }, {
2715
+ type: 'function',
2716
+ name: 'msgSender',
2717
+ inputs: [],
2718
+ outputs: [{
2719
+ name: '',
2720
+ type: 'address',
2721
+ internalType: 'address'
2722
+ }],
2723
+ stateMutability: 'view'
2724
+ }, {
2725
+ type: 'function',
2726
+ name: 'multicall',
2727
+ inputs: [{
2728
+ name: 'data',
2729
+ type: 'bytes[]',
2730
+ internalType: 'bytes[]'
2731
+ }],
2732
+ outputs: [{
2733
+ name: 'results',
2734
+ type: 'bytes[]',
2735
+ internalType: 'bytes[]'
2736
+ }],
2737
+ stateMutability: 'payable'
2738
+ }, {
2739
+ type: 'function',
2740
+ name: 'name',
2741
+ inputs: [],
2742
+ outputs: [{
2743
+ name: '',
2744
+ type: 'string',
2745
+ internalType: 'string'
2746
+ }],
2747
+ stateMutability: 'view'
2748
+ }, {
2749
+ type: 'function',
2750
+ name: 'nextTokenId',
2751
+ inputs: [],
2752
+ outputs: [{
2753
+ name: '',
2754
+ type: 'uint256',
2755
+ internalType: 'uint256'
2756
+ }],
2757
+ stateMutability: 'view'
2758
+ }, {
2759
+ type: 'function',
2760
+ name: 'nonces',
2761
+ inputs: [{
2762
+ name: 'owner',
2763
+ type: 'address',
2764
+ internalType: 'address'
2765
+ }, {
2766
+ name: 'word',
2767
+ type: 'uint256',
2768
+ internalType: 'uint256'
2769
+ }],
2770
+ outputs: [{
2771
+ name: 'bitmap',
2772
+ type: 'uint256',
2773
+ internalType: 'uint256'
2774
+ }],
2775
+ stateMutability: 'view'
2776
+ }, {
2777
+ type: 'function',
2778
+ name: 'ownerOf',
2779
+ inputs: [{
2780
+ name: 'id',
2781
+ type: 'uint256',
2782
+ internalType: 'uint256'
2783
+ }],
2784
+ outputs: [{
2785
+ name: 'owner',
2786
+ type: 'address',
2787
+ internalType: 'address'
2788
+ }],
2789
+ stateMutability: 'view'
2790
+ }, {
2791
+ type: 'function',
2792
+ name: 'permit',
2793
+ inputs: [{
2794
+ name: 'spender',
2795
+ type: 'address',
2796
+ internalType: 'address'
2797
+ }, {
2798
+ name: 'tokenId',
2799
+ type: 'uint256',
2800
+ internalType: 'uint256'
2801
+ }, {
2802
+ name: 'deadline',
2803
+ type: 'uint256',
2804
+ internalType: 'uint256'
2805
+ }, {
2806
+ name: 'nonce',
2807
+ type: 'uint256',
2808
+ internalType: 'uint256'
2809
+ }, {
2810
+ name: 'signature',
2811
+ type: 'bytes',
2812
+ internalType: 'bytes'
2813
+ }],
2814
+ outputs: [],
2815
+ stateMutability: 'payable'
2816
+ }, {
2817
+ type: 'function',
2818
+ name: 'permit',
2819
+ inputs: [{
2820
+ name: 'owner',
2821
+ type: 'address',
2822
+ internalType: 'address'
2823
+ }, {
2824
+ name: 'permitSingle',
2825
+ type: 'tuple',
2826
+ internalType: 'struct IAllowanceTransfer.PermitSingle',
2827
+ components: [{
2828
+ name: 'details',
2829
+ type: 'tuple',
2830
+ internalType: 'struct IAllowanceTransfer.PermitDetails',
2831
+ components: [{
2832
+ name: 'token',
2833
+ type: 'address',
2834
+ internalType: 'address'
2835
+ }, {
2836
+ name: 'amount',
2837
+ type: 'uint160',
2838
+ internalType: 'uint160'
2839
+ }, {
2840
+ name: 'expiration',
2841
+ type: 'uint48',
2842
+ internalType: 'uint48'
2843
+ }, {
2844
+ name: 'nonce',
2845
+ type: 'uint48',
2846
+ internalType: 'uint48'
2847
+ }]
2848
+ }, {
2849
+ name: 'spender',
2850
+ type: 'address',
2851
+ internalType: 'address'
2852
+ }, {
2853
+ name: 'sigDeadline',
2854
+ type: 'uint256',
2855
+ internalType: 'uint256'
2856
+ }]
2857
+ }, {
2858
+ name: 'signature',
2859
+ type: 'bytes',
2860
+ internalType: 'bytes'
2861
+ }],
2862
+ outputs: [{
2863
+ name: 'err',
2864
+ type: 'bytes',
2865
+ internalType: 'bytes'
2866
+ }],
2867
+ stateMutability: 'payable'
2868
+ }, {
2869
+ type: 'function',
2870
+ name: 'permit2',
2871
+ inputs: [],
2872
+ outputs: [{
2873
+ name: '',
2874
+ type: 'address',
2875
+ internalType: 'contract IAllowanceTransfer'
2876
+ }],
2877
+ stateMutability: 'view'
2878
+ }, {
2879
+ type: 'function',
2880
+ name: 'permitBatch',
2881
+ inputs: [{
2882
+ name: 'owner',
2883
+ type: 'address',
2884
+ internalType: 'address'
2885
+ }, {
2886
+ name: '_permitBatch',
2887
+ type: 'tuple',
2888
+ internalType: 'struct IAllowanceTransfer.PermitBatch',
2889
+ components: [{
2890
+ name: 'details',
2891
+ type: 'tuple[]',
2892
+ internalType: 'struct IAllowanceTransfer.PermitDetails[]',
2893
+ components: [{
2894
+ name: 'token',
2895
+ type: 'address',
2896
+ internalType: 'address'
2897
+ }, {
2898
+ name: 'amount',
2899
+ type: 'uint160',
2900
+ internalType: 'uint160'
2901
+ }, {
2902
+ name: 'expiration',
2903
+ type: 'uint48',
2904
+ internalType: 'uint48'
2905
+ }, {
2906
+ name: 'nonce',
2907
+ type: 'uint48',
2908
+ internalType: 'uint48'
2909
+ }]
2910
+ }, {
2911
+ name: 'spender',
2912
+ type: 'address',
2913
+ internalType: 'address'
2914
+ }, {
2915
+ name: 'sigDeadline',
2916
+ type: 'uint256',
2917
+ internalType: 'uint256'
2918
+ }]
2919
+ }, {
2920
+ name: 'signature',
2921
+ type: 'bytes',
2922
+ internalType: 'bytes'
2923
+ }],
2924
+ outputs: [{
2925
+ name: 'err',
2926
+ type: 'bytes',
2927
+ internalType: 'bytes'
2928
+ }],
2929
+ stateMutability: 'payable'
2930
+ }, {
2931
+ type: 'function',
2932
+ name: 'permitForAll',
2933
+ inputs: [{
2934
+ name: 'owner',
2935
+ type: 'address',
2936
+ internalType: 'address'
2937
+ }, {
2938
+ name: 'operator',
2939
+ type: 'address',
2940
+ internalType: 'address'
2941
+ }, {
2942
+ name: 'approved',
2943
+ type: 'bool',
2944
+ internalType: 'bool'
2945
+ }, {
2946
+ name: 'deadline',
2947
+ type: 'uint256',
2948
+ internalType: 'uint256'
2949
+ }, {
2950
+ name: 'nonce',
2951
+ type: 'uint256',
2952
+ internalType: 'uint256'
2953
+ }, {
2954
+ name: 'signature',
2955
+ type: 'bytes',
2956
+ internalType: 'bytes'
2957
+ }],
2958
+ outputs: [],
2959
+ stateMutability: 'payable'
2960
+ }, {
2961
+ type: 'function',
2962
+ name: 'poolKeys',
2963
+ inputs: [{
2964
+ name: 'poolId',
2965
+ type: 'bytes25',
2966
+ internalType: 'bytes25'
2967
+ }],
2968
+ outputs: [{
2969
+ name: 'currency0',
2970
+ type: 'address',
2971
+ internalType: 'Currency'
2972
+ }, {
2973
+ name: 'currency1',
2974
+ type: 'address',
2975
+ internalType: 'Currency'
2976
+ }, {
2977
+ name: 'fee',
2978
+ type: 'uint24',
2979
+ internalType: 'uint24'
2980
+ }, {
2981
+ name: 'tickSpacing',
2982
+ type: 'int24',
2983
+ internalType: 'int24'
2984
+ }, {
2985
+ name: 'hooks',
2986
+ type: 'address',
2987
+ internalType: 'contract IHooks'
2988
+ }],
2989
+ stateMutability: 'view'
2990
+ }, {
2991
+ type: 'function',
2992
+ name: 'poolManager',
2993
+ inputs: [],
2994
+ outputs: [{
2995
+ name: '',
2996
+ type: 'address',
2997
+ internalType: 'contract IPoolManager'
2998
+ }],
2999
+ stateMutability: 'view'
3000
+ }, {
3001
+ type: 'function',
3002
+ name: 'positionInfo',
3003
+ inputs: [{
3004
+ name: 'tokenId',
3005
+ type: 'uint256',
3006
+ internalType: 'uint256'
3007
+ }],
3008
+ outputs: [{
3009
+ name: 'info',
3010
+ type: 'uint256',
3011
+ internalType: 'PositionInfo'
3012
+ }],
3013
+ stateMutability: 'view'
3014
+ }, {
3015
+ type: 'function',
3016
+ name: 'revokeNonce',
3017
+ inputs: [{
3018
+ name: 'nonce',
3019
+ type: 'uint256',
3020
+ internalType: 'uint256'
3021
+ }],
3022
+ outputs: [],
3023
+ stateMutability: 'payable'
3024
+ }, {
3025
+ type: 'function',
3026
+ name: 'safeTransferFrom',
3027
+ inputs: [{
3028
+ name: 'from',
3029
+ type: 'address',
3030
+ internalType: 'address'
3031
+ }, {
3032
+ name: 'to',
3033
+ type: 'address',
3034
+ internalType: 'address'
3035
+ }, {
3036
+ name: 'id',
3037
+ type: 'uint256',
3038
+ internalType: 'uint256'
3039
+ }],
3040
+ outputs: [],
3041
+ stateMutability: 'nonpayable'
3042
+ }, {
3043
+ type: 'function',
3044
+ name: 'safeTransferFrom',
3045
+ inputs: [{
3046
+ name: 'from',
3047
+ type: 'address',
3048
+ internalType: 'address'
3049
+ }, {
3050
+ name: 'to',
3051
+ type: 'address',
3052
+ internalType: 'address'
3053
+ }, {
3054
+ name: 'id',
3055
+ type: 'uint256',
3056
+ internalType: 'uint256'
3057
+ }, {
3058
+ name: 'data',
3059
+ type: 'bytes',
3060
+ internalType: 'bytes'
3061
+ }],
3062
+ outputs: [],
3063
+ stateMutability: 'nonpayable'
3064
+ }, {
3065
+ type: 'function',
3066
+ name: 'setApprovalForAll',
3067
+ inputs: [{
3068
+ name: 'operator',
3069
+ type: 'address',
3070
+ internalType: 'address'
3071
+ }, {
3072
+ name: 'approved',
3073
+ type: 'bool',
3074
+ internalType: 'bool'
3075
+ }],
3076
+ outputs: [],
3077
+ stateMutability: 'nonpayable'
3078
+ }, {
3079
+ type: 'function',
3080
+ name: 'subscribe',
3081
+ inputs: [{
3082
+ name: 'tokenId',
3083
+ type: 'uint256',
3084
+ internalType: 'uint256'
3085
+ }, {
3086
+ name: 'newSubscriber',
3087
+ type: 'address',
3088
+ internalType: 'address'
3089
+ }, {
3090
+ name: 'data',
3091
+ type: 'bytes',
3092
+ internalType: 'bytes'
3093
+ }],
3094
+ outputs: [],
3095
+ stateMutability: 'payable'
3096
+ }, {
3097
+ type: 'function',
3098
+ name: 'subscriber',
3099
+ inputs: [{
3100
+ name: 'tokenId',
3101
+ type: 'uint256',
3102
+ internalType: 'uint256'
3103
+ }],
3104
+ outputs: [{
3105
+ name: 'subscriber',
3106
+ type: 'address',
3107
+ internalType: 'contract ISubscriber'
3108
+ }],
3109
+ stateMutability: 'view'
3110
+ }, {
3111
+ type: 'function',
3112
+ name: 'supportsInterface',
3113
+ inputs: [{
3114
+ name: 'interfaceId',
3115
+ type: 'bytes4',
3116
+ internalType: 'bytes4'
3117
+ }],
3118
+ outputs: [{
3119
+ name: '',
3120
+ type: 'bool',
3121
+ internalType: 'bool'
3122
+ }],
3123
+ stateMutability: 'view'
3124
+ }, {
3125
+ type: 'function',
3126
+ name: 'symbol',
3127
+ inputs: [],
3128
+ outputs: [{
3129
+ name: '',
3130
+ type: 'string',
3131
+ internalType: 'string'
3132
+ }],
3133
+ stateMutability: 'view'
3134
+ }, {
3135
+ type: 'function',
3136
+ name: 'tokenDescriptor',
3137
+ inputs: [],
3138
+ outputs: [{
3139
+ name: '',
3140
+ type: 'address',
3141
+ internalType: 'contract IPositionDescriptor'
3142
+ }],
3143
+ stateMutability: 'view'
3144
+ }, {
3145
+ type: 'function',
3146
+ name: 'tokenURI',
3147
+ inputs: [{
3148
+ name: 'tokenId',
3149
+ type: 'uint256',
3150
+ internalType: 'uint256'
3151
+ }],
3152
+ outputs: [{
3153
+ name: '',
3154
+ type: 'string',
3155
+ internalType: 'string'
3156
+ }],
3157
+ stateMutability: 'view'
3158
+ }, {
3159
+ type: 'function',
3160
+ name: 'transferFrom',
3161
+ inputs: [{
3162
+ name: 'from',
3163
+ type: 'address',
3164
+ internalType: 'address'
3165
+ }, {
3166
+ name: 'to',
3167
+ type: 'address',
3168
+ internalType: 'address'
3169
+ }, {
3170
+ name: 'id',
3171
+ type: 'uint256',
3172
+ internalType: 'uint256'
3173
+ }],
3174
+ outputs: [],
3175
+ stateMutability: 'nonpayable'
3176
+ }, {
3177
+ type: 'function',
3178
+ name: 'unlockCallback',
3179
+ inputs: [{
3180
+ name: 'data',
3181
+ type: 'bytes',
3182
+ internalType: 'bytes'
3183
+ }],
3184
+ outputs: [{
3185
+ name: '',
3186
+ type: 'bytes',
3187
+ internalType: 'bytes'
3188
+ }],
3189
+ stateMutability: 'nonpayable'
3190
+ }, {
3191
+ type: 'function',
3192
+ name: 'unsubscribe',
3193
+ inputs: [{
3194
+ name: 'tokenId',
3195
+ type: 'uint256',
3196
+ internalType: 'uint256'
3197
+ }],
3198
+ outputs: [],
3199
+ stateMutability: 'payable'
3200
+ }, {
3201
+ type: 'function',
3202
+ name: 'unsubscribeGasLimit',
3203
+ inputs: [],
3204
+ outputs: [{
3205
+ name: '',
3206
+ type: 'uint256',
3207
+ internalType: 'uint256'
3208
+ }],
3209
+ stateMutability: 'view'
3210
+ }, {
3211
+ type: 'event',
3212
+ name: 'Approval',
3213
+ inputs: [{
3214
+ name: 'owner',
3215
+ type: 'address',
3216
+ indexed: true,
3217
+ internalType: 'address'
3218
+ }, {
3219
+ name: 'spender',
3220
+ type: 'address',
3221
+ indexed: true,
3222
+ internalType: 'address'
3223
+ }, {
3224
+ name: 'id',
3225
+ type: 'uint256',
3226
+ indexed: true,
3227
+ internalType: 'uint256'
3228
+ }],
3229
+ anonymous: false
3230
+ }, {
3231
+ type: 'event',
3232
+ name: 'ApprovalForAll',
3233
+ inputs: [{
3234
+ name: 'owner',
3235
+ type: 'address',
3236
+ indexed: true,
3237
+ internalType: 'address'
3238
+ }, {
3239
+ name: 'operator',
3240
+ type: 'address',
3241
+ indexed: true,
3242
+ internalType: 'address'
3243
+ }, {
3244
+ name: 'approved',
3245
+ type: 'bool',
3246
+ indexed: false,
3247
+ internalType: 'bool'
3248
+ }],
3249
+ anonymous: false
3250
+ }, {
3251
+ type: 'event',
3252
+ name: 'Subscription',
3253
+ inputs: [{
3254
+ name: 'tokenId',
3255
+ type: 'uint256',
3256
+ indexed: true,
3257
+ internalType: 'uint256'
3258
+ }, {
3259
+ name: 'subscriber',
3260
+ type: 'address',
3261
+ indexed: true,
3262
+ internalType: 'address'
3263
+ }],
3264
+ anonymous: false
3265
+ }, {
3266
+ type: 'event',
3267
+ name: 'Transfer',
3268
+ inputs: [{
3269
+ name: 'from',
3270
+ type: 'address',
3271
+ indexed: true,
3272
+ internalType: 'address'
3273
+ }, {
3274
+ name: 'to',
3275
+ type: 'address',
3276
+ indexed: true,
3277
+ internalType: 'address'
3278
+ }, {
3279
+ name: 'id',
3280
+ type: 'uint256',
3281
+ indexed: true,
3282
+ internalType: 'uint256'
3283
+ }],
3284
+ anonymous: false
3285
+ }, {
3286
+ type: 'event',
3287
+ name: 'Unsubscription',
3288
+ inputs: [{
3289
+ name: 'tokenId',
3290
+ type: 'uint256',
3291
+ indexed: true,
3292
+ internalType: 'uint256'
3293
+ }, {
3294
+ name: 'subscriber',
3295
+ type: 'address',
3296
+ indexed: true,
3297
+ internalType: 'address'
3298
+ }],
3299
+ anonymous: false
3300
+ }, {
3301
+ type: 'error',
3302
+ name: 'AlreadySubscribed',
3303
+ inputs: [{
3304
+ name: 'tokenId',
3305
+ type: 'uint256',
3306
+ internalType: 'uint256'
3307
+ }, {
3308
+ name: 'subscriber',
3309
+ type: 'address',
3310
+ internalType: 'address'
3311
+ }]
3312
+ }, {
3313
+ type: 'error',
3314
+ name: 'BurnNotificationReverted',
3315
+ inputs: [{
3316
+ name: 'subscriber',
3317
+ type: 'address',
3318
+ internalType: 'address'
3319
+ }, {
3320
+ name: 'reason',
3321
+ type: 'bytes',
3322
+ internalType: 'bytes'
3323
+ }]
3324
+ }, {
3325
+ type: 'error',
3326
+ name: 'ContractLocked',
3327
+ inputs: []
3328
+ }, {
3329
+ type: 'error',
3330
+ name: 'DeadlinePassed',
3331
+ inputs: [{
3332
+ name: 'deadline',
3333
+ type: 'uint256',
3334
+ internalType: 'uint256'
3335
+ }]
3336
+ }, {
3337
+ type: 'error',
3338
+ name: 'DeltaNotNegative',
3339
+ inputs: [{
3340
+ name: 'currency',
3341
+ type: 'address',
3342
+ internalType: 'Currency'
3343
+ }]
3344
+ }, {
3345
+ type: 'error',
3346
+ name: 'DeltaNotPositive',
3347
+ inputs: [{
3348
+ name: 'currency',
3349
+ type: 'address',
3350
+ internalType: 'Currency'
3351
+ }]
3352
+ }, {
3353
+ type: 'error',
3354
+ name: 'GasLimitTooLow',
3355
+ inputs: []
3356
+ }, {
3357
+ type: 'error',
3358
+ name: 'InputLengthMismatch',
3359
+ inputs: []
3360
+ }, {
3361
+ type: 'error',
3362
+ name: 'InsufficientBalance',
3363
+ inputs: []
3364
+ }, {
3365
+ type: 'error',
3366
+ name: 'InvalidContractSignature',
3367
+ inputs: []
3368
+ }, {
3369
+ type: 'error',
3370
+ name: 'InvalidEthSender',
3371
+ inputs: []
3372
+ }, {
3373
+ type: 'error',
3374
+ name: 'InvalidSignature',
3375
+ inputs: []
3376
+ }, {
3377
+ type: 'error',
3378
+ name: 'InvalidSignatureLength',
3379
+ inputs: []
3380
+ }, {
3381
+ type: 'error',
3382
+ name: 'InvalidSigner',
3383
+ inputs: []
3384
+ }, {
3385
+ type: 'error',
3386
+ name: 'MaximumAmountExceeded',
3387
+ inputs: [{
3388
+ name: 'maximumAmount',
3389
+ type: 'uint128',
3390
+ internalType: 'uint128'
3391
+ }, {
3392
+ name: 'amountRequested',
3393
+ type: 'uint128',
3394
+ internalType: 'uint128'
3395
+ }]
3396
+ }, {
3397
+ type: 'error',
3398
+ name: 'MinimumAmountInsufficient',
3399
+ inputs: [{
3400
+ name: 'minimumAmount',
3401
+ type: 'uint128',
3402
+ internalType: 'uint128'
3403
+ }, {
3404
+ name: 'amountReceived',
3405
+ type: 'uint128',
3406
+ internalType: 'uint128'
3407
+ }]
3408
+ }, {
3409
+ type: 'error',
3410
+ name: 'ModifyLiquidityNotificationReverted',
3411
+ inputs: [{
3412
+ name: 'subscriber',
3413
+ type: 'address',
3414
+ internalType: 'address'
3415
+ }, {
3416
+ name: 'reason',
3417
+ type: 'bytes',
3418
+ internalType: 'bytes'
3419
+ }]
3420
+ }, {
3421
+ type: 'error',
3422
+ name: 'NoCodeSubscriber',
3423
+ inputs: []
3424
+ }, {
3425
+ type: 'error',
3426
+ name: 'NoSelfPermit',
3427
+ inputs: []
3428
+ }, {
3429
+ type: 'error',
3430
+ name: 'NonceAlreadyUsed',
3431
+ inputs: []
3432
+ }, {
3433
+ type: 'error',
3434
+ name: 'NotApproved',
3435
+ inputs: [{
3436
+ name: 'caller',
3437
+ type: 'address',
3438
+ internalType: 'address'
3439
+ }]
3440
+ }, {
3441
+ type: 'error',
3442
+ name: 'NotPoolManager',
3443
+ inputs: []
3444
+ }, {
3445
+ type: 'error',
3446
+ name: 'NotSubscribed',
3447
+ inputs: []
3448
+ }, {
3449
+ type: 'error',
3450
+ name: 'PoolManagerMustBeLocked',
3451
+ inputs: []
3452
+ }, {
3453
+ type: 'error',
3454
+ name: 'SignatureDeadlineExpired',
3455
+ inputs: []
3456
+ }, {
3457
+ type: 'error',
3458
+ name: 'SubscriptionReverted',
3459
+ inputs: [{
3460
+ name: 'subscriber',
3461
+ type: 'address',
3462
+ internalType: 'address'
3463
+ }, {
3464
+ name: 'reason',
3465
+ type: 'bytes',
3466
+ internalType: 'bytes'
3467
+ }]
3468
+ }, {
3469
+ type: 'error',
3470
+ name: 'TransferNotificationReverted',
3471
+ inputs: [{
3472
+ name: 'subscriber',
3473
+ type: 'address',
3474
+ internalType: 'address'
3475
+ }, {
3476
+ name: 'reason',
3477
+ type: 'bytes',
3478
+ internalType: 'bytes'
3479
+ }]
3480
+ }, {
3481
+ type: 'error',
3482
+ name: 'Unauthorized',
3483
+ inputs: []
3484
+ }, {
3485
+ type: 'error',
3486
+ name: 'UnsupportedAction',
3487
+ inputs: [{
3488
+ name: 'action',
3489
+ type: 'uint256',
3490
+ internalType: 'uint256'
3491
+ }]
3492
+ }];
3493
+
3494
+ var NFT_PERMIT_TYPES = {
3495
+ Permit: [{
3496
+ name: 'spender',
3497
+ type: 'address'
3498
+ }, {
3499
+ name: 'tokenId',
3500
+ type: 'uint256'
3501
+ }, {
3502
+ name: 'nonce',
3503
+ type: 'uint256'
3504
+ }, {
3505
+ name: 'deadline',
3506
+ type: 'uint256'
3507
+ }]
3508
+ };
3509
+ // type guard
3510
+ function isMint(options) {
3511
+ return Object.keys(options).some(function (k) {
3512
+ return k === 'recipient';
3513
+ });
3514
+ }
3515
+ function shouldCreatePool(options) {
3516
+ if (options.createPool) {
3517
+ !(options.sqrtPriceX96 !== undefined) ? process.env.NODE_ENV !== "production" ? invariant(false, NO_SQRT_PRICE) : invariant(false) : void 0;
3518
+ return true;
3519
+ }
3520
+ return false;
3521
+ }
3522
+ var V4PositionManager = /*#__PURE__*/function () {
3523
+ /**
3524
+ * Cannot be constructed.
3525
+ */
3526
+ function V4PositionManager() {}
3527
+ /**
3528
+ * Public methods to encode method parameters for different actions on the PositionManager contract
3529
+ */
3530
+ V4PositionManager.createCallParameters = function createCallParameters(poolKey, sqrtPriceX96) {
3531
+ return {
3532
+ calldata: this.encodeInitializePool(poolKey, sqrtPriceX96),
3533
+ value: toHex(0)
3534
+ };
3535
+ };
3536
+ V4PositionManager.addCallParameters = function addCallParameters(position, options) {
3537
+ /**
3538
+ * Cases:
3539
+ * - if pool does not exist yet, encode initializePool
3540
+ * then,
3541
+ * - if is mint, encode MINT_POSITION. If migrating, encode a SETTLE and SWEEP for both currencies. Else, encode a SETTLE_PAIR. If on a NATIVE pool, encode a SWEEP.
3542
+ * - else, encode INCREASE_LIQUIDITY and SETTLE_PAIR. If it is on a NATIVE pool, encode a SWEEP.
3543
+ */
3544
+ !JSBI.greaterThan(position.liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, ZERO_LIQUIDITY) : invariant(false) : void 0;
3545
+ var calldataList = [];
3546
+ var planner = new V4PositionPlanner();
3547
+ // Encode initialize pool.
3548
+ if (isMint(options) && shouldCreatePool(options)) {
3549
+ // No planner used here because initializePool is not supported as an Action
3550
+ calldataList.push(V4PositionManager.encodeInitializePool(position.pool.poolKey, options.sqrtPriceX96));
3551
+ }
3552
+ // position.pool.currency0 is native if and only if options.useNative is set
3553
+ !(position.pool.currency0 === options.useNative || !position.pool.currency0.isNative && options.useNative === undefined) ? process.env.NODE_ENV !== "production" ? invariant(false, NATIVE_NOT_SET) : invariant(false) : void 0;
3554
+ // adjust for slippage
3555
+ var maximumAmounts = position.mintAmountsWithSlippage(options.slippageTolerance);
3556
+ var amount0Max = toHex(maximumAmounts.amount0);
3557
+ var amount1Max = toHex(maximumAmounts.amount1);
3558
+ // We use permit2 to approve tokens to the position manager
3559
+ if (options.batchPermit) {
3560
+ calldataList.push(V4PositionManager.encodePermitBatch(options.batchPermit.owner, options.batchPermit.permitBatch, options.batchPermit.signature));
3561
+ }
3562
+ // mint
3563
+ if (isMint(options)) {
3564
+ var recipient = validateAndParseAddress(options.recipient);
3565
+ planner.addMint(position.pool, position.tickLower, position.tickUpper, position.liquidity, amount0Max, amount1Max, recipient, options.hookData);
3566
+ } else {
3567
+ // increase
3568
+ planner.addIncrease(options.tokenId, position.liquidity, amount0Max, amount1Max, options.hookData);
3569
+ }
3570
+ var value = toHex(0);
3571
+ // If migrating, we need to settle and sweep both currencies individually
3572
+ if (isMint(options) && options.migrate) {
3573
+ if (options.useNative) {
3574
+ // unwrap the exact amount needed to send to the pool manager
3575
+ planner.addUnwrap(OPEN_DELTA);
3576
+ // payer is v4 position manager
3577
+ planner.addSettle(position.pool.currency0, false);
3578
+ planner.addSettle(position.pool.currency1, false);
3579
+ // sweep any leftover wrapped native that was not unwrapped
3580
+ // recipient will be same as the v4 lp token recipient
3581
+ planner.addSweep(position.pool.currency0.wrapped, options.recipient);
3582
+ planner.addSweep(position.pool.currency1, options.recipient);
3583
+ } else {
3584
+ // payer is v4 position manager
3585
+ planner.addSettle(position.pool.currency0, false);
3586
+ planner.addSettle(position.pool.currency1, false);
3587
+ // recipient will be same as the v4 lp token recipient
3588
+ planner.addSweep(position.pool.currency0, options.recipient);
3589
+ planner.addSweep(position.pool.currency1, options.recipient);
3590
+ }
3591
+ } else {
3592
+ // need to settle both currencies when minting / adding liquidity (user is the payer)
3593
+ planner.addSettlePair(position.pool.currency0, position.pool.currency1);
3594
+ // When not migrating and adding native currency, add a final sweep
3595
+ if (options.useNative) {
3596
+ // Any sweeping must happen after the settling.
3597
+ // native currency will always be currency0 in v4
3598
+ value = toHex(amount0Max);
3599
+ planner.addSweep(position.pool.currency0, MSG_SENDER);
3600
+ }
3601
+ }
3602
+ calldataList.push(V4PositionManager.encodeModifyLiquidities(planner.finalize(), options.deadline));
3603
+ return {
3604
+ calldata: Multicall.encodeMulticall(calldataList),
3605
+ value: value
3606
+ };
3607
+ }
3608
+ /**
3609
+ * Produces the calldata for completely or partially exiting a position
3610
+ * @param position The position to exit
3611
+ * @param options Additional information necessary for generating the calldata
3612
+ * @returns The call parameters
3613
+ */;
3614
+ V4PositionManager.removeCallParameters = function removeCallParameters(position, options) {
3615
+ /**
3616
+ * cases:
3617
+ * - if liquidityPercentage is 100%, encode BURN_POSITION and then TAKE_PAIR
3618
+ * - else, encode DECREASE_LIQUIDITY and then TAKE_PAIR
3619
+ */
3620
+ var calldataList = [];
3621
+ var planner = new V4PositionPlanner();
3622
+ var tokenId = toHex(options.tokenId);
3623
+ if (options.burnToken) {
3624
+ // if burnToken is true, the specified liquidity percentage must be 100%
3625
+ !options.liquidityPercentage.equalTo(ONE) ? process.env.NODE_ENV !== "production" ? invariant(false, CANNOT_BURN) : invariant(false) : void 0;
3626
+ // if there is a permit, encode the ERC721Permit permit call
3627
+ if (options.permit) {
3628
+ calldataList.push(V4PositionManager.encodeERC721Permit(options.permit.spender, options.permit.tokenId, options.permit.deadline, options.permit.nonce, options.permit.signature));
3629
+ }
3630
+ // slippage-adjusted amounts derived from current position liquidity
3631
+ var _position$burnAmounts = position.burnAmountsWithSlippage(options.slippageTolerance),
3632
+ amount0Min = _position$burnAmounts.amount0,
3633
+ amount1Min = _position$burnAmounts.amount1;
3634
+ planner.addBurn(tokenId, amount0Min, amount1Min, options.hookData);
3635
+ } else {
3636
+ var _options$hookData;
3637
+ // construct a partial position with a percentage of liquidity
3638
+ var partialPosition = new Position({
3639
+ pool: position.pool,
3640
+ liquidity: options.liquidityPercentage.multiply(position.liquidity).quotient,
3641
+ tickLower: position.tickLower,
3642
+ tickUpper: position.tickUpper
3643
+ });
3644
+ // If the partial position has liquidity=0, this is a collect call and collectCallParameters should be used
3645
+ !JSBI.greaterThan(partialPosition.liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, ZERO_LIQUIDITY) : invariant(false) : void 0;
3646
+ // slippage-adjusted underlying amounts
3647
+ var _partialPosition$burn = partialPosition.burnAmountsWithSlippage(options.slippageTolerance),
3648
+ _amount0Min = _partialPosition$burn.amount0,
3649
+ _amount1Min = _partialPosition$burn.amount1;
3650
+ planner.addDecrease(tokenId, partialPosition.liquidity.toString(), _amount0Min.toString(), _amount1Min.toString(), (_options$hookData = options.hookData) != null ? _options$hookData : EMPTY_BYTES);
3651
+ }
3652
+ planner.addTakePair(position.pool.currency0, position.pool.currency1, MSG_SENDER);
3653
+ calldataList.push(V4PositionManager.encodeModifyLiquidities(planner.finalize(), options.deadline));
3654
+ return {
3655
+ calldata: Multicall.encodeMulticall(calldataList),
3656
+ value: toHex(0)
3657
+ };
3658
+ }
3659
+ /**
3660
+ * Produces the calldata for collecting fees from a position
3661
+ * @param position The position to collect fees from
3662
+ * @param options Additional information necessary for generating the calldata
3663
+ * @returns The call parameters
3664
+ */;
3665
+ V4PositionManager.collectCallParameters = function collectCallParameters(position, options) {
3666
+ var calldataList = [];
3667
+ var planner = new V4PositionPlanner();
3668
+ var tokenId = toHex(options.tokenId);
3669
+ var recipient = validateAndParseAddress(options.recipient);
3670
+ /**
3671
+ * To collect fees in V4, we need to:
3672
+ * - encode a decrease liquidity by 0
3673
+ * - and encode a TAKE_PAIR
3674
+ */
3675
+ planner.addDecrease(tokenId, '0', '0', '0', options.hookData);
3676
+ planner.addTakePair(position.pool.currency0, position.pool.currency1, recipient);
3677
+ calldataList.push(V4PositionManager.encodeModifyLiquidities(planner.finalize(), options.deadline));
3678
+ return {
3679
+ calldata: Multicall.encodeMulticall(calldataList),
3680
+ value: toHex(0)
3681
+ };
3682
+ }
3683
+ // Initialize a pool
3684
+ ;
3685
+ V4PositionManager.encodeInitializePool = function encodeInitializePool(poolKey, sqrtPriceX96) {
3686
+ return V4PositionManager.INTERFACE.encodeFunctionData(PositionFunctions.INITIALIZE_POOL, [poolKey, sqrtPriceX96.toString()]);
3687
+ }
3688
+ // Encode a modify liquidities call
3689
+ ;
3690
+ V4PositionManager.encodeModifyLiquidities = function encodeModifyLiquidities(unlockData, deadline) {
3691
+ return V4PositionManager.INTERFACE.encodeFunctionData(PositionFunctions.MODIFY_LIQUIDITIES, [unlockData, deadline]);
3692
+ }
3693
+ // Encode a permit batch call
3694
+ ;
3695
+ V4PositionManager.encodePermitBatch = function encodePermitBatch(owner, permitBatch, signature) {
3696
+ return V4PositionManager.INTERFACE.encodeFunctionData(PositionFunctions.PERMIT_BATCH, [owner, permitBatch, signature]);
3697
+ }
3698
+ // Encode a ERC721Permit permit call
3699
+ ;
3700
+ V4PositionManager.encodeERC721Permit = function encodeERC721Permit(spender, tokenId, deadline, nonce, signature) {
3701
+ return V4PositionManager.INTERFACE.encodeFunctionData(PositionFunctions.ERC721PERMIT_PERMIT, [spender, tokenId, deadline, nonce, signature]);
3702
+ }
3703
+ // Prepare the params for an EIP712 signTypedData request
3704
+ ;
3705
+ V4PositionManager.getPermitData = function getPermitData(permit, positionManagerAddress, chainId) {
3706
+ return {
3707
+ domain: {
3708
+ name: 'Uniswap V4 Positions NFT',
3709
+ chainId: chainId,
3710
+ verifyingContract: positionManagerAddress
3711
+ },
3712
+ types: NFT_PERMIT_TYPES,
3713
+ values: permit
3714
+ };
3715
+ };
3716
+ return V4PositionManager;
3717
+ }();
3718
+ V4PositionManager.INTERFACE = /*#__PURE__*/new Interface(positionManagerAbi);
3719
+
3720
+ export { Actions, DYNAMIC_FEE_FLAG, Hook, HookOptions, Pool, Position, Route, Subparser, Trade, V4BaseActionsParser, V4Planner, V4PositionManager, V4PositionPlanner, V4_BASE_ACTIONS_ABI_DEFINITION, amountWithPathCurrency, encodeRouteToPath, getPathCurrency, hookFlagIndex, priceToClosestTick, sortsBefore, tickToPrice, toAddress, toHex, tradeComparator };
3721
+ //# sourceMappingURL=v4-sdk.esm.js.map