@ring-protocol/v2-sdk 0.1.0

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