UNPKG

@basex-fi/sdk-core

Version:

An SDK for building applications on top of BaseX

1,190 lines (1,175 loc) 182 kB
import _Big from 'big.js'; import JSBI from 'jsbi'; import invariant from 'tiny-invariant'; import toFormat from 'toformat'; import _Decimal from 'decimal.js-light'; import { BigNumber } from '@ethersproject/bignumber'; import { getAddress, getCreate2Address } from '@ethersproject/address'; import { defaultAbiCoder, Interface } from '@ethersproject/abi'; import { keccak256, pack } from '@ethersproject/solidity'; var WETH_ADDRESS = "0x4200000000000000000000000000000000000006"; var FACTORY_ADDRESS = "0xdC323d16C451819890805737997F4Ede96b95e3e"; var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; var NONFUNGIBLE_POSITION_MANAGER_ADDRESS = "0xe9e4346431c2006026720d1e03d33f12FabDbc3f"; var TICK_LENS_ADDRESS = "0x6f07aF1F970789B5CF29134B6f4506D9774ce935"; var QUOTER_ADDRESS = "0x30FF944EaEc54a433B7283dA42C6A9c65e20038F"; var MULTICALL_ADDRESS = "0x6D93fC5ae3c3f5a147Ed92E9CD738BF45D8a29BB"; var SWAP_ROUTER_02_ADDRESS = "0x875f7D1A45C5f9D8deeb19bEe68f72fe4187e490"; var ADDRESS_MAP = { v3CoreFactoryAddress: FACTORY_ADDRESS, multicallAddress: MULTICALL_ADDRESS, quoterAddress: QUOTER_ADDRESS, nonfungiblePositionManagerAddress: NONFUNGIBLE_POSITION_MANAGER_ADDRESS, tickLensAddress: TICK_LENS_ADDRESS, swapRouter02Address: SWAP_ROUTER_02_ADDRESS }; function _regeneratorRuntime() { _regeneratorRuntime = function () { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function (t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function (t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(typeof e + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function (e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function () { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function (e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function (t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function (t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function (t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function (e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } var _TICK_SPACINGS; var MaxUint256 = /*#__PURE__*/JSBI.BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); var TradeType; (function (TradeType) { TradeType[TradeType["EXACT_INPUT"] = 0] = "EXACT_INPUT"; TradeType[TradeType["EXACT_OUTPUT"] = 1] = "EXACT_OUTPUT"; })(TradeType || (TradeType = {})); var Rounding; (function (Rounding) { Rounding[Rounding["ROUND_DOWN"] = 0] = "ROUND_DOWN"; Rounding[Rounding["ROUND_HALF_UP"] = 1] = "ROUND_HALF_UP"; Rounding[Rounding["ROUND_UP"] = 2] = "ROUND_UP"; })(Rounding || (Rounding = {})); /** * The default factory enabled fee amounts, denominated in hundredths of bips. */ var FeeAmount; (function (FeeAmount) { FeeAmount[FeeAmount["LOWEST"] = 100] = "LOWEST"; FeeAmount[FeeAmount["LOW"] = 500] = "LOW"; FeeAmount[FeeAmount["MEDIUM"] = 3000] = "MEDIUM"; FeeAmount[FeeAmount["HIGH"] = 10000] = "HIGH"; })(FeeAmount || (FeeAmount = {})); /** * The default factory tick spacings by fee amount. */ var TICK_SPACINGS = (_TICK_SPACINGS = {}, _TICK_SPACINGS[FeeAmount.LOWEST] = 1, _TICK_SPACINGS[FeeAmount.LOW] = 10, _TICK_SPACINGS[FeeAmount.MEDIUM] = 60, _TICK_SPACINGS[FeeAmount.HIGH] = 200, _TICK_SPACINGS); // constants used internally but not expected to be used externally var NEGATIVE_ONE = /*#__PURE__*/JSBI.BigInt(-1); var ZERO = /*#__PURE__*/JSBI.BigInt(0); var ONE = /*#__PURE__*/JSBI.BigInt(1); // used in liquidity amount math var Q96 = /*#__PURE__*/JSBI.exponentiate( /*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(96)); var Q192 = /*#__PURE__*/JSBI.exponentiate(Q96, /*#__PURE__*/JSBI.BigInt(2)); var POOL_INIT_CODE_HASH = "0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54"; var _toSignificantRoundin, _toFixedRounding; var Decimal = /*#__PURE__*/toFormat(_Decimal); var Big = /*#__PURE__*/toFormat(_Big); 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); var toFixedRounding = (_toFixedRounding = {}, _toFixedRounding[Rounding.ROUND_DOWN] = 0, _toFixedRounding[Rounding.ROUND_HALF_UP] = 1, _toFixedRounding[Rounding.ROUND_UP] = 3, _toFixedRounding); var Fraction = /*#__PURE__*/function () { function Fraction(numerator, denominator) { if (denominator === void 0) { denominator = JSBI.BigInt(1); } this.numerator = JSBI.BigInt(numerator); this.denominator = JSBI.BigInt(denominator); } Fraction.tryParseFraction = function tryParseFraction(fractionish) { if (fractionish instanceof JSBI || typeof fractionish === "number" || typeof fractionish === "string") return new Fraction(fractionish); if ("numerator" in fractionish && "denominator" in fractionish) return fractionish; throw new Error("Could not parse fraction"); } // performs floor division ; var _proto = Fraction.prototype; _proto.invert = function invert() { return new Fraction(this.denominator, this.numerator); }; _proto.add = function add(other) { var otherParsed = Fraction.tryParseFraction(other); if (JSBI.equal(this.denominator, otherParsed.denominator)) { return new Fraction(JSBI.add(this.numerator, otherParsed.numerator), this.denominator); } return new Fraction(JSBI.add(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)), JSBI.multiply(this.denominator, otherParsed.denominator)); }; _proto.subtract = function subtract(other) { var otherParsed = Fraction.tryParseFraction(other); if (JSBI.equal(this.denominator, otherParsed.denominator)) { return new Fraction(JSBI.subtract(this.numerator, otherParsed.numerator), this.denominator); } return new Fraction(JSBI.subtract(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)), JSBI.multiply(this.denominator, otherParsed.denominator)); }; _proto.lessThan = function lessThan(other) { var otherParsed = Fraction.tryParseFraction(other); return JSBI.lessThan(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)); }; _proto.equalTo = function equalTo(other) { var otherParsed = Fraction.tryParseFraction(other); return JSBI.equal(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)); }; _proto.greaterThan = function greaterThan(other) { var otherParsed = Fraction.tryParseFraction(other); return JSBI.greaterThan(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(otherParsed.numerator, this.denominator)); }; _proto.multiply = function multiply(other) { var otherParsed = Fraction.tryParseFraction(other); return new Fraction(JSBI.multiply(this.numerator, otherParsed.numerator), JSBI.multiply(this.denominator, otherParsed.denominator)); }; _proto.divide = function divide(other) { var otherParsed = Fraction.tryParseFraction(other); return new Fraction(JSBI.multiply(this.numerator, otherParsed.denominator), JSBI.multiply(this.denominator, otherParsed.numerator)); }; _proto.toSignificant = function toSignificant(significantDigits, format, rounding) { if (format === void 0) { format = { groupSeparator: "" }; } if (rounding === void 0) { rounding = Rounding.ROUND_HALF_UP; } !Number.isInteger(significantDigits) ? process.env.NODE_ENV !== "production" ? invariant(false, significantDigits + " is not an integer.") : invariant(false) : void 0; !(significantDigits > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, significantDigits + " is not positive.") : invariant(false) : void 0; Decimal.set({ precision: significantDigits + 1, rounding: toSignificantRounding[rounding] }); var quotient = new Decimal(this.numerator.toString()).div(this.denominator.toString()).toSignificantDigits(significantDigits); return quotient.toFormat(quotient.decimalPlaces(), format); }; _proto.toFixed = function toFixed(decimalPlaces, format, rounding) { if (format === void 0) { format = { groupSeparator: "" }; } if (rounding === void 0) { rounding = Rounding.ROUND_HALF_UP; } !Number.isInteger(decimalPlaces) ? process.env.NODE_ENV !== "production" ? invariant(false, decimalPlaces + " is not an integer.") : invariant(false) : void 0; !(decimalPlaces >= 0) ? process.env.NODE_ENV !== "production" ? invariant(false, decimalPlaces + " is negative.") : invariant(false) : void 0; Big.DP = decimalPlaces; Big.RM = toFixedRounding[rounding]; return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(decimalPlaces, format); } /** * Helper method for converting any super class back to a fraction */; _createClass(Fraction, [{ key: "quotient", get: function get() { return JSBI.divide(this.numerator, this.denominator); } // remainder after floor division }, { key: "remainder", get: function get() { return new Fraction(JSBI.remainder(this.numerator, this.denominator), this.denominator); } }, { key: "asFraction", get: function get() { return new Fraction(this.numerator, this.denominator); } }]); return Fraction; }(); var Big$1 = /*#__PURE__*/toFormat(_Big); var CurrencyAmount = /*#__PURE__*/function (_Fraction) { _inheritsLoose(CurrencyAmount, _Fraction); function CurrencyAmount(currency, numerator, denominator) { var _this; _this = _Fraction.call(this, numerator, denominator) || this; !JSBI.lessThanOrEqual(_this.quotient, MaxUint256) ? process.env.NODE_ENV !== "production" ? invariant(false, "AMOUNT") : invariant(false) : void 0; _this.currency = currency; _this.decimalScale = JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(currency.decimals)); return _this; } /** * Returns a new currency amount instance from the unitless amount of token, i.e. the raw amount * @param currency the currency in the amount * @param rawAmount the raw token or ether amount */ CurrencyAmount.fromRawAmount = function fromRawAmount(currency, rawAmount) { return new CurrencyAmount(currency, rawAmount); } /** * Construct a currency amount with a denominator that is not equal to 1 * @param currency the currency * @param numerator the numerator of the fractional token amount * @param denominator the denominator of the fractional token amount */; CurrencyAmount.fromFractionalAmount = function fromFractionalAmount(currency, numerator, denominator) { return new CurrencyAmount(currency, numerator, denominator); }; var _proto = CurrencyAmount.prototype; _proto.add = function add(other) { !this.currency.equals(other.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, "CURRENCY") : invariant(false) : void 0; var added = _Fraction.prototype.add.call(this, other); return CurrencyAmount.fromFractionalAmount(this.currency, added.numerator, added.denominator); }; _proto.subtract = function subtract(other) { !this.currency.equals(other.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, "CURRENCY") : invariant(false) : void 0; var subtracted = _Fraction.prototype.subtract.call(this, other); return CurrencyAmount.fromFractionalAmount(this.currency, subtracted.numerator, subtracted.denominator); }; _proto.multiply = function multiply(other) { var multiplied = _Fraction.prototype.multiply.call(this, other); return CurrencyAmount.fromFractionalAmount(this.currency, multiplied.numerator, multiplied.denominator); }; _proto.divide = function divide(other) { var divided = _Fraction.prototype.divide.call(this, other); return CurrencyAmount.fromFractionalAmount(this.currency, divided.numerator, divided.denominator); }; _proto.toSignificant = function toSignificant(significantDigits, format, rounding) { if (significantDigits === void 0) { significantDigits = 6; } if (rounding === void 0) { rounding = Rounding.ROUND_DOWN; } return _Fraction.prototype.divide.call(this, this.decimalScale).toSignificant(significantDigits, format, rounding); }; _proto.toFixed = function toFixed(decimalPlaces, format, rounding) { if (decimalPlaces === void 0) { decimalPlaces = this.currency.decimals; } if (rounding === void 0) { rounding = Rounding.ROUND_DOWN; } !(decimalPlaces <= this.currency.decimals) ? process.env.NODE_ENV !== "production" ? invariant(false, "DECIMALS") : invariant(false) : void 0; return _Fraction.prototype.divide.call(this, this.decimalScale).toFixed(decimalPlaces, format, rounding); }; _proto.toExact = function toExact(format) { if (format === void 0) { format = { groupSeparator: "" }; } Big$1.DP = this.currency.decimals; return new Big$1(this.quotient.toString()).div(this.decimalScale.toString()).toFormat(format); }; _createClass(CurrencyAmount, [{ key: "wrapped", get: function get() { if (this.currency.isToken) return this; return CurrencyAmount.fromFractionalAmount(this.currency.wrapped, this.numerator, this.denominator); } }]); return CurrencyAmount; }(Fraction); var Price = /*#__PURE__*/function (_Fraction) { _inheritsLoose(Price, _Fraction); /** * Construct a price, either with the base and quote currency amount, or the * @param args */ function Price() { var _this; var baseCurrency, quoteCurrency, denominator, numerator; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 4) { baseCurrency = args[0]; quoteCurrency = args[1]; denominator = args[2]; numerator = args[3]; } else { var result = args[0].quoteAmount.divide(args[0].baseAmount); var _ref = [args[0].baseAmount.currency, args[0].quoteAmount.currency, result.denominator, result.numerator]; baseCurrency = _ref[0]; quoteCurrency = _ref[1]; denominator = _ref[2]; numerator = _ref[3]; } _this = _Fraction.call(this, numerator, denominator) || this; _this.baseCurrency = baseCurrency; _this.quoteCurrency = quoteCurrency; _this.scalar = new Fraction(JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(baseCurrency.decimals)), JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(quoteCurrency.decimals))); return _this; } /** * Flip the price, switching the base and quote currency */ var _proto = Price.prototype; _proto.invert = function invert() { return new Price(this.quoteCurrency, this.baseCurrency, this.numerator, this.denominator); } /** * Multiply the price by another price, returning a new price. The other price must have the same base currency as this price's quote currency * @param other the other price */; _proto.multiply = function multiply(other) { !this.quoteCurrency.equals(other.baseCurrency) ? process.env.NODE_ENV !== "production" ? invariant(false, "TOKEN") : invariant(false) : void 0; var fraction = _Fraction.prototype.multiply.call(this, other); return new Price(this.baseCurrency, other.quoteCurrency, fraction.denominator, fraction.numerator); } /** * Return the amount of quote currency corresponding to a given amount of the base currency * @param currencyAmount the amount of base currency to quote against the price */; _proto.quote = function quote(currencyAmount) { !currencyAmount.currency.equals(this.baseCurrency) ? process.env.NODE_ENV !== "production" ? invariant(false, "TOKEN") : invariant(false) : void 0; var result = _Fraction.prototype.multiply.call(this, currencyAmount); return CurrencyAmount.fromFractionalAmount(this.quoteCurrency, result.numerator, result.denominator); } /** * Get the value scaled by decimals for formatting * @private */; _proto.toSignificant = function toSignificant(significantDigits, format, rounding) { if (significantDigits === void 0) { significantDigits = 6; } return this.adjustedForDecimals.toSignificant(significantDigits, format, rounding); }; _proto.toFixed = function toFixed(decimalPlaces, format, rounding) { if (decimalPlaces === void 0) { decimalPlaces = 4; } return this.adjustedForDecimals.toFixed(decimalPlaces, format, rounding); }; _createClass(Price, [{ key: "adjustedForDecimals", get: function get() { return _Fraction.prototype.multiply.call(this, this.scalar); } }]); return Price; }(Fraction); var ONE_HUNDRED = /*#__PURE__*/new Fraction( /*#__PURE__*/JSBI.BigInt(100)); /** * Converts a fraction to a percent * @param fraction the fraction to convert */ function toPercent(fraction) { return new Percent(fraction.numerator, fraction.denominator); } var Percent = /*#__PURE__*/function (_Fraction) { _inheritsLoose(Percent, _Fraction); function Percent() { var _this; _this = _Fraction.apply(this, arguments) || this; /** * This boolean prevents a fraction from being interpreted as a Percent */ _this.isPercent = true; return _this; } var _proto = Percent.prototype; _proto.add = function add(other) { return toPercent(_Fraction.prototype.add.call(this, other)); }; _proto.subtract = function subtract(other) { return toPercent(_Fraction.prototype.subtract.call(this, other)); }; _proto.multiply = function multiply(other) { return toPercent(_Fraction.prototype.multiply.call(this, other)); }; _proto.divide = function divide(other) { return toPercent(_Fraction.prototype.divide.call(this, other)); }; _proto.toSignificant = function toSignificant(significantDigits, format, rounding) { if (significantDigits === void 0) { significantDigits = 5; } return _Fraction.prototype.multiply.call(this, ONE_HUNDRED).toSignificant(significantDigits, format, rounding); }; _proto.toFixed = function toFixed(decimalPlaces, format, rounding) { if (decimalPlaces === void 0) { decimalPlaces = 2; } return _Fraction.prototype.multiply.call(this, ONE_HUNDRED).toFixed(decimalPlaces, format, rounding); }; return Percent; }(Fraction); var BaseCurrency = function BaseCurrency(decimals, symbol, name, icon, coingeckoId) { !(decimals >= 0 && decimals < 255 && Number.isInteger(decimals)) ? process.env.NODE_ENV !== "production" ? invariant(false, "DECIMALS") : invariant(false) : void 0; this.decimals = decimals; this.symbol = symbol; this.name = name; this.icon = icon; this.coingeckoId = coingeckoId; }; var NativeCurrency = /*#__PURE__*/function (_BaseCurrency) { _inheritsLoose(NativeCurrency, _BaseCurrency); function NativeCurrency() { var _this; _this = _BaseCurrency.apply(this, arguments) || this; _this.isNative = true; _this.isToken = false; return _this; } return NativeCurrency; }(BaseCurrency); var Token = /*#__PURE__*/function (_BaseCurrency) { _inheritsLoose(Token, _BaseCurrency); function Token(address, decimals, symbol, name, icon, coingeckoId, buyFeeBps, sellFeeBps) { var _this; _this = _BaseCurrency.call(this, decimals, symbol, name, icon, coingeckoId) || this; _this.isNative = false; _this.isToken = true; _this.address = address; if (buyFeeBps) { !buyFeeBps.gte(BigNumber.from(0)) ? process.env.NODE_ENV !== "production" ? invariant(false, "NON-NEGATIVE FOT FEES") : invariant(false) : void 0; } if (sellFeeBps) { !sellFeeBps.gte(BigNumber.from(0)) ? process.env.NODE_ENV !== "production" ? invariant(false, "NON-NEGATIVE FOT FEES") : invariant(false) : void 0; } _this.buyFeeBps = buyFeeBps; _this.sellFeeBps = sellFeeBps; return _this; } var _proto = Token.prototype; _proto.equals = function equals(other) { return other.isToken && this.address.toLowerCase() === other.address.toLowerCase(); }; _proto.sortsBefore = function sortsBefore(other) { !(this.address.toLowerCase() !== other.address.toLowerCase()) ? process.env.NODE_ENV !== "production" ? invariant(false, "ADDRESSES") : invariant(false) : void 0; return this.address.toLowerCase() < other.address.toLowerCase(); }; _createClass(Token, [{ key: "wrapped", get: function get() { return this; } }]); return Token; }(BaseCurrency); var Ether = /*#__PURE__*/function (_NativeCurrency) { _inheritsLoose(Ether, _NativeCurrency); function Ether() { return _NativeCurrency.call(this, 18, "ETH", "Ether", "/icons/ETH.svg", "ethereum") || this; } var _proto = Ether.prototype; _proto.equals = function equals(other) { return other.isNative; }; _createClass(Ether, [{ key: "wrapped", get: function get() { var weth = new Token(WETH_ADDRESS, 18, "WETH", "Wrapped Ether", "/icons/ETH.svg", "ethereum"); return weth; } }]); return Ether; }(NativeCurrency); /** * This tick data provider does not know how to fetch any tick data. It throws whenever it is required. Useful if you * do not need to load tick data for your use case. */ var NoTickDataProvider = /*#__PURE__*/function () { function NoTickDataProvider() {} var _proto = NoTickDataProvider.prototype; _proto.getTick = /*#__PURE__*/function () { var _getTick = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_tick) { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: throw new Error(NoTickDataProvider.ERROR_MESSAGE); case 1: case "end": return _context.stop(); } }, _callee); })); function getTick(_x) { return _getTick.apply(this, arguments); } return getTick; }(); _proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () { var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_tick, _lte, _tickSpacing) { return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: throw new Error(NoTickDataProvider.ERROR_MESSAGE); case 1: case "end": return _context2.stop(); } }, _callee2); })); function nextInitializedTickWithinOneWord(_x2, _x3, _x4) { return _nextInitializedTickWithinOneWord.apply(this, arguments); } return nextInitializedTickWithinOneWord; }(); return NoTickDataProvider; }(); NoTickDataProvider.ERROR_MESSAGE = "No tick data provider was given"; var Tick = function Tick(_ref) { var index = _ref.index, liquidityGross = _ref.liquidityGross, liquidityNet = _ref.liquidityNet; !(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK) ? process.env.NODE_ENV !== "production" ? invariant(false, "TICK") : invariant(false) : void 0; this.index = index; this.liquidityGross = JSBI.BigInt(liquidityGross); this.liquidityNet = JSBI.BigInt(liquidityNet); }; /** * A data provider for ticks that is backed by an in-memory array of ticks. */ var TickListDataProvider = /*#__PURE__*/function () { function TickListDataProvider(ticks, tickSpacing) { var ticksMapped = ticks.map(function (t) { return t instanceof Tick ? t : new Tick(t); }); TickList.validateList(ticksMapped, tickSpacing); this.ticks = ticksMapped; } var _proto = TickListDataProvider.prototype; _proto.getTick = /*#__PURE__*/function () { var _getTick = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(tick) { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", TickList.getTick(this.ticks, tick)); case 1: case "end": return _context.stop(); } }, _callee, this); })); function getTick(_x) { return _getTick.apply(this, arguments); } return getTick; }(); _proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () { var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(tick, lte, tickSpacing) { return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: return _context2.abrupt("return", TickList.nextInitializedTickWithinOneWord(this.ticks, tick, lte, tickSpacing)); case 1: case "end": return _context2.stop(); } }, _callee2, this); })); function nextInitializedTickWithinOneWord(_x2, _x3, _x4) { return _nextInitializedTickWithinOneWord.apply(this, arguments); } return nextInitializedTickWithinOneWord; }(); return TickListDataProvider; }(); /** * By default, pools will not allow operations that require ticks. */ var NO_TICK_DATA_PROVIDER_DEFAULT = /*#__PURE__*/new NoTickDataProvider(); /** * Represents a V3 pool */ var Pool = /*#__PURE__*/function () { /** * Construct a pool * @param tokenA One of the tokens in the pool * @param tokenB The other token in the pool * @param fee The fee in hundredths of a bips of the input amount of every swap that is collected by the pool * @param sqrtRatioX96 The sqrt of the current ratio of amounts of token1 to token0 * @param liquidity The current value of in range liquidity * @param tickCurrent The current tick of the pool * @param ticks The current state of the pool ticks or a data provider that can return tick data */ function Pool(tokenA, tokenB, fee, sqrtRatioX96, liquidity, tickCurrent, ticks) { if (ticks === void 0) { ticks = NO_TICK_DATA_PROVIDER_DEFAULT; } !(Number.isInteger(fee) && fee < 1000000) ? process.env.NODE_ENV !== "production" ? invariant(false, "FEE") : invariant(false) : void 0; var tickCurrentSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent); var nextTickSqrtRatioX96 = TickMath.getSqrtRatioAtTick(tickCurrent + 1); !(JSBI.greaterThanOrEqual(JSBI.BigInt(sqrtRatioX96), tickCurrentSqrtRatioX96) && JSBI.lessThanOrEqual(JSBI.BigInt(sqrtRatioX96), nextTickSqrtRatioX96)) ? process.env.NODE_ENV !== "production" ? invariant(false, "PRICE_BOUNDS") : invariant(false) : void 0; // always create a copy of the list since we want the pool's tick list to be immutable var _ref = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA]; this.token0 = _ref[0]; this.token1 = _ref[1]; this.fee = fee; this.sqrtRatioX96 = JSBI.BigInt(sqrtRatioX96); this.liquidity = JSBI.BigInt(liquidity); this.tickCurrent = tickCurrent; this.tickDataProvider = Array.isArray(ticks) ? new TickListDataProvider(ticks, TICK_SPACINGS[fee]) : ticks; } Pool.getAddress = function getAddress(tokenA, tokenB, fee, initCodeHashManualOverride, factoryAddressOverride) { return computePoolAddress({ factoryAddress: factoryAddressOverride != null ? factoryAddressOverride : FACTORY_ADDRESS, fee: fee, tokenA: tokenA, tokenB: tokenB, initCodeHashManualOverride: initCodeHashManualOverride }); } /** * Returns true if the token is either token0 or token1 * @param token The token to check * @returns True if token is either token0 or token */; var _proto = Pool.prototype; _proto.involvesToken = function involvesToken(token) { return token.equals(this.token0) || token.equals(this.token1); } /** * Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0 */; /** * Return the price of the given token in terms of the other token in the pool. * @param token The token to return price of * @returns The price of the given token, in terms of the other. */ _proto.priceOf = function priceOf(token) { !this.involvesToken(token) ? process.env.NODE_ENV !== "production" ? invariant(false, "TOKEN") : invariant(false) : void 0; return token.equals(this.token0) ? this.token0Price : this.token1Price; } /** * Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade * @param inputAmount The input amount for which to quote the output amount * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit * @returns The output amount and the pool with updated state */; _proto.getOutputAmount = /*#__PURE__*/ function () { var _getOutputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(inputAmount, sqrtPriceLimitX96) { var zeroForOne, _yield$this$swap, outputAmount, sqrtRatioX96, liquidity, tickCurrent, outputToken; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: !this.involvesToken(inputAmount.currency) ? process.env.NODE_ENV !== "production" ? invariant(false, "TOKEN") : invariant(false) : void 0; zeroForOne = inputAmount.currency.equals(this.token0); _context.next = 4; return this.swap(zeroForOne, inputAmount.quotient, sqrtPriceLimitX96); case 4: _yield$this$swap = _context.sent; outputAmount = _yield$this$swap.amountCalculated; sqrtRatioX96 = _yield$this$swap.sqrtRatioX96; liquidity = _yield$this$swap.liquidity; tickCurrent = _yield$this$swap.tickCurrent; outputToken = zeroForOne ? this.token1 : this.token0; return _context.abrupt("return", [CurrencyAmount.fromRawAmount(outputToken, JSBI.multiply(outputAmount, NEGATIVE_ONE)), new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]); case 11: case "end": return _context.stop(); } }, _callee, this); })); function getOutputAmount(_x, _x2) { return _getOutputAmount.apply(this, arguments); } return getOutputAmount; }() /** * Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade * @param outputAmount the output amount for which to quote the input amount * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap * @returns The input amount and the pool with updated state */ ; _proto.getInputAmount = /*#__PURE__*/ function () { var _getInputAmount = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(outputAmount, sqrtPriceLimitX96) { var zeroForOne, _yield$this$swap2, inputAmount, sqrtRatioX96, liquidity, tickCurrent, inputToken; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: !(outputAmount.currency.isToken && this.involvesToken(outputAmount.currency)) ? process.env.NODE_ENV !== "production" ? invariant(false, "TOKEN") : invariant(false) : void 0; zeroForOne = outputAmount.currency.equals(this.token1); _context2.next = 4; return this.swap(zeroForOne, JSBI.multiply(outputAmount.quotient, NEGATIVE_ONE), sqrtPriceLimitX96); case 4: _yield$this$swap2 = _context2.sent; inputAmount = _yield$this$swap2.amountCalculated; sqrtRatioX96 = _yield$this$swap2.sqrtRatioX96; liquidity = _yield$this$swap2.liquidity; tickCurrent = _yield$this$swap2.tickCurrent; inputToken = zeroForOne ? this.token0 : this.token1; return _context2.abrupt("return", [CurrencyAmount.fromRawAmount(inputToken, inputAmount), new Pool(this.token0, this.token1, this.fee, sqrtRatioX96, liquidity, tickCurrent, this.tickDataProvider)]); case 11: case "end": return _context2.stop(); } }, _callee2, this); })); function getInputAmount(_x3, _x4) { return _getInputAmount.apply(this, arguments); } return getInputAmount; }() /** * Executes a swap * @param zeroForOne Whether the amount in is token0 or token1 * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) * @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap * @returns amountCalculated * @returns sqrtRatioX96 * @returns liquidity * @returns tickCurrent */ ; _proto.swap = /*#__PURE__*/ function () { var _swap = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(zeroForOne, amountSpecified, sqrtPriceLimitX96) { var exactInput, state, step, _yield$this$tickDataP, _SwapMath$computeSwap, liquidityNet; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (!sqrtPriceLimitX96) sqrtPriceLimitX96 = zeroForOne ? JSBI.add(TickMath.MIN_SQRT_RATIO, ONE) : JSBI.subtract(TickMath.MAX_SQRT_RATIO, ONE); if (zeroForOne) { !JSBI.greaterThan(sqrtPriceLimitX96, TickMath.MIN_SQRT_RATIO) ? process.env.NODE_ENV !== "production" ? invariant(false, "RATIO_MIN") : invariant(false) : void 0; !JSBI.lessThan(sqrtPriceLimitX96, this.sqrtRatioX96) ? process.env.NODE_ENV !== "production" ? invariant(false, "RATIO_CURRENT") : invariant(false) : void 0; } else { !JSBI.lessThan(sqrtPriceLimitX96, TickMath.MAX_SQRT_RATIO) ? process.env.NODE_ENV !== "production" ? invariant(false, "RATIO_MAX") : invariant(false) : void 0; !JSBI.greaterThan(sqrtPriceLimitX96, this.sqrtRatioX96) ? process.env.NODE_ENV !== "production" ? invariant(false, "RATIO_CURRENT") : invariant(false) : void 0; } exactInput = JSBI.greaterThanOrEqual(amountSpecified, ZERO); // keep track of swap state state = { amountSpecifiedRemaining: amountSpecified, amountCalculated: ZERO, sqrtPriceX96: this.sqrtRatioX96, tick: this.tickCurrent, liquidity: this.liquidity }; // start swap while loop case 4: if (!(JSBI.notEqual(state.amountSpecifiedRemaining, ZERO) && state.sqrtPriceX96 != sqrtPriceLimitX96)) { _context3.next = 35; break; } step = {}; step.sqrtPriceStartX96 = state.sqrtPriceX96; // because each iteration of the while loop rounds, we can't optimize this code (relative to the smart contract) // by simply traversing to the next available tick, we instead need to exactly replicate // tickBitmap.nextInitializedTickWithinOneWord _context3.next = 9; return this.tickDataProvider.nextInitializedTickWithinOneWord(state.tick, zeroForOne, this.tickSpacing); case 9