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