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