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