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