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