@kayenfinance/v2-sdk 0.0.1

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