@crosswise-finance1/sdk-v2 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.
Files changed (38) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -0
  3. package/dist/constants.d.ts +41 -0
  4. package/dist/entities/currency.d.ts +23 -0
  5. package/dist/entities/fractions/currencyAmount.d.ts +19 -0
  6. package/dist/entities/fractions/fraction.d.ts +19 -0
  7. package/dist/entities/fractions/index.d.ts +5 -0
  8. package/dist/entities/fractions/percent.d.ts +6 -0
  9. package/dist/entities/fractions/price.d.ts +19 -0
  10. package/dist/entities/fractions/tokenAmount.d.ts +9 -0
  11. package/dist/entities/index.d.ts +6 -0
  12. package/dist/entities/pair.d.ts +41 -0
  13. package/dist/entities/route.d.ts +14 -0
  14. package/dist/entities/token.d.ts +31 -0
  15. package/dist/entities/trade.d.ts +106 -0
  16. package/dist/errors.d.ts +16 -0
  17. package/dist/fetcher.d.ts +28 -0
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +8 -0
  20. package/dist/router.d.ts +63 -0
  21. package/dist/sdk-v2.cjs.development.js +1604 -0
  22. package/dist/sdk-v2.cjs.development.js.map +1 -0
  23. package/dist/sdk-v2.cjs.production.min.js +2 -0
  24. package/dist/sdk-v2.cjs.production.min.js.map +1 -0
  25. package/dist/sdk-v2.esm.js +1582 -0
  26. package/dist/sdk-v2.esm.js.map +1 -0
  27. package/dist/test/constants.test.d.ts +1 -0
  28. package/dist/test/data.test.d.ts +1 -0
  29. package/dist/test/entities.test.d.ts +1 -0
  30. package/dist/test/fraction.test.d.ts +1 -0
  31. package/dist/test/miscellaneous.test.d.ts +1 -0
  32. package/dist/test/pair.test.d.ts +1 -0
  33. package/dist/test/route.test.d.ts +1 -0
  34. package/dist/test/router.test.d.ts +1 -0
  35. package/dist/test/token.test.d.ts +1 -0
  36. package/dist/test/trade.test.d.ts +1 -0
  37. package/dist/utils.d.ts +7 -0
  38. package/package.json +62 -0
