@juiceswapxyz/v4-sdk 3.0.0 → 3.0.1

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