@juiceswapxyz/v2-sdk 3.0.0 → 3.0.1

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