@kayenfinance/v2-sdk 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,945 @@
1
+ import { ChainId, V2_FACTORY_ADDRESSES, Percent, CurrencyAmount, sqrt, Token, Price, TradeType, Fraction, computePriceImpact, sortedInsert, validateAndParseAddress } from '@kayenfinance/sdk-core';
2
+ import JSBI from 'jsbi';
3
+ import { getCreate2Address } from '@ethersproject/address';
4
+ import { BigNumber } from '@ethersproject/bignumber';
5
+ import { keccak256, pack } from '@ethersproject/solidity';
6
+ import invariant from 'tiny-invariant';
7
+
8
+ var _FACTORY_ADDRESS_BY_C, _INIT_CODE_HASH_BY_CH;
9
+
10
+ /**
11
+ * @deprecated use FACTORY_ADDRESS_MAP instead
12
+ */
13
+ var FACTORY_ADDRESS = '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f';
14
+ var FACTORY_ADDRESS_BY_CHAIN_ID = (_FACTORY_ADDRESS_BY_C = {}, _FACTORY_ADDRESS_BY_C[ChainId.CHILIZ] = '0xE2918AA38088878546c1A18F2F9b1BC83297fdD3', _FACTORY_ADDRESS_BY_C[ChainId.SPICY] = '0xfc1924E20d64AD4daA3A4947b4bAE6cDE77d2dBC', _FACTORY_ADDRESS_BY_C);
15
+ var FACTORY_ADDRESS_MAP = V2_FACTORY_ADDRESSES;
16
+ var INIT_CODE_HASH = '0x4fb91ee014f2c198fe03fa69aa007f8e04f2fe96fe4444492a517fdec1063a17';
17
+ var INIT_CODE_HASH_BY_CHAIN_ID = (_INIT_CODE_HASH_BY_CH = {}, _INIT_CODE_HASH_BY_CH[ChainId.CHILIZ] = '0x4fb91ee014f2c198fe03fa69aa007f8e04f2fe96fe4444492a517fdec1063a17', _INIT_CODE_HASH_BY_CH[ChainId.SPICY] = '0x4fb91ee014f2c198fe03fa69aa007f8e04f2fe96fe4444492a517fdec1063a17', _INIT_CODE_HASH_BY_CH);
18
+ var MINIMUM_LIQUIDITY = /*#__PURE__*/JSBI.BigInt(1000);
19
+
20
+ // exports for internal consumption
21
+ var ZERO = /*#__PURE__*/JSBI.BigInt(0);
22
+ var ONE = /*#__PURE__*/JSBI.BigInt(1);
23
+ var FIVE = /*#__PURE__*/JSBI.BigInt(5);
24
+ var _997 = /*#__PURE__*/JSBI.BigInt(997);
25
+ var _1000 = /*#__PURE__*/JSBI.BigInt(1000);
26
+ var BASIS_POINTS = /*#__PURE__*/JSBI.BigInt(10000);
27
+ var ZERO_PERCENT = /*#__PURE__*/new Percent(ZERO);
28
+ var ONE_HUNDRED_PERCENT = /*#__PURE__*/new Percent(ONE);
29
+
30
+ function _arrayLikeToArray(r, a) {
31
+ (null == a || a > r.length) && (a = r.length);
32
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
33
+ return n;
34
+ }
35
+ function _construct(t, e, r) {
36
+ if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
37
+ var o = [null];
38
+ o.push.apply(o, e);
39
+ var p = new (t.bind.apply(t, o))();
40
+ return r && _setPrototypeOf(p, r.prototype), p;
41
+ }
42
+ function _defineProperties(e, r) {
43
+ for (var t = 0; t < r.length; t++) {
44
+ var o = r[t];
45
+ o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
46
+ }
47
+ }
48
+ function _createClass(e, r, t) {
49
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
50
+ writable: !1
51
+ }), e;
52
+ }
53
+ function _createForOfIteratorHelperLoose(r, e) {
54
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
55
+ if (t) return (t = t.call(r)).next.bind(t);
56
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
57
+ t && (r = t);
58
+ var o = 0;
59
+ return function () {
60
+ return o >= r.length ? {
61
+ done: !0
62
+ } : {
63
+ done: !1,
64
+ value: r[o++]
65
+ };
66
+ };
67
+ }
68
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
69
+ }
70
+ function _getPrototypeOf(t) {
71
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
72
+ return t.__proto__ || Object.getPrototypeOf(t);
73
+ }, _getPrototypeOf(t);
74
+ }
75
+ function _inheritsLoose(t, o) {
76
+ t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
77
+ }
78
+ function _isNativeFunction(t) {
79
+ try {
80
+ return -1 !== Function.toString.call(t).indexOf("[native code]");
81
+ } catch (n) {
82
+ return "function" == typeof t;
83
+ }
84
+ }
85
+ function _isNativeReflectConstruct() {
86
+ try {
87
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
88
+ } catch (t) {}
89
+ return (_isNativeReflectConstruct = function () {
90
+ return !!t;
91
+ })();
92
+ }
93
+ function _setPrototypeOf(t, e) {
94
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
95
+ return t.__proto__ = e, t;
96
+ }, _setPrototypeOf(t, e);
97
+ }
98
+ function _toPrimitive(t, r) {
99
+ if ("object" != typeof t || !t) return t;
100
+ var e = t[Symbol.toPrimitive];
101
+ if (void 0 !== e) {
102
+ var i = e.call(t, r || "default");
103
+ if ("object" != typeof i) return i;
104
+ throw new TypeError("@@toPrimitive must return a primitive value.");
105
+ }
106
+ return ("string" === r ? String : Number)(t);
107
+ }
108
+ function _toPropertyKey(t) {
109
+ var i = _toPrimitive(t, "string");
110
+ return "symbol" == typeof i ? i : i + "";
111
+ }
112
+ function _unsupportedIterableToArray(r, a) {
113
+ if (r) {
114
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
115
+ var t = {}.toString.call(r).slice(8, -1);
116
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
117
+ }
118
+ }
119
+ function _wrapNativeSuper(t) {
120
+ var r = "function" == typeof Map ? new Map() : void 0;
121
+ return _wrapNativeSuper = function (t) {
122
+ if (null === t || !_isNativeFunction(t)) return t;
123
+ if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
124
+ if (void 0 !== r) {
125
+ if (r.has(t)) return r.get(t);
126
+ r.set(t, Wrapper);
127
+ }
128
+ function Wrapper() {
129
+ return _construct(t, arguments, _getPrototypeOf(this).constructor);
130
+ }
131
+ return Wrapper.prototype = Object.create(t.prototype, {
132
+ constructor: {
133
+ value: Wrapper,
134
+ enumerable: !1,
135
+ writable: !0,
136
+ configurable: !0
137
+ }
138
+ }), _setPrototypeOf(Wrapper, t);
139
+ }, _wrapNativeSuper(t);
140
+ }
141
+
142
+ // see https://stackoverflow.com/a/41102306
143
+ var CAN_SET_PROTOTYPE = 'setPrototypeOf' in Object;
144
+
145
+ /**
146
+ * Indicates that the pair has insufficient reserves for a desired output amount. I.e. the amount of output cannot be
147
+ * obtained by sending any amount of input.
148
+ */
149
+ var InsufficientReservesError = /*#__PURE__*/function (_Error) {
150
+ function InsufficientReservesError() {
151
+ var _this;
152
+ _this = _Error.call(this) || this;
153
+ _this.isInsufficientReservesError = true;
154
+ _this.name = _this.constructor.name;
155
+ if (CAN_SET_PROTOTYPE) Object.setPrototypeOf(_this, (this instanceof InsufficientReservesError ? this.constructor : void 0).prototype);
156
+ return _this;
157
+ }
158
+ _inheritsLoose(InsufficientReservesError, _Error);
159
+ return InsufficientReservesError;
160
+ }(/*#__PURE__*/_wrapNativeSuper(Error));
161
+
162
+ /**
163
+ * Indicates that the input amount is too small to produce any amount of output. I.e. the amount of input sent is less
164
+ * than the price of a single unit of output after fees.
165
+ */
166
+ var InsufficientInputAmountError = /*#__PURE__*/function (_Error2) {
167
+ function InsufficientInputAmountError() {
168
+ var _this2;
169
+ _this2 = _Error2.call(this) || this;
170
+ _this2.isInsufficientInputAmountError = true;
171
+ _this2.name = _this2.constructor.name;
172
+ if (CAN_SET_PROTOTYPE) Object.setPrototypeOf(_this2, (this instanceof InsufficientInputAmountError ? this.constructor : void 0).prototype);
173
+ return _this2;
174
+ }
175
+ _inheritsLoose(InsufficientInputAmountError, _Error2);
176
+ return InsufficientInputAmountError;
177
+ }(/*#__PURE__*/_wrapNativeSuper(Error));
178
+
179
+ var computePairAddress = function computePairAddress(_ref) {
180
+ var factoryAddress = _ref.factoryAddress,
181
+ tokenA = _ref.tokenA,
182
+ tokenB = _ref.tokenB;
183
+ var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
184
+ token0 = _ref2[0],
185
+ token1 = _ref2[1]; // does safety checks
186
+ return getCreate2Address(factoryAddress, keccak256(['bytes'], [pack(['address', 'address'], [token0.address, token1.address])]), INIT_CODE_HASH);
187
+ };
188
+ var Pair = /*#__PURE__*/function () {
189
+ function Pair(currencyAmountA, tokenAmountB) {
190
+ this.liquidityToken = void 0;
191
+ this.tokenAmounts = void 0;
192
+ var tokenAmounts = currencyAmountA.currency.sortsBefore(tokenAmountB.currency) // does safety checks
193
+ ? [currencyAmountA, tokenAmountB] : [tokenAmountB, currencyAmountA];
194
+ this.liquidityToken = new Token(tokenAmounts[0].currency.chainId, Pair.getAddress(tokenAmounts[0].currency, tokenAmounts[1].currency), 18, 'UNI-V2', 'Uniswap V2');
195
+ this.tokenAmounts = tokenAmounts;
196
+ }
197
+
198
+ /**
199
+ * Returns true if the token is either token0 or token1
200
+ * @param token to check
201
+ */
202
+ Pair.getAddress = function getAddress(tokenA, tokenB) {
203
+ var _FACTORY_ADDRESS_MAP$;
204
+ var factoryAddress = (_FACTORY_ADDRESS_MAP$ = FACTORY_ADDRESS_MAP[tokenA.chainId]) != null ? _FACTORY_ADDRESS_MAP$ : FACTORY_ADDRESS;
205
+ return computePairAddress({
206
+ factoryAddress: factoryAddress,
207
+ tokenA: tokenA,
208
+ tokenB: tokenB
209
+ });
210
+ };
211
+ var _proto = Pair.prototype;
212
+ _proto.involvesToken = function involvesToken(token) {
213
+ return token.equals(this.token0) || token.equals(this.token1);
214
+ }
215
+
216
+ /**
217
+ * Returns the current mid price of the pair in terms of token0, i.e. the ratio of reserve1 to reserve0
218
+ */;
219
+ /**
220
+ * Return the price of the given token in terms of the other token in the pair.
221
+ * @param token token to return price of
222
+ */
223
+ _proto.priceOf = function priceOf(token) {
224
+ !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
225
+ return token.equals(this.token0) ? this.token0Price : this.token1Price;
226
+ }
227
+
228
+ /**
229
+ * Returns the chain ID of the tokens in the pair.
230
+ */;
231
+ _proto.reserveOf = function reserveOf(token) {
232
+ !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
233
+ return token.equals(this.token0) ? this.reserve0 : this.reserve1;
234
+ }
235
+
236
+ /**
237
+ * getAmountOut is the linear algebra of reserve ratio against amountIn:amountOut.
238
+ * https://ethereum.stackexchange.com/questions/101629/what-is-math-for-uniswap-calculates-the-amountout-and-amountin-why-997-and-1000
239
+ * has the math deduction for the reserve calculation without fee-on-transfer fees.
240
+ *
241
+ * With fee-on-transfer tax, intuitively it's just:
242
+ * inputAmountWithFeeAndTax = 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
243
+ * = (1 - amountIn.sellFeesBips / 10000) * amountInWithFee
244
+ * where amountInWithFee is the amountIn after taking out the LP fees
245
+ * outputAmountWithTax = amountOut * (1 - amountOut.buyFeesBips / 10000)
246
+ *
247
+ * But we are illustrating the math deduction below to ensure that's the case.
248
+ *
249
+ * before swap A * B = K where A = reserveIn B = reserveOut
250
+ *
251
+ * after swap A' * B' = K where only k is a constant value
252
+ *
253
+ * getAmountOut
254
+ *
255
+ * A' = A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn # here 0.3% is deducted
256
+ * B' = B - amountOut * (1 - amountOut.buyFeesBips / 10000)
257
+ * amountOut = (B - B') / (1 - amountOut.buyFeesBips / 10000) # where A' * B' still is k
258
+ * = (B - K/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
259
+ * /
260
+ * (1 - amountOut.buyFeesBips / 10000)
261
+ * = (B - AB/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
262
+ * /
263
+ * (1 - amountOut.buyFeesBips / 10000)
264
+ * = ((BA + B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn - AB)/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
265
+ * /
266
+ * (1 - amountOut.buyFeesBips / 10000)
267
+ * = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn / (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
268
+ * /
269
+ * (1 - amountOut.buyFeesBips / 10000)
270
+ * amountOut * (1 - amountOut.buyFeesBips / 10000) = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
271
+ * /
272
+ * (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
273
+ *
274
+ * outputAmountWithTax = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
275
+ * /
276
+ * (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
277
+ * = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn * 1000
278
+ * /
279
+ * ((A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn) * 1000)
280
+ * = (B * (1 - amountIn.sellFeesBips / 10000) 997 * * amountIn
281
+ * /
282
+ * (1000 * A + (1 - amountIn.sellFeesBips / 10000) * 997 * amountIn)
283
+ * = (B * (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee)
284
+ * /
285
+ * (1000 * A + (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee)
286
+ * = (B * inputAmountWithFeeAndTax)
287
+ * /
288
+ * (1000 * A + inputAmountWithFeeAndTax)
289
+ *
290
+ * inputAmountWithFeeAndTax = (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee
291
+ * outputAmountWithTax = amountOut * (1 - amountOut.buyFeesBips / 10000)
292
+ *
293
+ * @param inputAmount
294
+ * @param calculateFotFees
295
+ */;
296
+ _proto.getOutputAmount = function getOutputAmount(inputAmount, calculateFotFees) {
297
+ if (calculateFotFees === void 0) {
298
+ calculateFotFees = true;
299
+ }
300
+ !this.involvesToken(inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
301
+ if (JSBI.equal(this.reserve0.quotient, ZERO) || JSBI.equal(this.reserve1.quotient, ZERO)) {
302
+ throw new InsufficientReservesError();
303
+ }
304
+ var inputReserve = this.reserveOf(inputAmount.currency);
305
+ var outputReserve = this.reserveOf(inputAmount.currency.equals(this.token0) ? this.token1 : this.token0);
306
+ var percentAfterSellFees = calculateFotFees ? this.derivePercentAfterSellFees(inputAmount) : ZERO_PERCENT;
307
+ var inputAmountAfterTax = percentAfterSellFees.greaterThan(ZERO_PERCENT) ? CurrencyAmount.fromRawAmount(inputAmount.currency, percentAfterSellFees.multiply(inputAmount).quotient // fraction.quotient will round down by itself, which is desired
308
+ ) : inputAmount;
309
+ var inputAmountWithFeeAndAfterTax = JSBI.multiply(inputAmountAfterTax.quotient, _997);
310
+ var numerator = JSBI.multiply(inputAmountWithFeeAndAfterTax, outputReserve.quotient);
311
+ var denominator = JSBI.add(JSBI.multiply(inputReserve.quotient, _1000), inputAmountWithFeeAndAfterTax);
312
+ var outputAmount = CurrencyAmount.fromRawAmount(inputAmount.currency.equals(this.token0) ? this.token1 : this.token0, JSBI.divide(numerator, denominator) // JSBI.divide will round down by itself, which is desired
313
+ );
314
+ if (JSBI.equal(outputAmount.quotient, ZERO)) {
315
+ throw new InsufficientInputAmountError();
316
+ }
317
+ var percentAfterBuyFees = calculateFotFees ? this.derivePercentAfterBuyFees(outputAmount) : ZERO_PERCENT;
318
+ var outputAmountAfterTax = percentAfterBuyFees.greaterThan(ZERO_PERCENT) ? CurrencyAmount.fromRawAmount(outputAmount.currency, outputAmount.multiply(percentAfterBuyFees).quotient // fraction.quotient will round down by itself, which is desired
319
+ ) : outputAmount;
320
+ if (JSBI.equal(outputAmountAfterTax.quotient, ZERO)) {
321
+ throw new InsufficientInputAmountError();
322
+ }
323
+ return [outputAmountAfterTax, new Pair(inputReserve.add(inputAmountAfterTax), outputReserve.subtract(outputAmountAfterTax))];
324
+ }
325
+
326
+ /**
327
+ * getAmountIn is the linear algebra of reserve ratio against amountIn:amountOut.
328
+ * https://ethereum.stackexchange.com/questions/101629/what-is-math-for-uniswap-calculates-the-amountout-and-amountin-why-997-and-1000
329
+ * has the math deduction for the reserve calculation without fee-on-transfer fees.
330
+ *
331
+ * With fee-on-transfer fees, intuitively it's just:
332
+ * outputAmountWithTax = amountOut / (1 - amountOut.buyFeesBips / 10000)
333
+ * inputAmountWithTax = amountIn / (1 - amountIn.sellFeesBips / 10000) / 0.997
334
+ *
335
+ * But we are illustrating the math deduction below to ensure that's the case.
336
+ *
337
+ * before swap A * B = K where A = reserveIn B = reserveOut
338
+ *
339
+ * after swap A' * B' = K where only k is a constant value
340
+ *
341
+ * getAmountIn
342
+ *
343
+ * B' = B - amountOut * (1 - amountOut.buyFeesBips / 10000)
344
+ * A' = A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn # here 0.3% is deducted
345
+ * amountIn = (A' - A) / (0.997 * (1 - amountIn.sellFeesBips / 10000))
346
+ * = (K / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)) - A)
347
+ * /
348
+ * (0.997 * (1 - amountIn.sellFeesBips / 10000))
349
+ * = (AB / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)) - A)
350
+ * /
351
+ * (0.997 * (1 - amountIn.sellFeesBips / 10000))
352
+ * = ((AB - AB + A * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
353
+ * /
354
+ * (0.997 * (1 - amountIn.sellFeesBips / 10000))
355
+ * = ((A * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
356
+ * /
357
+ * (0.997 * (1 - amountIn.sellFeesBips / 10000))
358
+ * = ((A * 1000 * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
359
+ * /
360
+ * (997 * (1 - amountIn.sellFeesBips / 10000))
361
+ *
362
+ * outputAmountWithTax = amountOut / (1 - amountOut.buyFeesBips / 10000)
363
+ * inputAmountWithTax = amountIn / (997 * (1 - amountIn.sellFeesBips / 10000))
364
+ * = (A * outputAmountWithTax * 1000) / ((B - outputAmountWithTax) * 997)
365
+ *
366
+ * @param outputAmount
367
+ */;
368
+ _proto.getInputAmount = function getInputAmount(outputAmount, calculateFotFees) {
369
+ if (calculateFotFees === void 0) {
370
+ calculateFotFees = true;
371
+ }
372
+ !this.involvesToken(outputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
373
+ var percentAfterBuyFees = calculateFotFees ? this.derivePercentAfterBuyFees(outputAmount) : ZERO_PERCENT;
374
+ var outputAmountBeforeTax = percentAfterBuyFees.greaterThan(ZERO_PERCENT) ? CurrencyAmount.fromRawAmount(outputAmount.currency, JSBI.add(outputAmount.divide(percentAfterBuyFees).quotient, ONE) // add 1 for rounding up
375
+ ) : outputAmount;
376
+ if (JSBI.equal(this.reserve0.quotient, ZERO) || JSBI.equal(this.reserve1.quotient, ZERO) || JSBI.greaterThanOrEqual(outputAmount.quotient, this.reserveOf(outputAmount.currency).quotient) || JSBI.greaterThanOrEqual(outputAmountBeforeTax.quotient, this.reserveOf(outputAmount.currency).quotient)) {
377
+ throw new InsufficientReservesError();
378
+ }
379
+ var outputReserve = this.reserveOf(outputAmount.currency);
380
+ var inputReserve = this.reserveOf(outputAmount.currency.equals(this.token0) ? this.token1 : this.token0);
381
+ var numerator = JSBI.multiply(JSBI.multiply(inputReserve.quotient, outputAmountBeforeTax.quotient), _1000);
382
+ var denominator = JSBI.multiply(JSBI.subtract(outputReserve.quotient, outputAmountBeforeTax.quotient), _997);
383
+ var inputAmount = CurrencyAmount.fromRawAmount(outputAmount.currency.equals(this.token0) ? this.token1 : this.token0, JSBI.add(JSBI.divide(numerator, denominator), ONE) // add 1 here is part of the formula, no rounding needed here, since there will not be decimal at this point
384
+ );
385
+ var percentAfterSellFees = calculateFotFees ? this.derivePercentAfterSellFees(inputAmount) : ZERO_PERCENT;
386
+ var inputAmountBeforeTax = percentAfterSellFees.greaterThan(ZERO_PERCENT) ? CurrencyAmount.fromRawAmount(inputAmount.currency, JSBI.add(inputAmount.divide(percentAfterSellFees).quotient, ONE) // add 1 for rounding up
387
+ ) : inputAmount;
388
+ return [inputAmountBeforeTax, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))];
389
+ };
390
+ _proto.getLiquidityMinted = function getLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB) {
391
+ !totalSupply.currency.equals(this.liquidityToken) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LIQUIDITY') : invariant(false) : void 0;
392
+ var tokenAmounts = tokenAmountA.currency.sortsBefore(tokenAmountB.currency) // does safety checks
393
+ ? [tokenAmountA, tokenAmountB] : [tokenAmountB, tokenAmountA];
394
+ !(tokenAmounts[0].currency.equals(this.token0) && tokenAmounts[1].currency.equals(this.token1)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
395
+ var liquidity;
396
+ if (JSBI.equal(totalSupply.quotient, ZERO)) {
397
+ liquidity = JSBI.subtract(sqrt(JSBI.multiply(tokenAmounts[0].quotient, tokenAmounts[1].quotient)), MINIMUM_LIQUIDITY);
398
+ } else {
399
+ var amount0 = JSBI.divide(JSBI.multiply(tokenAmounts[0].quotient, totalSupply.quotient), this.reserve0.quotient);
400
+ var amount1 = JSBI.divide(JSBI.multiply(tokenAmounts[1].quotient, totalSupply.quotient), this.reserve1.quotient);
401
+ liquidity = JSBI.lessThanOrEqual(amount0, amount1) ? amount0 : amount1;
402
+ }
403
+ if (!JSBI.greaterThan(liquidity, ZERO)) {
404
+ throw new InsufficientInputAmountError();
405
+ }
406
+ return CurrencyAmount.fromRawAmount(this.liquidityToken, liquidity);
407
+ };
408
+ _proto.getLiquidityValue = function getLiquidityValue(token, totalSupply, liquidity, feeOn, kLast) {
409
+ if (feeOn === void 0) {
410
+ feeOn = false;
411
+ }
412
+ !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
413
+ !totalSupply.currency.equals(this.liquidityToken) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOTAL_SUPPLY') : invariant(false) : void 0;
414
+ !liquidity.currency.equals(this.liquidityToken) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LIQUIDITY') : invariant(false) : void 0;
415
+ !JSBI.lessThanOrEqual(liquidity.quotient, totalSupply.quotient) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LIQUIDITY') : invariant(false) : void 0;
416
+ var totalSupplyAdjusted;
417
+ if (!feeOn) {
418
+ totalSupplyAdjusted = totalSupply;
419
+ } else {
420
+ !!!kLast ? process.env.NODE_ENV !== "production" ? invariant(false, 'K_LAST') : invariant(false) : void 0;
421
+ var kLastParsed = JSBI.BigInt(kLast);
422
+ if (!JSBI.equal(kLastParsed, ZERO)) {
423
+ var rootK = sqrt(JSBI.multiply(this.reserve0.quotient, this.reserve1.quotient));
424
+ var rootKLast = sqrt(kLastParsed);
425
+ if (JSBI.greaterThan(rootK, rootKLast)) {
426
+ var numerator = JSBI.multiply(totalSupply.quotient, JSBI.subtract(rootK, rootKLast));
427
+ var denominator = JSBI.add(JSBI.multiply(rootK, FIVE), rootKLast);
428
+ var feeLiquidity = JSBI.divide(numerator, denominator);
429
+ totalSupplyAdjusted = totalSupply.add(CurrencyAmount.fromRawAmount(this.liquidityToken, feeLiquidity));
430
+ } else {
431
+ totalSupplyAdjusted = totalSupply;
432
+ }
433
+ } else {
434
+ totalSupplyAdjusted = totalSupply;
435
+ }
436
+ }
437
+ return CurrencyAmount.fromRawAmount(token, JSBI.divide(JSBI.multiply(liquidity.quotient, this.reserveOf(token).quotient), totalSupplyAdjusted.quotient));
438
+ };
439
+ _proto.derivePercentAfterSellFees = function derivePercentAfterSellFees(inputAmount) {
440
+ var sellFeeBips = this.token0.wrapped.equals(inputAmount.wrapped.currency) ? this.token0.wrapped.sellFeeBps : this.token1.wrapped.sellFeeBps;
441
+ if (sellFeeBips != null && sellFeeBips.gt(BigNumber.from(0))) {
442
+ return ONE_HUNDRED_PERCENT.subtract(new Percent(JSBI.BigInt(sellFeeBips)).divide(BASIS_POINTS));
443
+ } else {
444
+ return ZERO_PERCENT;
445
+ }
446
+ };
447
+ _proto.derivePercentAfterBuyFees = function derivePercentAfterBuyFees(outputAmount) {
448
+ var buyFeeBps = this.token0.wrapped.equals(outputAmount.wrapped.currency) ? this.token0.wrapped.buyFeeBps : this.token1.wrapped.buyFeeBps;
449
+ if (buyFeeBps != null && buyFeeBps.gt(BigNumber.from(0))) {
450
+ return ONE_HUNDRED_PERCENT.subtract(new Percent(JSBI.BigInt(buyFeeBps)).divide(BASIS_POINTS));
451
+ } else {
452
+ return ZERO_PERCENT;
453
+ }
454
+ };
455
+ return _createClass(Pair, [{
456
+ key: "token0Price",
457
+ get: function get() {
458
+ var result = this.tokenAmounts[1].divide(this.tokenAmounts[0]);
459
+ return new Price(this.token0, this.token1, result.denominator, result.numerator);
460
+ }
461
+
462
+ /**
463
+ * Returns the current mid price of the pair in terms of token1, i.e. the ratio of reserve0 to reserve1
464
+ */
465
+ }, {
466
+ key: "token1Price",
467
+ get: function get() {
468
+ var result = this.tokenAmounts[0].divide(this.tokenAmounts[1]);
469
+ return new Price(this.token1, this.token0, result.denominator, result.numerator);
470
+ }
471
+ }, {
472
+ key: "chainId",
473
+ get: function get() {
474
+ return this.token0.chainId;
475
+ }
476
+ }, {
477
+ key: "token0",
478
+ get: function get() {
479
+ return this.tokenAmounts[0].currency;
480
+ }
481
+ }, {
482
+ key: "token1",
483
+ get: function get() {
484
+ return this.tokenAmounts[1].currency;
485
+ }
486
+ }, {
487
+ key: "reserve0",
488
+ get: function get() {
489
+ return this.tokenAmounts[0];
490
+ }
491
+ }, {
492
+ key: "reserve1",
493
+ get: function get() {
494
+ return this.tokenAmounts[1];
495
+ }
496
+ }]);
497
+ }();
498
+
499
+ var Route = /*#__PURE__*/function () {
500
+ function Route(pairs, input, output) {
501
+ this.pairs = void 0;
502
+ this.path = void 0;
503
+ this.input = void 0;
504
+ this.output = void 0;
505
+ this._midPrice = null;
506
+ !(pairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PAIRS') : invariant(false) : void 0;
507
+ var chainId = pairs[0].chainId;
508
+ !pairs.every(function (pair) {
509
+ return pair.chainId === chainId;
510
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0;
511
+ var wrappedInput = input.wrapped;
512
+ !pairs[0].involvesToken(wrappedInput) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
513
+ !(typeof output === 'undefined' || pairs[pairs.length - 1].involvesToken(output.wrapped)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
514
+ var path = [wrappedInput];
515
+ for (var _iterator = _createForOfIteratorHelperLoose(pairs.entries()), _step; !(_step = _iterator()).done;) {
516
+ var _step$value = _step.value,
517
+ i = _step$value[0],
518
+ pair = _step$value[1];
519
+ var currentInput = path[i];
520
+ !(currentInput.equals(pair.token0) || currentInput.equals(pair.token1)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PATH') : invariant(false) : void 0;
521
+ var _output = currentInput.equals(pair.token0) ? pair.token1 : pair.token0;
522
+ path.push(_output);
523
+ }
524
+ this.pairs = pairs;
525
+ this.path = path;
526
+ this.input = input;
527
+ this.output = output;
528
+ }
529
+ return _createClass(Route, [{
530
+ key: "midPrice",
531
+ get: function get() {
532
+ if (this._midPrice !== null) return this._midPrice;
533
+ var prices = [];
534
+ for (var _iterator2 = _createForOfIteratorHelperLoose(this.pairs.entries()), _step2; !(_step2 = _iterator2()).done;) {
535
+ var _step2$value = _step2.value,
536
+ i = _step2$value[0],
537
+ pair = _step2$value[1];
538
+ prices.push(this.path[i].equals(pair.token0) ? new Price(pair.reserve0.currency, pair.reserve1.currency, pair.reserve0.quotient, pair.reserve1.quotient) : new Price(pair.reserve1.currency, pair.reserve0.currency, pair.reserve1.quotient, pair.reserve0.quotient));
539
+ }
540
+ var reduced = prices.slice(1).reduce(function (accumulator, currentValue) {
541
+ return accumulator.multiply(currentValue);
542
+ }, prices[0]);
543
+ return this._midPrice = new Price(this.input, this.output, reduced.denominator, reduced.numerator);
544
+ }
545
+ }, {
546
+ key: "chainId",
547
+ get: function get() {
548
+ return this.pairs[0].chainId;
549
+ }
550
+ }]);
551
+ }();
552
+
553
+ // minimal interface so the input output comparator may be shared across types
554
+
555
+ // comparator function that allows sorting trades by their output amounts, in decreasing order, and then input amounts
556
+ // in increasing order. i.e. the best trades have the most outputs for the least inputs and are sorted first
557
+ function inputOutputComparator(a, b) {
558
+ // must have same input and output token for comparison
559
+ !a.inputAmount.currency.equals(b.inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY') : invariant(false) : void 0;
560
+ !a.outputAmount.currency.equals(b.outputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY') : invariant(false) : void 0;
561
+ if (a.outputAmount.equalTo(b.outputAmount)) {
562
+ if (a.inputAmount.equalTo(b.inputAmount)) {
563
+ return 0;
564
+ }
565
+ // trade A requires less input than trade B, so A should come first
566
+ if (a.inputAmount.lessThan(b.inputAmount)) {
567
+ return -1;
568
+ } else {
569
+ return 1;
570
+ }
571
+ } else {
572
+ // tradeA has less output than trade B, so should come second
573
+ if (a.outputAmount.lessThan(b.outputAmount)) {
574
+ return 1;
575
+ } else {
576
+ return -1;
577
+ }
578
+ }
579
+ }
580
+
581
+ // extension of the input output comparator that also considers other dimensions of the trade in ranking them
582
+ function tradeComparator(a, b) {
583
+ var ioComp = inputOutputComparator(a, b);
584
+ if (ioComp !== 0) {
585
+ return ioComp;
586
+ }
587
+
588
+ // consider lowest slippage next, since these are less likely to fail
589
+ if (a.priceImpact.lessThan(b.priceImpact)) {
590
+ return -1;
591
+ } else if (a.priceImpact.greaterThan(b.priceImpact)) {
592
+ return 1;
593
+ }
594
+
595
+ // finally consider the number of hops since each hop costs gas
596
+ return a.route.path.length - b.route.path.length;
597
+ }
598
+ /**
599
+ * Represents a trade executed against a list of pairs.
600
+ * Does not account for slippage, i.e. trades that front run this trade and move the price.
601
+ */
602
+ var Trade = /*#__PURE__*/function () {
603
+ function Trade(route, amount, tradeType) {
604
+ /**
605
+ * The route of the trade, i.e. which pairs the trade goes through and the input/output currencies.
606
+ */
607
+ this.route = void 0;
608
+ /**
609
+ * The type of the trade, either exact in or exact out.
610
+ */
611
+ this.tradeType = void 0;
612
+ /**
613
+ * The input amount for the trade assuming no slippage.
614
+ */
615
+ this.inputAmount = void 0;
616
+ /**
617
+ * The output amount for the trade assuming no slippage.
618
+ */
619
+ this.outputAmount = void 0;
620
+ /**
621
+ * The price expressed in terms of output amount/input amount.
622
+ */
623
+ this.executionPrice = void 0;
624
+ /**
625
+ * The percent difference between the mid price before the trade and the trade execution price.
626
+ */
627
+ this.priceImpact = void 0;
628
+ this.route = route;
629
+ this.tradeType = tradeType;
630
+ var tokenAmounts = new Array(route.path.length);
631
+ if (tradeType === TradeType.EXACT_INPUT) {
632
+ !amount.currency.equals(route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
633
+ tokenAmounts[0] = amount.wrapped;
634
+ for (var i = 0; i < route.path.length - 1; i++) {
635
+ var pair = route.pairs[i];
636
+ var _pair$getOutputAmount = pair.getOutputAmount(tokenAmounts[i]),
637
+ outputAmount = _pair$getOutputAmount[0];
638
+ tokenAmounts[i + 1] = outputAmount;
639
+ }
640
+ this.inputAmount = CurrencyAmount.fromFractionalAmount(route.input, amount.numerator, amount.denominator);
641
+ this.outputAmount = CurrencyAmount.fromFractionalAmount(route.output, tokenAmounts[tokenAmounts.length - 1].numerator, tokenAmounts[tokenAmounts.length - 1].denominator);
642
+ } else {
643
+ !amount.currency.equals(route.output) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
644
+ tokenAmounts[tokenAmounts.length - 1] = amount.wrapped;
645
+ for (var _i = route.path.length - 1; _i > 0; _i--) {
646
+ var _pair = route.pairs[_i - 1];
647
+ var _pair$getInputAmount = _pair.getInputAmount(tokenAmounts[_i]),
648
+ inputAmount = _pair$getInputAmount[0];
649
+ tokenAmounts[_i - 1] = inputAmount;
650
+ }
651
+ this.inputAmount = CurrencyAmount.fromFractionalAmount(route.input, tokenAmounts[0].numerator, tokenAmounts[0].denominator);
652
+ this.outputAmount = CurrencyAmount.fromFractionalAmount(route.output, amount.numerator, amount.denominator);
653
+ }
654
+ this.executionPrice = new Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.quotient, this.outputAmount.quotient);
655
+ this.priceImpact = computePriceImpact(route.midPrice, this.inputAmount, this.outputAmount);
656
+ }
657
+
658
+ /**
659
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
660
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
661
+ */
662
+ /**
663
+ * Constructs an exact in trade with the given amount in and route
664
+ * @param route route of the exact in trade
665
+ * @param amountIn the amount being passed in
666
+ */
667
+ Trade.exactIn = function exactIn(route, amountIn) {
668
+ return new Trade(route, amountIn, TradeType.EXACT_INPUT);
669
+ }
670
+
671
+ /**
672
+ * Constructs an exact out trade with the given amount out and route
673
+ * @param route route of the exact out trade
674
+ * @param amountOut the amount returned by the trade
675
+ */;
676
+ Trade.exactOut = function exactOut(route, amountOut) {
677
+ return new Trade(route, amountOut, TradeType.EXACT_OUTPUT);
678
+ };
679
+ var _proto = Trade.prototype;
680
+ _proto.minimumAmountOut = function minimumAmountOut(slippageTolerance) {
681
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
682
+ if (this.tradeType === TradeType.EXACT_OUTPUT) {
683
+ return this.outputAmount;
684
+ } else {
685
+ var slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(this.outputAmount.quotient).quotient;
686
+ return CurrencyAmount.fromRawAmount(this.outputAmount.currency, slippageAdjustedAmountOut);
687
+ }
688
+ }
689
+
690
+ /**
691
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
692
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
693
+ */;
694
+ _proto.maximumAmountIn = function maximumAmountIn(slippageTolerance) {
695
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
696
+ if (this.tradeType === TradeType.EXACT_INPUT) {
697
+ return this.inputAmount;
698
+ } else {
699
+ var slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(this.inputAmount.quotient).quotient;
700
+ return CurrencyAmount.fromRawAmount(this.inputAmount.currency, slippageAdjustedAmountIn);
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Given a list of pairs, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
706
+ * amount to an output token, making at most `maxHops` hops.
707
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
708
+ * the amount in among multiple routes.
709
+ * @param pairs the pairs to consider in finding the best trade
710
+ * @param nextAmountIn exact amount of input currency to spend
711
+ * @param currencyOut the desired currency out
712
+ * @param maxNumResults maximum number of results to return
713
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
714
+ * @param currentPairs used in recursion; the current list of pairs
715
+ * @param currencyAmountIn used in recursion; the original value of the currencyAmountIn parameter
716
+ * @param bestTrades used in recursion; the current list of best trades
717
+ */;
718
+ Trade.bestTradeExactIn = function bestTradeExactIn(pairs, currencyAmountIn, currencyOut, _temp,
719
+ // used in recursion.
720
+ currentPairs, nextAmountIn, bestTrades) {
721
+ var _ref = _temp === void 0 ? {} : _temp,
722
+ _ref$maxNumResults = _ref.maxNumResults,
723
+ maxNumResults = _ref$maxNumResults === void 0 ? 3 : _ref$maxNumResults,
724
+ _ref$maxHops = _ref.maxHops,
725
+ maxHops = _ref$maxHops === void 0 ? 3 : _ref$maxHops;
726
+ if (currentPairs === void 0) {
727
+ currentPairs = [];
728
+ }
729
+ if (nextAmountIn === void 0) {
730
+ nextAmountIn = currencyAmountIn;
731
+ }
732
+ if (bestTrades === void 0) {
733
+ bestTrades = [];
734
+ }
735
+ !(pairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PAIRS') : invariant(false) : void 0;
736
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
737
+ !(currencyAmountIn === nextAmountIn || currentPairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
738
+ var amountIn = nextAmountIn.wrapped;
739
+ var tokenOut = currencyOut.wrapped;
740
+ for (var i = 0; i < pairs.length; i++) {
741
+ var pair = pairs[i];
742
+ // pair irrelevant
743
+ if (!pair.token0.equals(amountIn.currency) && !pair.token1.equals(amountIn.currency)) continue;
744
+ if (pair.reserve0.equalTo(ZERO) || pair.reserve1.equalTo(ZERO)) continue;
745
+ var amountOut = void 0;
746
+ try {
747
+ ;
748
+ var _pair$getOutputAmount2 = pair.getOutputAmount(amountIn);
749
+ amountOut = _pair$getOutputAmount2[0];
750
+ } catch (error) {
751
+ // input too low
752
+ if (error.isInsufficientInputAmountError) {
753
+ continue;
754
+ }
755
+ throw error;
756
+ }
757
+ // we have arrived at the output token, so this is the final trade of one of the paths
758
+ if (amountOut.currency.equals(tokenOut)) {
759
+ sortedInsert(bestTrades, new Trade(new Route([].concat(currentPairs, [pair]), currencyAmountIn.currency, currencyOut), currencyAmountIn, TradeType.EXACT_INPUT), maxNumResults, tradeComparator);
760
+ } else if (maxHops > 1 && pairs.length > 1) {
761
+ var pairsExcludingThisPair = pairs.slice(0, i).concat(pairs.slice(i + 1, pairs.length));
762
+
763
+ // otherwise, consider all the other paths that lead from this token as long as we have not exceeded maxHops
764
+ Trade.bestTradeExactIn(pairsExcludingThisPair, currencyAmountIn, currencyOut, {
765
+ maxNumResults: maxNumResults,
766
+ maxHops: maxHops - 1
767
+ }, [].concat(currentPairs, [pair]), amountOut, bestTrades);
768
+ }
769
+ }
770
+ return bestTrades;
771
+ }
772
+
773
+ /**
774
+ * Return the execution price after accounting for slippage tolerance
775
+ * @param slippageTolerance the allowed tolerated slippage
776
+ */;
777
+ _proto.worstExecutionPrice = function worstExecutionPrice(slippageTolerance) {
778
+ return new Price(this.inputAmount.currency, this.outputAmount.currency, this.maximumAmountIn(slippageTolerance).quotient, this.minimumAmountOut(slippageTolerance).quotient);
779
+ }
780
+
781
+ /**
782
+ * similar to the above method but instead targets a fixed output amount
783
+ * given a list of pairs, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
784
+ * to an output token amount, making at most `maxHops` hops
785
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
786
+ * the amount in among multiple routes.
787
+ * @param pairs the pairs to consider in finding the best trade
788
+ * @param currencyIn the currency to spend
789
+ * @param nextAmountOut the exact amount of currency out
790
+ * @param maxNumResults maximum number of results to return
791
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
792
+ * @param currentPairs used in recursion; the current list of pairs
793
+ * @param currencyAmountOut used in recursion; the original value of the currencyAmountOut parameter
794
+ * @param bestTrades used in recursion; the current list of best trades
795
+ */;
796
+ Trade.bestTradeExactOut = function bestTradeExactOut(pairs, currencyIn, currencyAmountOut, _temp2,
797
+ // used in recursion.
798
+ currentPairs, nextAmountOut, bestTrades) {
799
+ var _ref2 = _temp2 === void 0 ? {} : _temp2,
800
+ _ref2$maxNumResults = _ref2.maxNumResults,
801
+ maxNumResults = _ref2$maxNumResults === void 0 ? 3 : _ref2$maxNumResults,
802
+ _ref2$maxHops = _ref2.maxHops,
803
+ maxHops = _ref2$maxHops === void 0 ? 3 : _ref2$maxHops;
804
+ if (currentPairs === void 0) {
805
+ currentPairs = [];
806
+ }
807
+ if (nextAmountOut === void 0) {
808
+ nextAmountOut = currencyAmountOut;
809
+ }
810
+ if (bestTrades === void 0) {
811
+ bestTrades = [];
812
+ }
813
+ !(pairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PAIRS') : invariant(false) : void 0;
814
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
815
+ !(currencyAmountOut === nextAmountOut || currentPairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
816
+ var amountOut = nextAmountOut.wrapped;
817
+ var tokenIn = currencyIn.wrapped;
818
+ for (var i = 0; i < pairs.length; i++) {
819
+ var pair = pairs[i];
820
+ // pair irrelevant
821
+ if (!pair.token0.equals(amountOut.currency) && !pair.token1.equals(amountOut.currency)) continue;
822
+ if (pair.reserve0.equalTo(ZERO) || pair.reserve1.equalTo(ZERO)) continue;
823
+ var amountIn = void 0;
824
+ try {
825
+ ;
826
+ var _pair$getInputAmount2 = pair.getInputAmount(amountOut);
827
+ amountIn = _pair$getInputAmount2[0];
828
+ } catch (error) {
829
+ // not enough liquidity in this pair
830
+ if (error.isInsufficientReservesError) {
831
+ continue;
832
+ }
833
+ throw error;
834
+ }
835
+ // we have arrived at the input token, so this is the first trade of one of the paths
836
+ if (amountIn.currency.equals(tokenIn)) {
837
+ sortedInsert(bestTrades, new Trade(new Route([pair].concat(currentPairs), currencyIn, currencyAmountOut.currency), currencyAmountOut, TradeType.EXACT_OUTPUT), maxNumResults, tradeComparator);
838
+ } else if (maxHops > 1 && pairs.length > 1) {
839
+ var pairsExcludingThisPair = pairs.slice(0, i).concat(pairs.slice(i + 1, pairs.length));
840
+
841
+ // otherwise, consider all the other paths that arrive at this token as long as we have not exceeded maxHops
842
+ Trade.bestTradeExactOut(pairsExcludingThisPair, currencyIn, currencyAmountOut, {
843
+ maxNumResults: maxNumResults,
844
+ maxHops: maxHops - 1
845
+ }, [pair].concat(currentPairs), amountIn, bestTrades);
846
+ }
847
+ }
848
+ return bestTrades;
849
+ };
850
+ return Trade;
851
+ }();
852
+
853
+ /**
854
+ * Options for producing the arguments to send call to the router.
855
+ */
856
+
857
+ /**
858
+ * The parameters to use in the call to the Uniswap V2 Router to execute a trade.
859
+ */
860
+
861
+ function toHex(currencyAmount) {
862
+ return "0x" + currencyAmount.quotient.toString(16);
863
+ }
864
+ var ZERO_HEX = '0x0';
865
+
866
+ /**
867
+ * Represents the Uniswap V2 Router, and has static methods for helping execute trades.
868
+ */
869
+ var Router = /*#__PURE__*/function () {
870
+ /**
871
+ * Cannot be constructed.
872
+ */
873
+ function Router() {}
874
+ /**
875
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
876
+ * @param trade to produce call parameters for
877
+ * @param options options for the call parameters
878
+ */
879
+ Router.swapCallParameters = function swapCallParameters(trade, options) {
880
+ var etherIn = trade.inputAmount.currency.isNative;
881
+ var etherOut = trade.outputAmount.currency.isNative;
882
+ // the router does not support both ether in and out
883
+ !!(etherIn && etherOut) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ETHER_IN_OUT') : invariant(false) : void 0;
884
+ !(!('ttl' in options) || options.ttl > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TTL') : invariant(false) : void 0;
885
+ var to = validateAndParseAddress(options.recipient);
886
+ var amountIn = toHex(trade.maximumAmountIn(options.allowedSlippage));
887
+ var amountOut = toHex(trade.minimumAmountOut(options.allowedSlippage));
888
+ var path = trade.route.path.map(function (token) {
889
+ return token.address;
890
+ });
891
+ var deadline = 'ttl' in options ? "0x" + (Math.floor(new Date().getTime() / 1000) + options.ttl).toString(16) : "0x" + options.deadline.toString(16);
892
+ var useFeeOnTransfer = Boolean(options.feeOnTransfer);
893
+ var methodName;
894
+ var args;
895
+ var value;
896
+ switch (trade.tradeType) {
897
+ case TradeType.EXACT_INPUT:
898
+ if (etherIn) {
899
+ methodName = useFeeOnTransfer ? 'swapExactETHForTokensSupportingFeeOnTransferTokens' : 'swapExactETHForTokens';
900
+ // (uint amountOutMin, address[] calldata path, address to, uint deadline)
901
+ args = [amountOut, path, to, deadline];
902
+ value = amountIn;
903
+ } else if (etherOut) {
904
+ methodName = useFeeOnTransfer ? 'swapExactTokensForETHSupportingFeeOnTransferTokens' : 'swapExactTokensForETH';
905
+ // (uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
906
+ args = [amountIn, amountOut, path, to, deadline];
907
+ value = ZERO_HEX;
908
+ } else {
909
+ methodName = useFeeOnTransfer ? 'swapExactTokensForTokensSupportingFeeOnTransferTokens' : 'swapExactTokensForTokens';
910
+ // (uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
911
+ args = [amountIn, amountOut, path, to, deadline];
912
+ value = ZERO_HEX;
913
+ }
914
+ break;
915
+ case TradeType.EXACT_OUTPUT:
916
+ !!useFeeOnTransfer ? process.env.NODE_ENV !== "production" ? invariant(false, 'EXACT_OUT_FOT') : invariant(false) : void 0;
917
+ if (etherIn) {
918
+ methodName = 'swapETHForExactTokens';
919
+ // (uint amountOut, address[] calldata path, address to, uint deadline)
920
+ args = [amountOut, path, to, deadline];
921
+ value = amountIn;
922
+ } else if (etherOut) {
923
+ methodName = 'swapTokensForExactETH';
924
+ // (uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
925
+ args = [amountOut, amountIn, path, to, deadline];
926
+ value = ZERO_HEX;
927
+ } else {
928
+ methodName = 'swapTokensForExactTokens';
929
+ // (uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
930
+ args = [amountOut, amountIn, path, to, deadline];
931
+ value = ZERO_HEX;
932
+ }
933
+ break;
934
+ }
935
+ return {
936
+ methodName: methodName,
937
+ args: args,
938
+ value: value
939
+ };
940
+ };
941
+ return Router;
942
+ }();
943
+
944
+ export { FACTORY_ADDRESS_MAP, INIT_CODE_HASH, InsufficientInputAmountError, InsufficientReservesError, MINIMUM_LIQUIDITY, Pair, Route, Router, Trade, computePairAddress, inputOutputComparator, tradeComparator };
945
+ //# sourceMappingURL=v2-sdk.esm.js.map