@@ -0,0 +1,1582 @@
1
+ import JSBI from 'jsbi';
2
+ export { default as JSBI } from 'jsbi';
3
+ import invariant from 'tiny-invariant';
4
+ import warning from 'tiny-warning';
5
+ import { getAddress, getCreate2Address } from '@ethersproject/address';
6
+ import _Big from 'big.js';
7
+ import toFormat from 'toformat';
8
+ import _Decimal from 'decimal.js-light';
9
+ import { keccak256, pack } from '@ethersproject/solidity';
10
+ import { Contract } from '@ethersproject/contracts';
11
+ import { getNetwork } from '@ethersproject/networks';
12
+ import { getDefaultProvider } from '@ethersproject/providers';
13
+ import IPancakePair from '@pancakeswap-libs/pancake-swap-core/build/IPancakePair.json';
14
+
15
+ var _FACTORY_ADDRESS, _INIT_CODE_HASH, _SOLIDITY_TYPE_MAXIMA;
16
+ var ChainId;
17
+
18
+ (function (ChainId) {
19
+ ChainId[ChainId["MAINNET"] = 56] = "MAINNET";
20
+ ChainId[ChainId["TESTNET"] = 97] = "TESTNET";
21
+ })(ChainId || (ChainId = {}));
22
+
23
+ var TradeType;
24
+
25
+ (function (TradeType) {
26
+ TradeType[TradeType["EXACT_INPUT"] = 0] = "EXACT_INPUT";
27
+ TradeType[TradeType["EXACT_OUTPUT"] = 1] = "EXACT_OUTPUT";
28
+ })(TradeType || (TradeType = {}));
29
+
30
+ var Rounding;
31
+
32
+ (function (Rounding) {
33
+ Rounding[Rounding["ROUND_DOWN"] = 0] = "ROUND_DOWN";
34
+ Rounding[Rounding["ROUND_HALF_UP"] = 1] = "ROUND_HALF_UP";
35
+ Rounding[Rounding["ROUND_UP"] = 2] = "ROUND_UP";
36
+ })(Rounding || (Rounding = {}));
37
+
38
+ var FACTORY_ADDRESS = (_FACTORY_ADDRESS = {}, _FACTORY_ADDRESS[ChainId.MAINNET] = '0x47b30B5eD46101473ED2AEc7b9046aaCb6fd4bBC', _FACTORY_ADDRESS[ChainId.TESTNET] = '0x79436975DcD97893732BbE2422DB0137E977B0fD', _FACTORY_ADDRESS); // export const INIT_CODE_HASH = '0xc7f24a213a5242f06ef67ceacbe69c94319427889cde21b4269af8b8afe52163'
39
+ // export const INIT_CODE_HASH = '0x273b6c5d4a2e1e12f680c1c82ac31e00b39f0f5578954a8a8b7dca84b98bf273'
40
+
41
+ var INIT_CODE_HASH = (_INIT_CODE_HASH = {}, _INIT_CODE_HASH[ChainId.MAINNET] = '0xb57d471479b9c504aef8c74dfa1f516be4a744bc7354ef20bedff76cd1de274a', _INIT_CODE_HASH[ChainId.TESTNET] = '0x355c7eb3cf8d9317ff55f1d8e6e6b2c8067b97dcdbabab44ab2e194ca85c9783', _INIT_CODE_HASH);
42
+ var MINIMUM_LIQUIDITY = /*#__PURE__*/JSBI.BigInt(1000); // exports for internal consumption
43
+
44
+ var ZERO = /*#__PURE__*/JSBI.BigInt(0);
45
+ var ONE = /*#__PURE__*/JSBI.BigInt(1);
46
+ var TWO = /*#__PURE__*/JSBI.BigInt(2);
47
+ var THREE = /*#__PURE__*/JSBI.BigInt(3);
48
+ var FIVE = /*#__PURE__*/JSBI.BigInt(5);
49
+ var TEN = /*#__PURE__*/JSBI.BigInt(10);
50
+ var _100 = /*#__PURE__*/JSBI.BigInt(100);
51
+ var FEES_NUMERATOR = /*#__PURE__*/JSBI.BigInt(9975);
52
+ var FEES_DENOMINATOR = /*#__PURE__*/JSBI.BigInt(10000);
53
+ var SolidityType;
54
+
55
+ (function (SolidityType) {
56
+ SolidityType["uint8"] = "uint8";
57
+ SolidityType["uint256"] = "uint256";
58
+ })(SolidityType || (SolidityType = {}));
59
+
60
+ var SOLIDITY_TYPE_MAXIMA = (_SOLIDITY_TYPE_MAXIMA = {}, _SOLIDITY_TYPE_MAXIMA[SolidityType.uint8] = /*#__PURE__*/JSBI.BigInt('0xff'), _SOLIDITY_TYPE_MAXIMA[SolidityType.uint256] = /*#__PURE__*/JSBI.BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'), _SOLIDITY_TYPE_MAXIMA);
61
+
62
+ function _defineProperties(target, props) {
63
+ for (var i = 0; i < props.length; i++) {
64
+ var descriptor = props[i];
65
+ descriptor.enumerable = descriptor.enumerable || false;
66
+ descriptor.configurable = true;
67
+ if ("value" in descriptor) descriptor.writable = true;
68
+ Object.defineProperty(target, descriptor.key, descriptor);
69
+ }
70
+ }
71
+
72
+ function _createClass(Constructor, protoProps, staticProps) {
73
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
74
+ if (staticProps) _defineProperties(Constructor, staticProps);
75
+ return Constructor;
76
+ }
77
+
78
+ function _extends() {
79
+ _extends = Object.assign || function (target) {
80
+ for (var i = 1; i < arguments.length; i++) {
81
+ var source = arguments[i];
82
+
83
+ for (var key in source) {
84
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
85
+ target[key] = source[key];
86
+ }
87
+ }
88
+ }
89
+
90
+ return target;
91
+ };
92
+
93
+ return _extends.apply(this, arguments);
94
+ }
95
+
96
+ function _inheritsLoose(subClass, superClass) {
97
+ subClass.prototype = Object.create(superClass.prototype);
98
+ subClass.prototype.constructor = subClass;
99
+
100
+ _setPrototypeOf(subClass, superClass);
101
+ }
102
+
103
+ function _getPrototypeOf(o) {
104
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
105
+ return o.__proto__ || Object.getPrototypeOf(o);
106
+ };
107
+ return _getPrototypeOf(o);
108
+ }
109
+
110
+ function _setPrototypeOf(o, p) {
111
+ _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
112
+ o.__proto__ = p;
113
+ return o;
114
+ };
115
+
116
+ return _setPrototypeOf(o, p);
117
+ }
118
+
119
+ function _isNativeReflectConstruct() {
120
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
121
+ if (Reflect.construct.sham) return false;
122
+ if (typeof Proxy === "function") return true;
123
+
124
+ try {
125
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
126
+ return true;
127
+ } catch (e) {
128
+ return false;
129
+ }
130
+ }
131
+
132
+ function _construct(Parent, args, Class) {
133
+ if (_isNativeReflectConstruct()) {
134
+ _construct = Reflect.construct;
135
+ } else {
136
+ _construct = function _construct(Parent, args, Class) {
137
+ var a = [null];
138
+ a.push.apply(a, args);
139
+ var Constructor = Function.bind.apply(Parent, a);
140
+ var instance = new Constructor();
141
+ if (Class) _setPrototypeOf(instance, Class.prototype);
142
+ return instance;
143
+ };
144
+ }
145
+
146
+ return _construct.apply(null, arguments);
147
+ }
148
+
149
+ function _isNativeFunction(fn) {
150
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
151
+ }
152
+
153
+ function _wrapNativeSuper(Class) {
154
+ var _cache = typeof Map === "function" ? new Map() : undefined;
155
+
156
+ _wrapNativeSuper = function _wrapNativeSuper(Class) {
157
+ if (Class === null || !_isNativeFunction(Class)) return Class;
158
+
159
+ if (typeof Class !== "function") {
160
+ throw new TypeError("Super expression must either be null or a function");
161
+ }
162
+
163
+ if (typeof _cache !== "undefined") {
164
+ if (_cache.has(Class)) return _cache.get(Class);
165
+
166
+ _cache.set(Class, Wrapper);
167
+ }
168
+
169
+ function Wrapper() {
170
+ return _construct(Class, arguments, _getPrototypeOf(this).constructor);
171
+ }
172
+
173
+ Wrapper.prototype = Object.create(Class.prototype, {
174
+ constructor: {
175
+ value: Wrapper,
176
+ enumerable: false,
177
+ writable: true,
178
+ configurable: true
179
+ }
180
+ });
181
+ return _setPrototypeOf(Wrapper, Class);
182
+ };
183
+
184
+ return _wrapNativeSuper(Class);
185
+ }
186
+
187
+ function _assertThisInitialized(self) {
188
+ if (self === void 0) {
189
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
190
+ }
191
+
192
+ return self;
193
+ }
194
+
195
+ function _unsupportedIterableToArray(o, minLen) {
196
+ if (!o) return;
197
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
198
+ var n = Object.prototype.toString.call(o).slice(8, -1);
199
+ if (n === "Object" && o.constructor) n = o.constructor.name;
200
+ if (n === "Map" || n === "Set") return Array.from(o);
201
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
202
+ }
203
+
204
+ function _arrayLikeToArray(arr, len) {
205
+ if (len == null || len > arr.length) len = arr.length;
206
+
207
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
208
+
209
+ return arr2;
210
+ }
211
+
212
+ function _createForOfIteratorHelperLoose(o, allowArrayLike) {
213
+ var it;
214
+
215
+ if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
216
+ if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
217
+ if (it) o = it;
218
+ var i = 0;
219
+ return function () {
220
+ if (i >= o.length) return {
221
+ done: true
222
+ };
223
+ return {
224
+ done: false,
225
+ value: o[i++]
226
+ };
227
+ };
228
+ }
229
+
230
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
231
+ }
232
+
233
+ it = o[Symbol.iterator]();
234
+ return it.next.bind(it);
235
+ }
236
+
237
+ // see https://stackoverflow.com/a/41102306
238
+ var CAN_SET_PROTOTYPE = ('setPrototypeOf' in Object);
239
+ /**
240
+ * Indicates that the pair has insufficient reserves for a desired output amount. I.e. the amount of output cannot be
241
+ * obtained by sending any amount of input.
242
+ */
243
+
244
+ var InsufficientReservesError = /*#__PURE__*/function (_Error) {
245
+ _inheritsLoose(InsufficientReservesError, _Error);
246
+
247
+ function InsufficientReservesError() {
248
+ var _this;
249
+
250
+ _this = _Error.call(this) || this;
251
+ _this.isInsufficientReservesError = true;
252
+ _this.name = _this.constructor.name;
253
+ if (CAN_SET_PROTOTYPE) Object.setPrototypeOf(_assertThisInitialized(_this), (this instanceof InsufficientReservesError ? this.constructor : void 0).prototype);
254
+ return _this;
255
+ }
256
+
257
+ return InsufficientReservesError;
258
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
259
+ /**
260
+ * Indicates that the input amount is too small to produce any amount of output. I.e. the amount of input sent is less
261
+ * than the price of a single unit of output after fees.
262
+ */
263
+
264
+ var InsufficientInputAmountError = /*#__PURE__*/function (_Error2) {
265
+ _inheritsLoose(InsufficientInputAmountError, _Error2);
266
+
267
+ function InsufficientInputAmountError() {
268
+ var _this2;
269
+
270
+ _this2 = _Error2.call(this) || this;
271
+ _this2.isInsufficientInputAmountError = true;
272
+ _this2.name = _this2.constructor.name;
273
+ if (CAN_SET_PROTOTYPE) Object.setPrototypeOf(_assertThisInitialized(_this2), (this instanceof InsufficientInputAmountError ? this.constructor : void 0).prototype);
274
+ return _this2;
275
+ }
276
+
277
+ return InsufficientInputAmountError;
278
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
279
+
280
+ function validateSolidityTypeInstance(value, solidityType) {
281
+ !JSBI.greaterThanOrEqual(value, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, value + " is not a " + solidityType + ".") : invariant(false) : void 0;
282
+ !JSBI.lessThanOrEqual(value, SOLIDITY_TYPE_MAXIMA[solidityType]) ? process.env.NODE_ENV !== "production" ? invariant(false, value + " is not a " + solidityType + ".") : invariant(false) : void 0;
283
+ } // warns if addresses are not checksummed
284
+
285
+ function validateAndParseAddress(address) {
286
+ try {
287
+ var checksummedAddress = getAddress(address);
288
+ process.env.NODE_ENV !== "production" ? warning(address === checksummedAddress, address + " is not checksummed.") : void 0;
289
+ return checksummedAddress;
290
+ } catch (error) {
291
+ process.env.NODE_ENV !== "production" ? invariant(false, address + " is not a valid address.") : invariant(false) ;
292
+ }
293
+ }
294
+ function parseBigintIsh(bigintIsh) {
295
+ return bigintIsh instanceof JSBI ? bigintIsh : typeof bigintIsh === 'bigint' ? JSBI.BigInt(bigintIsh.toString()) : JSBI.BigInt(bigintIsh);
296
+ } // mock the on-chain sqrt function
297
+
298
+ function sqrt(y) {
299
+ validateSolidityTypeInstance(y, SolidityType.uint256);
300
+ var z = ZERO;
301
+ var x;
302
+
303
+ if (JSBI.greaterThan(y, THREE)) {
304
+ z = y;
305
+ x = JSBI.add(JSBI.divide(y, TWO), ONE);
306
+
307
+ while (JSBI.lessThan(x, z)) {
308
+ z = x;
309
+ x = JSBI.divide(JSBI.add(JSBI.divide(y, x), x), TWO);
310
+ }
311
+ } else if (JSBI.notEqual(y, ZERO)) {
312
+ z = ONE;
313
+ }
314
+
315
+ return z;
316
+ } // given an array of items sorted by `comparator`, insert an item into its sort index and constrain the size to
317
+ // `maxSize` by removing the last item
318
+
319
+ function sortedInsert(items, add, maxSize, comparator) {
320
+ !(maxSize > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_SIZE_ZERO') : invariant(false) : void 0; // this is an invariant because the interface cannot return multiple removed items if items.length exceeds maxSize
321
+
322
+ !(items.length <= maxSize) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ITEMS_SIZE') : invariant(false) : void 0; // short circuit first item add
323
+
324
+ if (items.length === 0) {
325
+ items.push(add);
326
+ return null;
327
+ } else {
328
+ var isFull = items.length === maxSize; // short circuit if full and the additional item does not come before the last item
329
+
330
+ if (isFull && comparator(items[items.length - 1], add) <= 0) {
331
+ return add;
332
+ }
333
+
334
+ var lo = 0,
335
+ hi = items.length;
336
+
337
+ while (lo < hi) {
338
+ var mid = lo + hi >>> 1;
339
+
340
+ if (comparator(items[mid], add) <= 0) {
341
+ lo = mid + 1;
342
+ } else {
343
+ hi = mid;
344
+ }
345
+ }
346
+
347
+ items.splice(lo, 0, add);
348
+ return isFull ? items.pop() : null;
349
+ }
350
+ }
351
+
352
+ /**
353
+ * A currency is any fungible financial instrument on Ethereum, including Ether and all ERC20 tokens.
354
+ *
355
+ * The only instance of the base class `Currency` is Ether.
356
+ */
357
+
358
+ var Currency =
359
+ /**
360
+ * Constructs an instance of the base class `Currency`. The only instance of the base class `Currency` is `Currency.ETHER`.
361
+ * @param decimals decimals of the currency
362
+ * @param symbol symbol of the currency
363
+ * @param name of the currency
364
+ */
365
+ function Currency(decimals, symbol, name) {
366
+ validateSolidityTypeInstance(JSBI.BigInt(decimals), SolidityType.uint8);
367
+ this.decimals = decimals;
368
+ this.symbol = symbol;
369
+ this.name = name;
370
+ };
371
+ /**
372
+ * The only instance of the base class `Currency`.
373
+ */
374
+
375
+ Currency.ETHER = /*#__PURE__*/new Currency(18, 'BNB', 'BNB');
376
+ var ETHER = Currency.ETHER;
377
+
378
+ var _WETH;
379
+ /**
380
+ * Represents an ERC20 token with a unique address and some metadata.
381
+ */
382
+
383
+ var Token = /*#__PURE__*/function (_Currency) {
384
+ _inheritsLoose(Token, _Currency);
385
+
386
+ function Token(chainId, address, decimals, symbol, name, projectLink) {
387
+ var _this;
388
+
389
+ _this = _Currency.call(this, decimals, symbol, name) || this;
390
+ _this.chainId = chainId;
391
+ _this.address = validateAndParseAddress(address);
392
+ _this.projectLink = projectLink;
393
+ return _this;
394
+ }
395
+ /**
396
+ * Returns true if the two tokens are equivalent, i.e. have the same chainId and address.
397
+ * @param other other token to compare
398
+ */
399
+
400
+
401
+ var _proto = Token.prototype;
402
+
403
+ _proto.equals = function equals(other) {
404
+ // short circuit on reference equality
405
+ if (this === other) {
406
+ return true;
407
+ }
408
+
409
+ return this.chainId === other.chainId && this.address === other.address;
410
+ }
411
+ /**
412
+ * Returns true if the address of this token sorts before the address of the other token
413
+ * @param other other token to compare
414
+ * @throws if the tokens have the same address
415
+ * @throws if the tokens are on different chains
416
+ */
417
+ ;
418
+
419
+ _proto.sortsBefore = function sortsBefore(other) {
420
+ !(this.chainId === other.chainId) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0;
421
+ !(this.address !== other.address) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ADDRESSES') : invariant(false) : void 0;
422
+ return this.address.toLowerCase() < other.address.toLowerCase();
423
+ };
424
+
425
+ return Token;
426
+ }(Currency);
427
+ /**
428
+ * Compares two currencies for equality
429
+ */
430
+
431
+ function currencyEquals(currencyA, currencyB) {
432
+ if (currencyA instanceof Token && currencyB instanceof Token) {
433
+ return currencyA.equals(currencyB);
434
+ } else if (currencyA instanceof Token) {
435
+ return false;
436
+ } else if (currencyB instanceof Token) {
437
+ return false;
438
+ } else {
439
+ return currencyA === currencyB;
440
+ }
441
+ }
442
+ var WETH = (_WETH = {}, _WETH[ChainId.MAINNET] = /*#__PURE__*/new Token(ChainId.MAINNET, '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', 18, 'WBNB', 'Wrapped BNB', 'https://www.binance.org'), _WETH[ChainId.TESTNET] = /*#__PURE__*/new Token(ChainId.TESTNET, '0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd', 18, 'WBNB', 'Wrapped BNB', 'https://www.binance.org'), _WETH);
443
+
444
+ var _toSignificantRoundin, _toFixedRounding;
445
+ var Decimal = /*#__PURE__*/toFormat(_Decimal);
446
+ var Big = /*#__PURE__*/toFormat(_Big);
447
+ var toSignificantRounding = (_toSignificantRoundin = {}, _toSignificantRoundin[Rounding.ROUND_DOWN] = Decimal.ROUND_DOWN, _toSignificantRoundin[Rounding.ROUND_HALF_UP] = Decimal.ROUND_HALF_UP, _toSignificantRoundin[Rounding.ROUND_UP] = Decimal.ROUND_UP, _toSignificantRoundin);
448
+ var toFixedRounding = (_toFixedRounding = {}, _toFixedRounding[Rounding.ROUND_DOWN] = 0, _toFixedRounding[Rounding.ROUND_HALF_UP] = 1, _toFixedRounding[Rounding.ROUND_UP] = 3, _toFixedRounding);
449
+ var Fraction = /*#__PURE__*/function () {
450
+ function Fraction(numerator, denominator) {
451
+ if (denominator === void 0) {
452
+ denominator = ONE;
453
+ }
454
+
455
+ this.numerator = parseBigintIsh(numerator);
456
+ this.denominator = parseBigintIsh(denominator);
457
+ } // performs floor division
458
+
459
+
460
+ var _proto = Fraction.prototype;
461
+
462
+ _proto.invert = function invert() {
463
+ return new Fraction(this.denominator, this.numerator);
464
+ };
465
+
466
+ _proto.add = function add(other) {
467
+ var otherParsed = other instanceof Fraction ? other : new Fraction(parseBigintIsh(other));
468
+
469
+ if (JSBI.equal(this.denominator, otherParsed.denominator)) {
470
+ return new Fraction(JSBI.add(this.numerator, otherParsed.numerator), this.denominator);
471
+ }
472
+
473
+ return new Fraction(JSBI.add(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)), JSBI.multiply(this.denominator, otherParsed.denominator));
474
+ };
475
+
476
+ _proto.subtract = function subtract(other) {
477
+ var otherParsed = other instanceof Fraction ? other : new Fraction(parseBigintIsh(other));
478
+
479
+ if (JSBI.equal(this.denominator, otherParsed.denominator)) {
480
+ return new Fraction(JSBI.subtract(this.numerator, otherParsed.numerator), this.denominator);
481
+ }
482
+
483
+ return new Fraction(JSBI.subtract(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)), JSBI.multiply(this.denominator, otherParsed.denominator));
484
+ };
485
+
486
+ _proto.lessThan = function lessThan(other) {
487
+ var otherParsed = other instanceof Fraction ? other : new Fraction(parseBigintIsh(other));
488
+ return JSBI.lessThan(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator));
489
+ };
490
+
491
+ _proto.equalTo = function equalTo(other) {
492
+ var otherParsed = other instanceof Fraction ? other : new Fraction(parseBigintIsh(other));
493
+ return JSBI.equal(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator));
494
+ };
495
+
496
+ _proto.greaterThan = function greaterThan(other) {
497
+ var otherParsed = other instanceof Fraction ? other : new Fraction(parseBigintIsh(other));
498
+ return JSBI.greaterThan(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator));
499
+ };
500
+
501
+ _proto.multiply = function multiply(other) {
502
+ var otherParsed = other instanceof Fraction ? other : new Fraction(parseBigintIsh(other));
503
+ return new Fraction(JSBI.multiply(this.numerator, otherParsed.numerator), JSBI.multiply(this.denominator, otherParsed.denominator));
504
+ };
505
+
506
+ _proto.divide = function divide(other) {
507
+ var otherParsed = other instanceof Fraction ? other : new Fraction(parseBigintIsh(other));
508
+ return new Fraction(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(this.denominator, otherParsed.numerator));
509
+ };
510
+
511
+ _proto.toSignificant = function toSignificant(significantDigits, format, rounding) {
512
+ if (format === void 0) {
513
+ format = {
514
+ groupSeparator: ''
515
+ };
516
+ }
517
+
518
+ if (rounding === void 0) {
519
+ rounding = Rounding.ROUND_HALF_UP;
520
+ }
521
+
522
+ !Number.isInteger(significantDigits) ? process.env.NODE_ENV !== "production" ? invariant(false, significantDigits + " is not an integer.") : invariant(false) : void 0;
523
+ !(significantDigits > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, significantDigits + " is not positive.") : invariant(false) : void 0;
524
+ Decimal.set({
525
+ precision: significantDigits + 1,
526
+ rounding: toSignificantRounding[rounding]
527
+ });
528
+ var quotient = new Decimal(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(significantDigits);
529
+ return quotient.toFormat(quotient.decimalPlaces(), format);
530
+ };
531
+
532
+ _proto.toFixed = function toFixed(decimalPlaces, format, rounding) {
533
+ if (format === void 0) {
534
+ format = {
535
+ groupSeparator: ''
536
+ };
537
+ }
538
+
539
+ if (rounding === void 0) {
540
+ rounding = Rounding.ROUND_HALF_UP;
541
+ }
542
+
543
+ !Number.isInteger(decimalPlaces) ? process.env.NODE_ENV !== "production" ? invariant(false, decimalPlaces + " is not an integer.") : invariant(false) : void 0;
544
+ !(decimalPlaces >= 0) ? process.env.NODE_ENV !== "production" ? invariant(false, decimalPlaces + " is negative.") : invariant(false) : void 0;
545
+ Big.DP = decimalPlaces;
546
+ Big.RM = toFixedRounding[rounding];
547
+ return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(decimalPlaces, format);
548
+ };
549
+
550
+ _createClass(Fraction, [{
551
+ key: "quotient",
552
+ get: function get() {
553
+ return JSBI.divide(this.numerator, this.denominator);
554
+ } // remainder after floor division
555
+
556
+ }, {
557
+ key: "remainder",
558
+ get: function get() {
559
+ return new Fraction(JSBI.remainder(this.numerator, this.denominator), this.denominator);
560
+ }
561
+ }]);
562
+
563
+ return Fraction;
564
+ }();
565
+
566
+ var Big$1 = /*#__PURE__*/toFormat(_Big);
567
+ var CurrencyAmount = /*#__PURE__*/function (_Fraction) {
568
+ _inheritsLoose(CurrencyAmount, _Fraction);
569
+
570
+ // amount _must_ be raw, i.e. in the native representation
571
+ function CurrencyAmount(currency, amount) {
572
+ var _this;
573
+
574
+ var parsedAmount = parseBigintIsh(amount);
575
+ validateSolidityTypeInstance(parsedAmount, SolidityType.uint256);
576
+ _this = _Fraction.call(this, parsedAmount, JSBI.exponentiate(TEN, JSBI.BigInt(currency.decimals))) || this;
577
+ _this.currency = currency;
578
+ return _this;
579
+ }
580
+ /**
581
+ * Helper that calls the constructor with the ETHER currency
582
+ * @param amount ether amount in wei
583
+ */
584
+
585
+
586
+ CurrencyAmount.ether = function ether(amount) {
587
+ return new CurrencyAmount(ETHER, amount);
588
+ };
589
+
590
+ var _proto = CurrencyAmount.prototype;
591
+
592
+ _proto.add = function add(other) {
593
+ !currencyEquals(this.currency, other.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
594
+ return new CurrencyAmount(this.currency, JSBI.add(this.raw, other.raw));
595
+ };
596
+
597
+ _proto.subtract = function subtract(other) {
598
+ !currencyEquals(this.currency, other.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
599
+ return new CurrencyAmount(this.currency, JSBI.subtract(this.raw, other.raw));
600
+ };
601
+
602
+ _proto.toSignificant = function toSignificant(significantDigits, format, rounding) {
603
+ if (significantDigits === void 0) {
604
+ significantDigits = 6;
605
+ }
606
+
607
+ if (rounding === void 0) {
608
+ rounding = Rounding.ROUND_DOWN;
609
+ }
610
+
611
+ return _Fraction.prototype.toSignificant.call(this, significantDigits, format, rounding);
612
+ };
613
+
614
+ _proto.toFixed = function toFixed(decimalPlaces, format, rounding) {
615
+ if (decimalPlaces === void 0) {
616
+ decimalPlaces = this.currency.decimals;
617
+ }
618
+
619
+ if (rounding === void 0) {
620
+ rounding = Rounding.ROUND_DOWN;
621
+ }
622
+
623
+ !(decimalPlaces <= this.currency.decimals) ? process.env.NODE_ENV !== "production" ? invariant(false, 'DECIMALS') : invariant(false) : void 0;
624
+ return _Fraction.prototype.toFixed.call(this, decimalPlaces, format, rounding);
625
+ };
626
+
627
+ _proto.toExact = function toExact(format) {
628
+ if (format === void 0) {
629
+ format = {
630
+ groupSeparator: ''
631
+ };
632
+ }
633
+
634
+ Big$1.DP = this.currency.decimals;
635
+ return new Big$1(this.numerator.toString()).div(this.denominator.toString()).toFormat(format);
636
+ };
637
+
638
+ _createClass(CurrencyAmount, [{
639
+ key: "raw",
640
+ get: function get() {
641
+ return this.numerator;
642
+ }
643
+ }]);
644
+
645
+ return CurrencyAmount;
646
+ }(Fraction);
647
+
648
+ var TokenAmount = /*#__PURE__*/function (_CurrencyAmount) {
649
+ _inheritsLoose(TokenAmount, _CurrencyAmount);
650
+
651
+ // amount _must_ be raw, i.e. in the native representation
652
+ function TokenAmount(token, amount) {
653
+ var _this;
654
+
655
+ _this = _CurrencyAmount.call(this, token, amount) || this;
656
+ _this.token = token;
657
+ return _this;
658
+ }
659
+
660
+ var _proto = TokenAmount.prototype;
661
+
662
+ _proto.add = function add(other) {
663
+ !this.token.equals(other.token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
664
+ return new TokenAmount(this.token, JSBI.add(this.raw, other.raw));
665
+ };
666
+
667
+ _proto.subtract = function subtract(other) {
668
+ !this.token.equals(other.token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
669
+ return new TokenAmount(this.token, JSBI.subtract(this.raw, other.raw));
670
+ };
671
+
672
+ return TokenAmount;
673
+ }(CurrencyAmount);
674
+
675
+ var Price = /*#__PURE__*/function (_Fraction) {
676
+ _inheritsLoose(Price, _Fraction);
677
+
678
+ // denominator and numerator _must_ be raw, i.e. in the native representation
679
+ function Price(baseCurrency, quoteCurrency, denominator, numerator) {
680
+ var _this;
681
+
682
+ _this = _Fraction.call(this, numerator, denominator) || this;
683
+ _this.baseCurrency = baseCurrency;
684
+ _this.quoteCurrency = quoteCurrency;
685
+ _this.scalar = new Fraction(JSBI.exponentiate(TEN, JSBI.BigInt(baseCurrency.decimals)), JSBI.exponentiate(TEN, JSBI.BigInt(quoteCurrency.decimals)));
686
+ return _this;
687
+ }
688
+
689
+ Price.fromRoute = function fromRoute(route) {
690
+ var prices = [];
691
+
692
+ for (var _iterator = _createForOfIteratorHelperLoose(route.pairs.entries()), _step; !(_step = _iterator()).done;) {
693
+ var _step$value = _step.value,
694
+ i = _step$value[0],
695
+ pair = _step$value[1];
696
+ prices.push(route.path[i].equals(pair.token0) ? new Price(pair.reserve0.currency, pair.reserve1.currency, pair.reserve0.raw, pair.reserve1.raw) : new Price(pair.reserve1.currency, pair.reserve0.currency, pair.reserve1.raw, pair.reserve0.raw));
697
+ }
698
+
699
+ return prices.slice(1).reduce(function (accumulator, currentValue) {
700
+ return accumulator.multiply(currentValue);
701
+ }, prices[0]);
702
+ };
703
+
704
+ var _proto = Price.prototype;
705
+
706
+ _proto.invert = function invert() {
707
+ return new Price(this.quoteCurrency, this.baseCurrency, this.numerator, this.denominator);
708
+ };
709
+
710
+ _proto.multiply = function multiply(other) {
711
+ !currencyEquals(this.quoteCurrency, other.baseCurrency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
712
+
713
+ var fraction = _Fraction.prototype.multiply.call(this, other);
714
+
715
+ return new Price(this.baseCurrency, other.quoteCurrency, fraction.denominator, fraction.numerator);
716
+ } // performs floor division on overflow
717
+ ;
718
+
719
+ _proto.quote = function quote(currencyAmount) {
720
+ !currencyEquals(currencyAmount.currency, this.baseCurrency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
721
+
722
+ if (this.quoteCurrency instanceof Token) {
723
+ return new TokenAmount(this.quoteCurrency, _Fraction.prototype.multiply.call(this, currencyAmount.raw).quotient);
724
+ }
725
+
726
+ return CurrencyAmount.ether(_Fraction.prototype.multiply.call(this, currencyAmount.raw).quotient);
727
+ };
728
+
729
+ _proto.toSignificant = function toSignificant(significantDigits, format, rounding) {
730
+ if (significantDigits === void 0) {
731
+ significantDigits = 6;
732
+ }
733
+
734
+ return this.adjusted.toSignificant(significantDigits, format, rounding);
735
+ };
736
+
737
+ _proto.toFixed = function toFixed(decimalPlaces, format, rounding) {
738
+ if (decimalPlaces === void 0) {
739
+ decimalPlaces = 4;
740
+ }
741
+
742
+ return this.adjusted.toFixed(decimalPlaces, format, rounding);
743
+ };
744
+
745
+ _createClass(Price, [{
746
+ key: "raw",
747
+ get: function get() {
748
+ return new Fraction(this.numerator, this.denominator);
749
+ }
750
+ }, {
751
+ key: "adjusted",
752
+ get: function get() {
753
+ return _Fraction.prototype.multiply.call(this, this.scalar);
754
+ }
755
+ }]);
756
+
757
+ return Price;
758
+ }(Fraction);
759
+
760
+ var PAIR_ADDRESS_CACHE = {};
761
+
762
+ var composeKey = function composeKey(token0, token1) {
763
+ return token0.chainId + "-" + token0.address + "-" + token1.address;
764
+ };
765
+
766
+ var Pair = /*#__PURE__*/function () {
767
+ function Pair(tokenAmountA, tokenAmountB) {
768
+ var tokenAmounts = tokenAmountA.token.sortsBefore(tokenAmountB.token) // does safety checks
769
+ ? [tokenAmountA, tokenAmountB] : [tokenAmountB, tokenAmountA];
770
+ this.liquidityToken = new Token(tokenAmounts[0].token.chainId, Pair.getAddress(tokenAmounts[0].token, tokenAmounts[1].token), 18, 'Crss-LP', 'Crosswise LPs');
771
+ this.tokenAmounts = tokenAmounts;
772
+ }
773
+
774
+ Pair.getAddress = function getAddress(tokenA, tokenB) {
775
+ var _PAIR_ADDRESS_CACHE;
776
+
777
+ var tokens = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA]; // does safety checks
778
+
779
+ var chainId = tokenA.chainId;
780
+ var key = composeKey(tokens[0], tokens[1]);
781
+
782
+ if (((_PAIR_ADDRESS_CACHE = PAIR_ADDRESS_CACHE) === null || _PAIR_ADDRESS_CACHE === void 0 ? void 0 : _PAIR_ADDRESS_CACHE[key]) === undefined) {
783
+ var _extends2;
784
+
785
+ PAIR_ADDRESS_CACHE = _extends({}, PAIR_ADDRESS_CACHE, (_extends2 = {}, _extends2[key] = getCreate2Address(FACTORY_ADDRESS[chainId], keccak256(['bytes'], [pack(['address', 'address'], [tokens[0].address, tokens[1].address])]), INIT_CODE_HASH[chainId]), _extends2));
786
+ }
787
+
788
+ return PAIR_ADDRESS_CACHE[key];
789
+ }
790
+ /**
791
+ * Returns true if the token is either token0 or token1
792
+ * @param token to check
793
+ */
794
+ ;
795
+
796
+ var _proto = Pair.prototype;
797
+
798
+ _proto.involvesToken = function involvesToken(token) {
799
+ return token.equals(this.token0) || token.equals(this.token1);
800
+ }
801
+ /**
802
+ * Returns the current mid price of the pair in terms of token0, i.e. the ratio of reserve1 to reserve0
803
+ */
804
+ ;
805
+
806
+ /**
807
+ * Return the price of the given token in terms of the other token in the pair.
808
+ * @param token token to return price of
809
+ */
810
+ _proto.priceOf = function priceOf(token) {
811
+ !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
812
+ return token.equals(this.token0) ? this.token0Price : this.token1Price;
813
+ }
814
+ /**
815
+ * Returns the chain ID of the tokens in the pair.
816
+ */
817
+ ;
818
+
819
+ _proto.reserveOf = function reserveOf(token) {
820
+ !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
821
+ return token.equals(this.token0) ? this.reserve0 : this.reserve1;
822
+ };
823
+
824
+ _proto.getOutputAmount = function getOutputAmount(inputAmount) {
825
+ !this.involvesToken(inputAmount.token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
826
+
827
+ if (JSBI.equal(this.reserve0.raw, ZERO) || JSBI.equal(this.reserve1.raw, ZERO)) {
828
+ throw new InsufficientReservesError();
829
+ }
830
+
831
+ var inputReserve = this.reserveOf(inputAmount.token);
832
+ var outputReserve = this.reserveOf(inputAmount.token.equals(this.token0) ? this.token1 : this.token0);
833
+ var inputAmountWithFee = JSBI.multiply(inputAmount.raw, FEES_NUMERATOR);
834
+ var numerator = JSBI.multiply(inputAmountWithFee, outputReserve.raw);
835
+ var denominator = JSBI.add(JSBI.multiply(inputReserve.raw, FEES_DENOMINATOR), inputAmountWithFee);
836
+ var outputAmount = new TokenAmount(inputAmount.token.equals(this.token0) ? this.token1 : this.token0, JSBI.divide(numerator, denominator));
837
+
838
+ if (JSBI.equal(outputAmount.raw, ZERO)) {
839
+ throw new InsufficientInputAmountError();
840
+ }
841
+
842
+ return [outputAmount, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))];
843
+ };
844
+
845
+ _proto.getInputAmount = function getInputAmount(outputAmount) {
846
+ !this.involvesToken(outputAmount.token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
847
+
848
+ if (JSBI.equal(this.reserve0.raw, ZERO) || JSBI.equal(this.reserve1.raw, ZERO) || JSBI.greaterThanOrEqual(outputAmount.raw, this.reserveOf(outputAmount.token).raw)) {
849
+ throw new InsufficientReservesError();
850
+ }
851
+
852
+ var outputReserve = this.reserveOf(outputAmount.token);
853
+ var inputReserve = this.reserveOf(outputAmount.token.equals(this.token0) ? this.token1 : this.token0);
854
+ var numerator = JSBI.multiply(JSBI.multiply(inputReserve.raw, outputAmount.raw), FEES_DENOMINATOR);
855
+ var denominator = JSBI.multiply(JSBI.subtract(outputReserve.raw, outputAmount.raw), FEES_NUMERATOR);
856
+ var inputAmount = new TokenAmount(outputAmount.token.equals(this.token0) ? this.token1 : this.token0, JSBI.add(JSBI.divide(numerator, denominator), ONE));
857
+ return [inputAmount, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))];
858
+ };
859
+
860
+ _proto.getLiquidityMinted = function getLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB) {
861
+ !totalSupply.token.equals(this.liquidityToken) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LIQUIDITY') : invariant(false) : void 0;
862
+ var tokenAmounts = tokenAmountA.token.sortsBefore(tokenAmountB.token) // does safety checks
863
+ ? [tokenAmountA, tokenAmountB] : [tokenAmountB, tokenAmountA];
864
+ !(tokenAmounts[0].token.equals(this.token0) && tokenAmounts[1].token.equals(this.token1)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
865
+ var liquidity;
866
+
867
+ if (JSBI.equal(totalSupply.raw, ZERO)) {
868
+ liquidity = JSBI.subtract(sqrt(JSBI.multiply(tokenAmounts[0].raw, tokenAmounts[1].raw)), MINIMUM_LIQUIDITY);
869
+ } else {
870
+ var amount0 = JSBI.divide(JSBI.multiply(tokenAmounts[0].raw, totalSupply.raw), this.reserve0.raw);
871
+ var amount1 = JSBI.divide(JSBI.multiply(tokenAmounts[1].raw, totalSupply.raw), this.reserve1.raw);
872
+ liquidity = JSBI.lessThanOrEqual(amount0, amount1) ? amount0 : amount1;
873
+ }
874
+
875
+ if (!JSBI.greaterThan(liquidity, ZERO)) {
876
+ throw new InsufficientInputAmountError();
877
+ }
878
+
879
+ return new TokenAmount(this.liquidityToken, liquidity);
880
+ };
881
+
882
+ _proto.getLiquidityValue = function getLiquidityValue(token, totalSupply, liquidity, feeOn, kLast) {
883
+ if (feeOn === void 0) {
884
+ feeOn = false;
885
+ }
886
+
887
+ !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOKEN') : invariant(false) : void 0;
888
+ !totalSupply.token.equals(this.liquidityToken) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TOTAL_SUPPLY') : invariant(false) : void 0;
889
+ !liquidity.token.equals(this.liquidityToken) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LIQUIDITY') : invariant(false) : void 0;
890
+ !JSBI.lessThanOrEqual(liquidity.raw, totalSupply.raw) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LIQUIDITY') : invariant(false) : void 0;
891
+ var totalSupplyAdjusted;
892
+
893
+ if (!feeOn) {
894
+ totalSupplyAdjusted = totalSupply;
895
+ } else {
896
+ !!!kLast ? process.env.NODE_ENV !== "production" ? invariant(false, 'K_LAST') : invariant(false) : void 0;
897
+ var kLastParsed = parseBigintIsh(kLast);
898
+
899
+ if (!JSBI.equal(kLastParsed, ZERO)) {
900
+ var rootK = sqrt(JSBI.multiply(this.reserve0.raw, this.reserve1.raw));
901
+ var rootKLast = sqrt(kLastParsed);
902
+
903
+ if (JSBI.greaterThan(rootK, rootKLast)) {
904
+ var numerator = JSBI.multiply(totalSupply.raw, JSBI.subtract(rootK, rootKLast));
905
+ var denominator = JSBI.add(JSBI.multiply(rootK, FIVE), rootKLast);
906
+ var feeLiquidity = JSBI.divide(numerator, denominator);
907
+ totalSupplyAdjusted = totalSupply.add(new TokenAmount(this.liquidityToken, feeLiquidity));
908
+ } else {
909
+ totalSupplyAdjusted = totalSupply;
910
+ }
911
+ } else {
912
+ totalSupplyAdjusted = totalSupply;
913
+ }
914
+ }
915
+
916
+ return new TokenAmount(token, JSBI.divide(JSBI.multiply(liquidity.raw, this.reserveOf(token).raw), totalSupplyAdjusted.raw));
917
+ };
918
+
919
+ _createClass(Pair, [{
920
+ key: "token0Price",
921
+ get: function get() {
922
+ return new Price(this.token0, this.token1, this.tokenAmounts[0].raw, this.tokenAmounts[1].raw);
923
+ }
924
+ /**
925
+ * Returns the current mid price of the pair in terms of token1, i.e. the ratio of reserve0 to reserve1
926
+ */
927
+
928
+ }, {
929
+ key: "token1Price",
930
+ get: function get() {
931
+ return new Price(this.token1, this.token0, this.tokenAmounts[1].raw, this.tokenAmounts[0].raw);
932
+ }
933
+ }, {
934
+ key: "chainId",
935
+ get: function get() {
936
+ return this.token0.chainId;
937
+ }
938
+ }, {
939
+ key: "token0",
940
+ get: function get() {
941
+ return this.tokenAmounts[0].token;
942
+ }
943
+ }, {
944
+ key: "token1",
945
+ get: function get() {
946
+ return this.tokenAmounts[1].token;
947
+ }
948
+ }, {
949
+ key: "reserve0",
950
+ get: function get() {
951
+ return this.tokenAmounts[0];
952
+ }
953
+ }, {
954
+ key: "reserve1",
955
+ get: function get() {
956
+ return this.tokenAmounts[1];
957
+ }
958
+ }]);
959
+
960
+ return Pair;
961
+ }();
962
+
963
+ var Route = /*#__PURE__*/function () {
964
+ function Route(pairs, input, output) {
965
+ !(pairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PAIRS') : invariant(false) : void 0;
966
+ !pairs.every(function (pair) {
967
+ return pair.chainId === pairs[0].chainId;
968
+ }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_IDS') : invariant(false) : void 0;
969
+ !(input instanceof Token && pairs[0].involvesToken(input) || input === ETHER && pairs[0].involvesToken(WETH[pairs[0].chainId])) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
970
+ !(typeof output === 'undefined' || output instanceof Token && pairs[pairs.length - 1].involvesToken(output) || output === ETHER && pairs[pairs.length - 1].involvesToken(WETH[pairs[0].chainId])) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
971
+ var path = [input instanceof Token ? input : WETH[pairs[0].chainId]];
972
+
973
+ for (var _iterator = _createForOfIteratorHelperLoose(pairs.entries()), _step; !(_step = _iterator()).done;) {
974
+ var _step$value = _step.value,
975
+ i = _step$value[0],
976
+ pair = _step$value[1];
977
+ var currentInput = path[i];
978
+ !(currentInput.equals(pair.token0) || currentInput.equals(pair.token1)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PATH') : invariant(false) : void 0;
979
+
980
+ var _output = currentInput.equals(pair.token0) ? pair.token1 : pair.token0;
981
+
982
+ path.push(_output);
983
+ }
984
+
985
+ this.pairs = pairs;
986
+ this.path = path;
987
+ this.midPrice = Price.fromRoute(this);
988
+ this.input = input;
989
+ this.output = output !== null && output !== void 0 ? output : path[path.length - 1];
990
+ }
991
+
992
+ _createClass(Route, [{
993
+ key: "chainId",
994
+ get: function get() {
995
+ return this.pairs[0].chainId;
996
+ }
997
+ }]);
998
+
999
+ return Route;
1000
+ }();
1001
+
1002
+ var _100_PERCENT = /*#__PURE__*/new Fraction(_100);
1003
+
1004
+ var Percent = /*#__PURE__*/function (_Fraction) {
1005
+ _inheritsLoose(Percent, _Fraction);
1006
+
1007
+ function Percent() {
1008
+ return _Fraction.apply(this, arguments) || this;
1009
+ }
1010
+
1011
+ var _proto = Percent.prototype;
1012
+
1013
+ _proto.toSignificant = function toSignificant(significantDigits, format, rounding) {
1014
+ if (significantDigits === void 0) {
1015
+ significantDigits = 5;
1016
+ }
1017
+
1018
+ return this.multiply(_100_PERCENT).toSignificant(significantDigits, format, rounding);
1019
+ };
1020
+
1021
+ _proto.toFixed = function toFixed(decimalPlaces, format, rounding) {
1022
+ if (decimalPlaces === void 0) {
1023
+ decimalPlaces = 2;
1024
+ }
1025
+
1026
+ return this.multiply(_100_PERCENT).toFixed(decimalPlaces, format, rounding);
1027
+ };
1028
+
1029
+ return Percent;
1030
+ }(Fraction);
1031
+
1032
+ /**
1033
+ * Returns the percent difference between the mid price and the execution price, i.e. price impact.
1034
+ * @param midPrice mid price before the trade
1035
+ * @param inputAmount the input amount of the trade
1036
+ * @param outputAmount the output amount of the trade
1037
+ */
1038
+
1039
+ function computePriceImpact(midPrice, inputAmount, outputAmount) {
1040
+ var exactQuote = midPrice.raw.multiply(inputAmount.raw); // calculate slippage := (exactQuote - outputAmount) / exactQuote
1041
+
1042
+ var slippage = exactQuote.subtract(outputAmount.raw).divide(exactQuote);
1043
+ return new Percent(slippage.numerator, slippage.denominator);
1044
+ } // comparator function that allows sorting trades by their output amounts, in decreasing order, and then input amounts
1045
+ // in increasing order. i.e. the best trades have the most outputs for the least inputs and are sorted first
1046
+
1047
+
1048
+ function inputOutputComparator(a, b) {
1049
+ // must have same input and output token for comparison
1050
+ !currencyEquals(a.inputAmount.currency, b.inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT_CURRENCY') : invariant(false) : void 0;
1051
+ !currencyEquals(a.outputAmount.currency, b.outputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT_CURRENCY') : invariant(false) : void 0;
1052
+
1053
+ if (a.outputAmount.equalTo(b.outputAmount)) {
1054
+ if (a.inputAmount.equalTo(b.inputAmount)) {
1055
+ return 0;
1056
+ } // trade A requires less input than trade B, so A should come first
1057
+
1058
+
1059
+ if (a.inputAmount.lessThan(b.inputAmount)) {
1060
+ return -1;
1061
+ } else {
1062
+ return 1;
1063
+ }
1064
+ } else {
1065
+ // tradeA has less output than trade B, so should come second
1066
+ if (a.outputAmount.lessThan(b.outputAmount)) {
1067
+ return 1;
1068
+ } else {
1069
+ return -1;
1070
+ }
1071
+ }
1072
+ } // extension of the input output comparator that also considers other dimensions of the trade in ranking them
1073
+
1074
+ function tradeComparator(a, b) {
1075
+ var ioComp = inputOutputComparator(a, b);
1076
+
1077
+ if (ioComp !== 0) {
1078
+ return ioComp;
1079
+ } // consider lowest slippage next, since these are less likely to fail
1080
+
1081
+
1082
+ if (a.priceImpact.lessThan(b.priceImpact)) {
1083
+ return -1;
1084
+ } else if (a.priceImpact.greaterThan(b.priceImpact)) {
1085
+ return 1;
1086
+ } // finally consider the number of hops since each hop costs gas
1087
+
1088
+
1089
+ return a.route.path.length - b.route.path.length;
1090
+ }
1091
+ /**
1092
+ * Given a currency amount and a chain ID, returns the equivalent representation as the token amount.
1093
+ * In other words, if the currency is ETHER, returns the WETH token amount for the given chain. Otherwise, returns
1094
+ * the input currency amount.
1095
+ */
1096
+
1097
+ function wrappedAmount(currencyAmount, chainId) {
1098
+ if (currencyAmount instanceof TokenAmount) return currencyAmount;
1099
+ if (currencyAmount.currency === ETHER) return new TokenAmount(WETH[chainId], currencyAmount.raw);
1100
+ process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) ;
1101
+ }
1102
+
1103
+ function wrappedCurrency(currency, chainId) {
1104
+ if (currency instanceof Token) return currency;
1105
+ if (currency === ETHER) return WETH[chainId];
1106
+ process.env.NODE_ENV !== "production" ? invariant(false, 'CURRENCY') : invariant(false) ;
1107
+ }
1108
+ /**
1109
+ * Represents a trade executed against a list of pairs.
1110
+ * Does not account for slippage, i.e. trades that front run this trade and move the price.
1111
+ */
1112
+
1113
+
1114
+ var Trade = /*#__PURE__*/function () {
1115
+ function Trade(route, amount, tradeType) {
1116
+ var amounts = new Array(route.path.length);
1117
+ var nextPairs = new Array(route.pairs.length);
1118
+
1119
+ if (tradeType === TradeType.EXACT_INPUT) {
1120
+ !currencyEquals(amount.currency, route.input) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INPUT') : invariant(false) : void 0;
1121
+ amounts[0] = wrappedAmount(amount, route.chainId);
1122
+
1123
+ for (var i = 0; i < route.path.length - 1; i++) {
1124
+ var pair = route.pairs[i];
1125
+
1126
+ var _pair$getOutputAmount = pair.getOutputAmount(amounts[i]),
1127
+ outputAmount = _pair$getOutputAmount[0],
1128
+ nextPair = _pair$getOutputAmount[1];
1129
+
1130
+ amounts[i + 1] = outputAmount;
1131
+ nextPairs[i] = nextPair;
1132
+ }
1133
+ } else {
1134
+ !currencyEquals(amount.currency, route.output) ? process.env.NODE_ENV !== "production" ? invariant(false, 'OUTPUT') : invariant(false) : void 0;
1135
+ amounts[amounts.length - 1] = wrappedAmount(amount, route.chainId);
1136
+
1137
+ for (var _i = route.path.length - 1; _i > 0; _i--) {
1138
+ var _pair = route.pairs[_i - 1];
1139
+
1140
+ var _pair$getInputAmount = _pair.getInputAmount(amounts[_i]),
1141
+ inputAmount = _pair$getInputAmount[0],
1142
+ _nextPair = _pair$getInputAmount[1];
1143
+
1144
+ amounts[_i - 1] = inputAmount;
1145
+ nextPairs[_i - 1] = _nextPair;
1146
+ }
1147
+ }
1148
+
1149
+ this.route = route;
1150
+ this.tradeType = tradeType;
1151
+ this.inputAmount = tradeType === TradeType.EXACT_INPUT ? amount : route.input === ETHER ? CurrencyAmount.ether(amounts[0].raw) : amounts[0];
1152
+ this.outputAmount = tradeType === TradeType.EXACT_OUTPUT ? amount : route.output === ETHER ? CurrencyAmount.ether(amounts[amounts.length - 1].raw) : amounts[amounts.length - 1];
1153
+ this.executionPrice = new Price(this.inputAmount.currency, this.outputAmount.currency, this.inputAmount.raw, this.outputAmount.raw);
1154
+ this.nextMidPrice = Price.fromRoute(new Route(nextPairs, route.input));
1155
+ this.priceImpact = computePriceImpact(route.midPrice, this.inputAmount, this.outputAmount);
1156
+ }
1157
+ /**
1158
+ * Constructs an exact in trade with the given amount in and route
1159
+ * @param route route of the exact in trade
1160
+ * @param amountIn the amount being passed in
1161
+ */
1162
+
1163
+
1164
+ Trade.exactIn = function exactIn(route, amountIn) {
1165
+ return new Trade(route, amountIn, TradeType.EXACT_INPUT);
1166
+ }
1167
+ /**
1168
+ * Constructs an exact out trade with the given amount out and route
1169
+ * @param route route of the exact out trade
1170
+ * @param amountOut the amount returned by the trade
1171
+ */
1172
+ ;
1173
+
1174
+ Trade.exactOut = function exactOut(route, amountOut) {
1175
+ return new Trade(route, amountOut, TradeType.EXACT_OUTPUT);
1176
+ }
1177
+ /**
1178
+ * Get the minimum amount that must be received from this trade for the given slippage tolerance
1179
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
1180
+ */
1181
+ ;
1182
+
1183
+ var _proto = Trade.prototype;
1184
+
1185
+ _proto.minimumAmountOut = function minimumAmountOut(slippageTolerance) {
1186
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
1187
+
1188
+ if (this.tradeType === TradeType.EXACT_OUTPUT) {
1189
+ return this.outputAmount;
1190
+ } else {
1191
+ var slippageAdjustedAmountOut = new Fraction(ONE).add(slippageTolerance).invert().multiply(this.outputAmount.raw).quotient;
1192
+ return this.outputAmount instanceof TokenAmount ? new TokenAmount(this.outputAmount.token, slippageAdjustedAmountOut) : CurrencyAmount.ether(slippageAdjustedAmountOut);
1193
+ }
1194
+ }
1195
+ /**
1196
+ * Get the maximum amount in that can be spent via this trade for the given slippage tolerance
1197
+ * @param slippageTolerance tolerance of unfavorable slippage from the execution price of this trade
1198
+ */
1199
+ ;
1200
+
1201
+ _proto.maximumAmountIn = function maximumAmountIn(slippageTolerance) {
1202
+ !!slippageTolerance.lessThan(ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SLIPPAGE_TOLERANCE') : invariant(false) : void 0;
1203
+
1204
+ if (this.tradeType === TradeType.EXACT_INPUT) {
1205
+ return this.inputAmount;
1206
+ } else {
1207
+ var slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(this.inputAmount.raw).quotient;
1208
+ return this.inputAmount instanceof TokenAmount ? new TokenAmount(this.inputAmount.token, slippageAdjustedAmountIn) : CurrencyAmount.ether(slippageAdjustedAmountIn);
1209
+ }
1210
+ }
1211
+ /**
1212
+ * Given a list of pairs, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token
1213
+ * amount to an output token, making at most `maxHops` hops.
1214
+ * Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting
1215
+ * the amount in among multiple routes.
1216
+ * @param pairs the pairs to consider in finding the best trade
1217
+ * @param currencyAmountIn exact amount of input currency to spend
1218
+ * @param currencyOut the desired currency out
1219
+ * @param maxNumResults maximum number of results to return
1220
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
1221
+ * @param currentPairs used in recursion; the current list of pairs
1222
+ * @param originalAmountIn used in recursion; the original value of the currencyAmountIn parameter
1223
+ * @param bestTrades used in recursion; the current list of best trades
1224
+ */
1225
+ ;
1226
+
1227
+ Trade.bestTradeExactIn = function bestTradeExactIn(pairs, currencyAmountIn, currencyOut, _temp, // used in recursion.
1228
+ currentPairs, originalAmountIn, bestTrades) {
1229
+ var _ref = _temp === void 0 ? {} : _temp,
1230
+ _ref$maxNumResults = _ref.maxNumResults,
1231
+ maxNumResults = _ref$maxNumResults === void 0 ? 3 : _ref$maxNumResults,
1232
+ _ref$maxHops = _ref.maxHops,
1233
+ maxHops = _ref$maxHops === void 0 ? 3 : _ref$maxHops;
1234
+
1235
+ if (currentPairs === void 0) {
1236
+ currentPairs = [];
1237
+ }
1238
+
1239
+ if (originalAmountIn === void 0) {
1240
+ originalAmountIn = currencyAmountIn;
1241
+ }
1242
+
1243
+ if (bestTrades === void 0) {
1244
+ bestTrades = [];
1245
+ }
1246
+
1247
+ !(pairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PAIRS') : invariant(false) : void 0;
1248
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
1249
+ !(originalAmountIn === currencyAmountIn || currentPairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
1250
+ var chainId = currencyAmountIn instanceof TokenAmount ? currencyAmountIn.token.chainId : currencyOut instanceof Token ? currencyOut.chainId : undefined;
1251
+ !(chainId !== undefined) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_ID') : invariant(false) : void 0;
1252
+ var amountIn = wrappedAmount(currencyAmountIn, chainId);
1253
+ var tokenOut = wrappedCurrency(currencyOut, chainId);
1254
+
1255
+ for (var i = 0; i < pairs.length; i++) {
1256
+ var pair = pairs[i]; // pair irrelevant
1257
+
1258
+ if (!pair.token0.equals(amountIn.token) && !pair.token1.equals(amountIn.token)) continue;
1259
+ if (pair.reserve0.equalTo(ZERO) || pair.reserve1.equalTo(ZERO)) continue;
1260
+ var amountOut = void 0;
1261
+
1262
+ try {
1263
+ ;
1264
+
1265
+ var _pair$getOutputAmount2 = pair.getOutputAmount(amountIn);
1266
+
1267
+ amountOut = _pair$getOutputAmount2[0];
1268
+ } catch (error) {
1269
+ // input too low
1270
+ if (error.isInsufficientInputAmountError) {
1271
+ continue;
1272
+ }
1273
+
1274
+ throw error;
1275
+ } // we have arrived at the output token, so this is the final trade of one of the paths
1276
+
1277
+
1278
+ if (amountOut.token.equals(tokenOut)) {
1279
+ sortedInsert(bestTrades, new Trade(new Route([].concat(currentPairs, [pair]), originalAmountIn.currency, currencyOut), originalAmountIn, TradeType.EXACT_INPUT), maxNumResults, tradeComparator);
1280
+ } else if (maxHops > 1 && pairs.length > 1) {
1281
+ 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
1282
+
1283
+ Trade.bestTradeExactIn(pairsExcludingThisPair, amountOut, currencyOut, {
1284
+ maxNumResults: maxNumResults,
1285
+ maxHops: maxHops - 1
1286
+ }, [].concat(currentPairs, [pair]), originalAmountIn, bestTrades);
1287
+ }
1288
+ }
1289
+
1290
+ return bestTrades;
1291
+ }
1292
+ /**
1293
+ * similar to the above method but instead targets a fixed output amount
1294
+ * given a list of pairs, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token
1295
+ * to an output token amount, making at most `maxHops` hops
1296
+ * note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting
1297
+ * the amount in among multiple routes.
1298
+ * @param pairs the pairs to consider in finding the best trade
1299
+ * @param currencyIn the currency to spend
1300
+ * @param currencyAmountOut the exact amount of currency out
1301
+ * @param maxNumResults maximum number of results to return
1302
+ * @param maxHops maximum number of hops a returned trade can make, e.g. 1 hop goes through a single pair
1303
+ * @param currentPairs used in recursion; the current list of pairs
1304
+ * @param originalAmountOut used in recursion; the original value of the currencyAmountOut parameter
1305
+ * @param bestTrades used in recursion; the current list of best trades
1306
+ */
1307
+ ;
1308
+
1309
+ Trade.bestTradeExactOut = function bestTradeExactOut(pairs, currencyIn, currencyAmountOut, _temp2, // used in recursion.
1310
+ currentPairs, originalAmountOut, bestTrades) {
1311
+ var _ref2 = _temp2 === void 0 ? {} : _temp2,
1312
+ _ref2$maxNumResults = _ref2.maxNumResults,
1313
+ maxNumResults = _ref2$maxNumResults === void 0 ? 3 : _ref2$maxNumResults,
1314
+ _ref2$maxHops = _ref2.maxHops,
1315
+ maxHops = _ref2$maxHops === void 0 ? 3 : _ref2$maxHops;
1316
+
1317
+ if (currentPairs === void 0) {
1318
+ currentPairs = [];
1319
+ }
1320
+
1321
+ if (originalAmountOut === void 0) {
1322
+ originalAmountOut = currencyAmountOut;
1323
+ }
1324
+
1325
+ if (bestTrades === void 0) {
1326
+ bestTrades = [];
1327
+ }
1328
+
1329
+ !(pairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'PAIRS') : invariant(false) : void 0;
1330
+ !(maxHops > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX_HOPS') : invariant(false) : void 0;
1331
+ !(originalAmountOut === currencyAmountOut || currentPairs.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'INVALID_RECURSION') : invariant(false) : void 0;
1332
+ var chainId = currencyAmountOut instanceof TokenAmount ? currencyAmountOut.token.chainId : currencyIn instanceof Token ? currencyIn.chainId : undefined;
1333
+ !(chainId !== undefined) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_ID') : invariant(false) : void 0;
1334
+ var amountOut = wrappedAmount(currencyAmountOut, chainId);
1335
+ var tokenIn = wrappedCurrency(currencyIn, chainId);
1336
+
1337
+ for (var i = 0; i < pairs.length; i++) {
1338
+ var pair = pairs[i]; // pair irrelevant
1339
+
1340
+ if (!pair.token0.equals(amountOut.token) && !pair.token1.equals(amountOut.token)) continue;
1341
+ if (pair.reserve0.equalTo(ZERO) || pair.reserve1.equalTo(ZERO)) continue;
1342
+ var amountIn = void 0;
1343
+
1344
+ try {
1345
+ ;
1346
+
1347
+ var _pair$getInputAmount2 = pair.getInputAmount(amountOut);
1348
+
1349
+ amountIn = _pair$getInputAmount2[0];
1350
+ } catch (error) {
1351
+ // not enough liquidity in this pair
1352
+ if (error.isInsufficientReservesError) {
1353
+ continue;
1354
+ }
1355
+
1356
+ throw error;
1357
+ } // we have arrived at the input token, so this is the first trade of one of the paths
1358
+
1359
+
1360
+ if (amountIn.token.equals(tokenIn)) {
1361
+ sortedInsert(bestTrades, new Trade(new Route([pair].concat(currentPairs), currencyIn, originalAmountOut.currency), originalAmountOut, TradeType.EXACT_OUTPUT), maxNumResults, tradeComparator);
1362
+ } else if (maxHops > 1 && pairs.length > 1) {
1363
+ 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
1364
+
1365
+ Trade.bestTradeExactOut(pairsExcludingThisPair, currencyIn, amountIn, {
1366
+ maxNumResults: maxNumResults,
1367
+ maxHops: maxHops - 1
1368
+ }, [pair].concat(currentPairs), originalAmountOut, bestTrades);
1369
+ }
1370
+ }
1371
+
1372
+ return bestTrades;
1373
+ };
1374
+
1375
+ return Trade;
1376
+ }();
1377
+
1378
+ function toHex(currencyAmount) {
1379
+ return "0x" + currencyAmount.raw.toString(16);
1380
+ }
1381
+
1382
+ var ZERO_HEX = '0x0';
1383
+ /**
1384
+ * Represents the Crosswise Router, and has static methods for helping execute trades.
1385
+ */
1386
+
1387
+ var Router = /*#__PURE__*/function () {
1388
+ /**
1389
+ * Cannot be constructed.
1390
+ */
1391
+ function Router() {}
1392
+ /**
1393
+ * Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade.
1394
+ * @param trade to produce call parameters for
1395
+ * @param options options for the call parameters
1396
+ */
1397
+
1398
+
1399
+ Router.swapCallParameters = function swapCallParameters(trade, options) {
1400
+ var etherIn = trade.inputAmount.currency === ETHER;
1401
+ var etherOut = trade.outputAmount.currency === ETHER; // the router does not support both ether in and out
1402
+
1403
+ !!(etherIn && etherOut) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ETHER_IN_OUT') : invariant(false) : void 0;
1404
+ !(!('ttl' in options) || options.ttl > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TTL') : invariant(false) : void 0;
1405
+ var to = validateAndParseAddress(options.recipient);
1406
+ var amountIn = toHex(trade.maximumAmountIn(options.allowedSlippage));
1407
+ var amountOut = toHex(trade.minimumAmountOut(options.allowedSlippage));
1408
+ var path = trade.route.path.map(function (token) {
1409
+ return token.address;
1410
+ });
1411
+ var deadline = 'ttl' in options ? "0x" + (Math.floor(new Date().getTime() / 1000) + options.ttl).toString(16) : "0x" + options.deadline.toString(16);
1412
+ var useFeeOnTransfer = Boolean(options.feeOnTransfer);
1413
+ var methodName;
1414
+ var args;
1415
+ var value;
1416
+
1417
+ switch (trade.tradeType) {
1418
+ case TradeType.EXACT_INPUT:
1419
+ if (etherIn) {
1420
+ methodName = useFeeOnTransfer ? 'swapExactETHForTokensSupportingFeeOnTransferTokens' : 'swapExactETHForTokens'; // (uint amountOutMin, address[] calldata path, address to, uint deadline)
1421
+
1422
+ args = [amountOut, path, to, deadline];
1423
+ value = amountIn;
1424
+ } else if (etherOut) {
1425
+ methodName = useFeeOnTransfer ? 'swapExactTokensForETHSupportingFeeOnTransferTokens' : 'swapExactTokensForETH'; // (uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
1426
+
1427
+ args = [amountIn, amountOut, path, to, deadline];
1428
+ value = ZERO_HEX;
1429
+ } else {
1430
+ methodName = useFeeOnTransfer ? 'swapExactTokensForTokensSupportingFeeOnTransferTokens' : 'swapExactTokensForTokens'; // (uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
1431
+
1432
+ args = [amountIn, amountOut, path, to, deadline];
1433
+ value = ZERO_HEX;
1434
+ }
1435
+
1436
+ break;
1437
+
1438
+ case TradeType.EXACT_OUTPUT:
1439
+ !!useFeeOnTransfer ? process.env.NODE_ENV !== "production" ? invariant(false, 'EXACT_OUT_FOT') : invariant(false) : void 0;
1440
+
1441
+ if (etherIn) {
1442
+ methodName = 'swapETHForExactTokens'; // (uint amountOut, address[] calldata path, address to, uint deadline)
1443
+
1444
+ args = [amountOut, path, to, deadline];
1445
+ value = amountIn;
1446
+ } else if (etherOut) {
1447
+ methodName = 'swapTokensForExactETH'; // (uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
1448
+
1449
+ args = [amountOut, amountIn, path, to, deadline];
1450
+ value = ZERO_HEX;
1451
+ } else {
1452
+ methodName = 'swapTokensForExactTokens'; // (uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
1453
+
1454
+ args = [amountOut, amountIn, path, to, deadline];
1455
+ value = ZERO_HEX;
1456
+ }
1457
+
1458
+ break;
1459
+ }
1460
+
1461
+ return {
1462
+ methodName: methodName,
1463
+ args: args,
1464
+ value: value
1465
+ };
1466
+ };
1467
+
1468
+ return Router;
1469
+ }();
1470
+
1471
+ var ERC20 = [
1472
+ {
1473
+ constant: true,
1474
+ inputs: [
1475
+ ],
1476
+ name: "decimals",
1477
+ outputs: [
1478
+ {
1479
+ name: "",
1480
+ type: "uint8"
1481
+ }
1482
+ ],
1483
+ payable: false,
1484
+ stateMutability: "view",
1485
+ type: "function"
1486
+ },
1487
+ {
1488
+ constant: true,
1489
+ inputs: [
1490
+ {
1491
+ name: "",
1492
+ type: "address"
1493
+ }
1494
+ ],
1495
+ name: "balanceOf",
1496
+ outputs: [
1497
+ {
1498
+ name: "",
1499
+ type: "uint256"
1500
+ }
1501
+ ],
1502
+ payable: false,
1503
+ stateMutability: "view",
1504
+ type: "function"
1505
+ }
1506
+ ];
1507
+
1508
+ var _TOKEN_DECIMALS_CACHE;
1509
+ var TOKEN_DECIMALS_CACHE = (_TOKEN_DECIMALS_CACHE = {}, _TOKEN_DECIMALS_CACHE[ChainId.MAINNET] = {
1510
+ '0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A': 9 // DGD
1511
+
1512
+ }, _TOKEN_DECIMALS_CACHE);
1513
+ /**
1514
+ * Contains methods for constructing instances of pairs and tokens from on-chain data.
1515
+ */
1516
+
1517
+ var Fetcher = /*#__PURE__*/function () {
1518
+ /**
1519
+ * Cannot be constructed.
1520
+ */
1521
+ function Fetcher() {}
1522
+ /**
1523
+ * Fetch information for a given token on the given chain, using the given ethers provider.
1524
+ * @param chainId chain of the token
1525
+ * @param address address of the token on the chain
1526
+ * @param provider provider used to fetch the token
1527
+ * @param symbol optional symbol of the token
1528
+ * @param name optional name of the token
1529
+ */
1530
+
1531
+
1532
+ Fetcher.fetchTokenData = function fetchTokenData(chainId, address, provider, symbol, name) {
1533
+ try {
1534
+ var _TOKEN_DECIMALS_CACHE2, _TOKEN_DECIMALS_CACHE3;
1535
+
1536
+ var _temp3 = function _temp3(parsedDecimals) {
1537
+ return new Token(chainId, address, parsedDecimals, symbol, name);
1538
+ };
1539
+
1540
+ if (provider === undefined) provider = getDefaultProvider(getNetwork(chainId));
1541
+
1542
+ var _temp4 = typeof ((_TOKEN_DECIMALS_CACHE2 = TOKEN_DECIMALS_CACHE) === null || _TOKEN_DECIMALS_CACHE2 === void 0 ? void 0 : (_TOKEN_DECIMALS_CACHE3 = _TOKEN_DECIMALS_CACHE2[chainId]) === null || _TOKEN_DECIMALS_CACHE3 === void 0 ? void 0 : _TOKEN_DECIMALS_CACHE3[address]) === 'number';
1543
+
1544
+ return Promise.resolve(_temp4 ? _temp3(TOKEN_DECIMALS_CACHE[chainId][address]) : Promise.resolve(new Contract(address, ERC20, provider).decimals().then(function (decimals) {
1545
+ var _TOKEN_DECIMALS_CACHE4, _extends2, _extends3;
1546
+
1547
+ TOKEN_DECIMALS_CACHE = _extends({}, TOKEN_DECIMALS_CACHE, (_extends3 = {}, _extends3[chainId] = _extends({}, (_TOKEN_DECIMALS_CACHE4 = TOKEN_DECIMALS_CACHE) === null || _TOKEN_DECIMALS_CACHE4 === void 0 ? void 0 : _TOKEN_DECIMALS_CACHE4[chainId], (_extends2 = {}, _extends2[address] = decimals, _extends2)), _extends3));
1548
+ return decimals;
1549
+ })).then(_temp3));
1550
+ } catch (e) {
1551
+ return Promise.reject(e);
1552
+ }
1553
+ }
1554
+ /**
1555
+ * Fetches information about a pair and constructs a pair from the given two tokens.
1556
+ * @param tokenA first token
1557
+ * @param tokenB second token
1558
+ * @param provider the provider to use to fetch the data
1559
+ */
1560
+ ;
1561
+
1562
+ Fetcher.fetchPairData = function fetchPairData(tokenA, tokenB, provider) {
1563
+ try {
1564
+ if (provider === undefined) provider = getDefaultProvider(getNetwork(tokenA.chainId));
1565
+ !(tokenA.chainId === tokenB.chainId) ? process.env.NODE_ENV !== "production" ? invariant(false, 'CHAIN_ID') : invariant(false) : void 0;
1566
+ var address = Pair.getAddress(tokenA, tokenB);
1567
+ return Promise.resolve(new Contract(address, IPancakePair.abi, provider).getReserves()).then(function (_ref) {
1568
+ var reserves0 = _ref[0],
1569
+ reserves1 = _ref[1];
1570
+ var balances = tokenA.sortsBefore(tokenB) ? [reserves0, reserves1] : [reserves1, reserves0];
1571
+ return new Pair(new TokenAmount(tokenA, balances[0]), new TokenAmount(tokenB, balances[1]));
1572
+ });
1573
+ } catch (e) {
1574
+ return Promise.reject(e);
1575
+ }
1576
+ };
1577
+
1578
+ return Fetcher;
1579
+ }();
1580
+
1581
+ export { ChainId, Currency, CurrencyAmount, ETHER, FACTORY_ADDRESS, Fetcher, Fraction, INIT_CODE_HASH, InsufficientInputAmountError, InsufficientReservesError, MINIMUM_LIQUIDITY, Pair, Percent, Price, Rounding, Route, Router, Token, TokenAmount, Trade, TradeType, WETH, currencyEquals, inputOutputComparator, tradeComparator };
1582
+ //# sourceMappingURL=sdk-v2.esm.js.map