@kayenfinance/v2-sdk 1.2.2 → 1.2.3

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