@kayenfi/v2-sdk 0.0.1

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