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