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