UNPKG

astra-cl-sdk-dev

Version:

⚒️ An SDK for building applications on top of Astra CL

1,125 lines (1,107 loc) 145 kB
import { ChainId, MaxUint256, sqrt, Price, CurrencyAmount, Percent, TradeType, Fraction, sortedInsert, validateAndParseAddress } from 'astra-sdk-core'; import JSBI from 'jsbi'; import invariant from 'tiny-invariant'; import { defaultAbiCoder, Interface } from '@ethersproject/abi'; import { getCreate2Address } from '@ethersproject/address'; import { keccak256, pack } from '@ethersproject/solidity'; import IMulticall from '@airdao/astra-cl-periphery/artifacts/contracts/interfaces/IMulticall.sol/IMulticall.json'; import INonfungiblePositionManager from '@airdao/astra-cl-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json'; import ISelfPermit from '@airdao/astra-cl-periphery/artifacts/contracts/interfaces/ISelfPermit.sol/ISelfPermit.json'; import IPeripheryPaymentsWithFee from '@airdao/astra-cl-periphery/artifacts/contracts/interfaces/IPeripheryPaymentsWithFee.sol/IPeripheryPaymentsWithFee.json'; import IQuoter from '@airdao/astra-cl-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json'; import IQuoterV2 from '@airdao/swap-router-contracts/artifacts/contracts/lens/QuoterV2.sol/QuoterV2.json'; import IAstraCLStaker from '@airdao/astra-cl-staker/artifacts/contracts/AstraCLStaker.sol/AstraCLStaker.json'; import ISwapRouter from '@airdao/astra-cl-periphery/artifacts/contracts/SwapRouter.sol/SwapRouter.json'; function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _createForOfIteratorHelperLoose(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (t) return (t = t.call(r)).next.bind(t); if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var o = 0; return function () { return o >= r.length ? { done: !0 } : { done: !1, value: r[o++] }; }; } 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 _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } 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 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 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 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 _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } var _TICK_SPACINGS; var FACTORY_ADDRESS = "0x1F98431c8aD98523631AE4a59f267346ea31F984"; var ADDRESS_ZERO = "0x0000000000000000000000000000000000000000"; // @deprecated please use poolInitCodeHash(chainId: ChainId) var POOL_INIT_CODE_HASH = "0x203c8ec649b23b7faf9b73ccadfb1a67af52a097119c82801f4947ec5deb6c04"; function poolInitCodeHash(chainId) { switch (chainId) { case ChainId.MAINNET: case ChainId.TESTNET: case ChainId.DEVNET: return "0x203c8ec649b23b7faf9b73ccadfb1a67af52a097119c82801f4947ec5deb6c04"; default: return POOL_INIT_CODE_HASH; } } /** * The default factory enabled fee amounts, denominated in hundredths of bips. */ var FeeAmount; (function (FeeAmount) { FeeAmount[FeeAmount["LOWEST"] = 100] = "LOWEST"; FeeAmount[FeeAmount["LOW_200"] = 200] = "LOW_200"; FeeAmount[FeeAmount["LOW_300"] = 300] = "LOW_300"; FeeAmount[FeeAmount["LOW_400"] = 400] = "LOW_400"; 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_200] = 4, _TICK_SPACINGS[FeeAmount.LOW_300] = 6, _TICK_SPACINGS[FeeAmount.LOW_400] = 8, _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)); /** * Computes a pool address * @param factoryAddress The Astra CL factory address * @param tokenA The first token of the pair, irrespective of sort order * @param tokenB The second token of the pair, irrespective of sort order * @param fee The fee tier of the pool * @param initCodeHashManualOverride Override the init code hash used to compute the pool address if necessary * @param chainId * @returns The pool address */ function computePoolAddress(_ref) { var factoryAddress = _ref.factoryAddress, tokenA = _ref.tokenA, tokenB = _ref.tokenB, fee = _ref.fee, initCodeHashManualOverride = _ref.initCodeHashManualOverride, chainId = _ref.chainId; var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA], token0 = _ref2[0], token1 = _ref2[1]; // does safety checks var salt = keccak256(['bytes'], [defaultAbiCoder.encode(['address', 'address', 'uint24'], [token0.address, token1.address, fee])]); var initCodeHash = initCodeHashManualOverride != null ? initCodeHashManualOverride : poolInitCodeHash(chainId); // ZKSync uses a different create2 address computation // Most likely all ZKEVM chains will use the different computation from standard create2 switch (chainId) { default: return getCreate2Address(factoryAddress, salt, initCodeHash); } } var FullMath = /*#__PURE__*/function () { /** * Cannot be constructed. */ function FullMath() {} FullMath.mulDivRoundingUp = function mulDivRoundingUp(a, b, denominator) { var product = JSBI.multiply(a, b); var result = JSBI.divide(product, denominator); if (JSBI.notEqual(JSBI.remainder(product, denominator), ZERO)) result = JSBI.add(result, ONE); return result; }; return FullMath; }(); var MaxUint160 = /*#__PURE__*/JSBI.subtract(/*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(160)), ONE); function multiplyIn256(x, y) { var product = JSBI.multiply(x, y); return JSBI.bitwiseAnd(product, MaxUint256); } function addIn256(x, y) { var sum = JSBI.add(x, y); return JSBI.bitwiseAnd(sum, MaxUint256); } var SqrtPriceMath = /*#__PURE__*/function () { /** * Cannot be constructed. */ function SqrtPriceMath() {} SqrtPriceMath.getAmount0Delta = function getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) { if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) { var _ref = [sqrtRatioBX96, sqrtRatioAX96]; sqrtRatioAX96 = _ref[0]; sqrtRatioBX96 = _ref[1]; } var numerator1 = JSBI.leftShift(liquidity, JSBI.BigInt(96)); var numerator2 = JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), ONE, sqrtRatioAX96) : JSBI.divide(JSBI.divide(JSBI.multiply(numerator1, numerator2), sqrtRatioBX96), sqrtRatioAX96); }; SqrtPriceMath.getAmount1Delta = function getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidity, roundUp) { if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) { var _ref2 = [sqrtRatioBX96, sqrtRatioAX96]; sqrtRatioAX96 = _ref2[0]; sqrtRatioBX96 = _ref2[1]; } return roundUp ? FullMath.mulDivRoundingUp(liquidity, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96), Q96) : JSBI.divide(JSBI.multiply(liquidity, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96)), Q96); }; SqrtPriceMath.getNextSqrtPriceFromInput = function getNextSqrtPriceFromInput(sqrtPX96, liquidity, amountIn, zeroForOne) { !JSBI.greaterThan(sqrtPX96, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0; !JSBI.greaterThan(liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0; return zeroForOne ? this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); }; SqrtPriceMath.getNextSqrtPriceFromOutput = function getNextSqrtPriceFromOutput(sqrtPX96, liquidity, amountOut, zeroForOne) { !JSBI.greaterThan(sqrtPX96, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0; !JSBI.greaterThan(liquidity, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0; return zeroForOne ? this.getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : this.getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); }; SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp = function getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amount, add) { if (JSBI.equal(amount, ZERO)) return sqrtPX96; var numerator1 = JSBI.leftShift(liquidity, JSBI.BigInt(96)); if (add) { var product = multiplyIn256(amount, sqrtPX96); if (JSBI.equal(JSBI.divide(product, amount), sqrtPX96)) { var denominator = addIn256(numerator1, product); if (JSBI.greaterThanOrEqual(denominator, numerator1)) { return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator); } } return FullMath.mulDivRoundingUp(numerator1, ONE, JSBI.add(JSBI.divide(numerator1, sqrtPX96), amount)); } else { var _product = multiplyIn256(amount, sqrtPX96); !JSBI.equal(JSBI.divide(_product, amount), sqrtPX96) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0; !JSBI.greaterThan(numerator1, _product) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0; var _denominator = JSBI.subtract(numerator1, _product); return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, _denominator); } }; SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown = function getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amount, add) { if (add) { var quotient = JSBI.lessThanOrEqual(amount, MaxUint160) ? JSBI.divide(JSBI.leftShift(amount, JSBI.BigInt(96)), liquidity) : JSBI.divide(JSBI.multiply(amount, Q96), liquidity); return JSBI.add(sqrtPX96, quotient); } else { var _quotient = FullMath.mulDivRoundingUp(amount, Q96, liquidity); !JSBI.greaterThan(sqrtPX96, _quotient) ? process.env.NODE_ENV !== "production" ? invariant(false) : invariant(false) : void 0; return JSBI.subtract(sqrtPX96, _quotient); } }; return SqrtPriceMath; }(); var MAX_FEE = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(10), /*#__PURE__*/JSBI.BigInt(6)); var SwapMath = /*#__PURE__*/function () { /** * Cannot be constructed. */ function SwapMath() {} SwapMath.computeSwapStep = function computeSwapStep(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, amountRemaining, feePips) { var returnValues = {}; feePips = JSBI.BigInt(feePips); var zeroForOne = JSBI.greaterThanOrEqual(sqrtRatioCurrentX96, sqrtRatioTargetX96); var exactIn = JSBI.greaterThanOrEqual(amountRemaining, ZERO); if (exactIn) { var amountRemainingLessFee = JSBI.divide(JSBI.multiply(amountRemaining, JSBI.subtract(MAX_FEE, feePips)), MAX_FEE); returnValues.amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true); if (JSBI.greaterThanOrEqual(amountRemainingLessFee, returnValues.amountIn)) { returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96; } else { returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne); } } else { returnValues.amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false); if (JSBI.greaterThanOrEqual(JSBI.multiply(amountRemaining, NEGATIVE_ONE), returnValues.amountOut)) { returnValues.sqrtRatioNextX96 = sqrtRatioTargetX96; } else { returnValues.sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtRatioCurrentX96, liquidity, JSBI.multiply(amountRemaining, NEGATIVE_ONE), zeroForOne); } } var max = JSBI.equal(sqrtRatioTargetX96, returnValues.sqrtRatioNextX96); if (zeroForOne) { returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount0Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true); returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount1Delta(returnValues.sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false); } else { returnValues.amountIn = max && exactIn ? returnValues.amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, true); returnValues.amountOut = max && !exactIn ? returnValues.amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, returnValues.sqrtRatioNextX96, liquidity, false); } if (!exactIn && JSBI.greaterThan(returnValues.amountOut, JSBI.multiply(amountRemaining, NEGATIVE_ONE))) { returnValues.amountOut = JSBI.multiply(amountRemaining, NEGATIVE_ONE); } if (exactIn && JSBI.notEqual(returnValues.sqrtRatioNextX96, sqrtRatioTargetX96)) { // we didn't reach the target, so take the remainder of the maximum input as fee returnValues.feeAmount = JSBI.subtract(amountRemaining, returnValues.amountIn); } else { returnValues.feeAmount = FullMath.mulDivRoundingUp(returnValues.amountIn, feePips, JSBI.subtract(MAX_FEE, feePips)); } return [returnValues.sqrtRatioNextX96, returnValues.amountIn, returnValues.amountOut, returnValues.feeAmount]; }; return SwapMath; }(); var LiquidityMath = /*#__PURE__*/function () { /** * Cannot be constructed. */ function LiquidityMath() {} LiquidityMath.addDelta = function addDelta(x, y) { if (JSBI.lessThan(y, ZERO)) { return JSBI.subtract(x, JSBI.multiply(y, NEGATIVE_ONE)); } else { return JSBI.add(x, y); } }; return LiquidityMath; }(); var TWO = /*#__PURE__*/JSBI.BigInt(2); var POWERS_OF_2 = /*#__PURE__*/[128, 64, 32, 16, 8, 4, 2, 1].map(function (pow) { return [pow, JSBI.exponentiate(TWO, JSBI.BigInt(pow))]; }); function mostSignificantBit(x) { !JSBI.greaterThan(x, ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO') : invariant(false) : void 0; !JSBI.lessThanOrEqual(x, MaxUint256) ? process.env.NODE_ENV !== "production" ? invariant(false, 'MAX') : invariant(false) : void 0; var msb = 0; for (var _iterator = _createForOfIteratorHelperLoose(POWERS_OF_2), _step; !(_step = _iterator()).done;) { var _step$value = _step.value, power = _step$value[0], min = _step$value[1]; if (JSBI.greaterThanOrEqual(x, min)) { x = JSBI.signedRightShift(x, JSBI.BigInt(power)); msb += power; } } return msb; } function mulShift(val, mulBy) { return JSBI.signedRightShift(JSBI.multiply(val, JSBI.BigInt(mulBy)), JSBI.BigInt(128)); } var Q32 = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(32)); var TickMath = /*#__PURE__*/function () { /** * Cannot be constructed. */ function TickMath() {} /** * Returns the sqrt ratio as a Q64.96 for the given tick. The sqrt ratio is computed as sqrt(1.0001)^tick * @param tick the tick for which to compute the sqrt ratio */ TickMath.getSqrtRatioAtTick = function getSqrtRatioAtTick(tick) { !(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK && Number.isInteger(tick)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK') : invariant(false) : void 0; var absTick = tick < 0 ? tick * -1 : tick; var ratio = (absTick & 0x1) !== 0 ? JSBI.BigInt('0xfffcb933bd6fad37aa2d162d1a594001') : JSBI.BigInt('0x100000000000000000000000000000000'); if ((absTick & 0x2) !== 0) ratio = mulShift(ratio, '0xfff97272373d413259a46990580e213a'); if ((absTick & 0x4) !== 0) ratio = mulShift(ratio, '0xfff2e50f5f656932ef12357cf3c7fdcc'); if ((absTick & 0x8) !== 0) ratio = mulShift(ratio, '0xffe5caca7e10e4e61c3624eaa0941cd0'); if ((absTick & 0x10) !== 0) ratio = mulShift(ratio, '0xffcb9843d60f6159c9db58835c926644'); if ((absTick & 0x20) !== 0) ratio = mulShift(ratio, '0xff973b41fa98c081472e6896dfb254c0'); if ((absTick & 0x40) !== 0) ratio = mulShift(ratio, '0xff2ea16466c96a3843ec78b326b52861'); if ((absTick & 0x80) !== 0) ratio = mulShift(ratio, '0xfe5dee046a99a2a811c461f1969c3053'); if ((absTick & 0x100) !== 0) ratio = mulShift(ratio, '0xfcbe86c7900a88aedcffc83b479aa3a4'); if ((absTick & 0x200) !== 0) ratio = mulShift(ratio, '0xf987a7253ac413176f2b074cf7815e54'); if ((absTick & 0x400) !== 0) ratio = mulShift(ratio, '0xf3392b0822b70005940c7a398e4b70f3'); if ((absTick & 0x800) !== 0) ratio = mulShift(ratio, '0xe7159475a2c29b7443b29c7fa6e889d9'); if ((absTick & 0x1000) !== 0) ratio = mulShift(ratio, '0xd097f3bdfd2022b8845ad8f792aa5825'); if ((absTick & 0x2000) !== 0) ratio = mulShift(ratio, '0xa9f746462d870fdf8a65dc1f90e061e5'); if ((absTick & 0x4000) !== 0) ratio = mulShift(ratio, '0x70d869a156d2a1b890bb3df62baf32f7'); if ((absTick & 0x8000) !== 0) ratio = mulShift(ratio, '0x31be135f97d08fd981231505542fcfa6'); if ((absTick & 0x10000) !== 0) ratio = mulShift(ratio, '0x9aa508b5b7a84e1c677de54f3e99bc9'); if ((absTick & 0x20000) !== 0) ratio = mulShift(ratio, '0x5d6af8dedb81196699c329225ee604'); if ((absTick & 0x40000) !== 0) ratio = mulShift(ratio, '0x2216e584f5fa1ea926041bedfe98'); if ((absTick & 0x80000) !== 0) ratio = mulShift(ratio, '0x48a170391f7dc42444e8fa2'); if (tick > 0) ratio = JSBI.divide(MaxUint256, ratio); // back to Q96 return JSBI.greaterThan(JSBI.remainder(ratio, Q32), ZERO) ? JSBI.add(JSBI.divide(ratio, Q32), ONE) : JSBI.divide(ratio, Q32); } /** * Returns the tick corresponding to a given sqrt ratio, s.t. #getSqrtRatioAtTick(tick) <= sqrtRatioX96 * and #getSqrtRatioAtTick(tick + 1) > sqrtRatioX96 * @param sqrtRatioX96 the sqrt ratio as a Q64.96 for which to compute the tick */; TickMath.getTickAtSqrtRatio = function getTickAtSqrtRatio(sqrtRatioX96) { !(JSBI.greaterThanOrEqual(sqrtRatioX96, TickMath.MIN_SQRT_RATIO) && JSBI.lessThan(sqrtRatioX96, TickMath.MAX_SQRT_RATIO)) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SQRT_RATIO') : invariant(false) : void 0; var sqrtRatioX128 = JSBI.leftShift(sqrtRatioX96, JSBI.BigInt(32)); var msb = mostSignificantBit(sqrtRatioX128); var r; if (JSBI.greaterThanOrEqual(JSBI.BigInt(msb), JSBI.BigInt(128))) { r = JSBI.signedRightShift(sqrtRatioX128, JSBI.BigInt(msb - 127)); } else { r = JSBI.leftShift(sqrtRatioX128, JSBI.BigInt(127 - msb)); } var log_2 = JSBI.leftShift(JSBI.subtract(JSBI.BigInt(msb), JSBI.BigInt(128)), JSBI.BigInt(64)); for (var i = 0; i < 14; i++) { r = JSBI.signedRightShift(JSBI.multiply(r, r), JSBI.BigInt(127)); var f = JSBI.signedRightShift(r, JSBI.BigInt(128)); log_2 = JSBI.bitwiseOr(log_2, JSBI.leftShift(f, JSBI.BigInt(63 - i))); r = JSBI.signedRightShift(r, f); } var log_sqrt10001 = JSBI.multiply(log_2, JSBI.BigInt('255738958999603826347141')); var tickLow = JSBI.toNumber(JSBI.signedRightShift(JSBI.subtract(log_sqrt10001, JSBI.BigInt('3402992956809132418596140100660247210')), JSBI.BigInt(128))); var tickHigh = JSBI.toNumber(JSBI.signedRightShift(JSBI.add(log_sqrt10001, JSBI.BigInt('291339464771989622907027621153398088495')), JSBI.BigInt(128))); return tickLow === tickHigh ? tickLow : JSBI.lessThanOrEqual(TickMath.getSqrtRatioAtTick(tickHigh), sqrtRatioX96) ? tickHigh : tickLow; }; return TickMath; }(); /** * The minimum tick that can be used on any pool. */ TickMath.MIN_TICK = -887272; /** * The maximum tick that can be used on any pool. */ TickMath.MAX_TICK = -TickMath.MIN_TICK; /** * The sqrt ratio corresponding to the minimum tick that could be used on any pool. */ TickMath.MIN_SQRT_RATIO = /*#__PURE__*/JSBI.BigInt('4295128739'); /** * The sqrt ratio corresponding to the maximum tick that could be used on any pool. */ TickMath.MAX_SQRT_RATIO = /*#__PURE__*/JSBI.BigInt('1461446703485210103287273052203988822378723970342'); function CLSwap(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8, _x9) { return _CLSwap.apply(this, arguments); } function _CLSwap() { _CLSwap = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(fee, sqrtRatioX96, tickCurrent, liquidity, tickSpacing, tickDataProvider, zeroForOne, amountSpecified, sqrtPriceLimitX96) { var exactInput, state, step, _yield$tickDataProvid, _SwapMath$computeSwap, liquidityNet; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.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, 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, 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: sqrtRatioX96, tick: tickCurrent, liquidity: liquidity }; // start swap while loop case 4: if (!(JSBI.notEqual(state.amountSpecifiedRemaining, ZERO) && state.sqrtPriceX96 !== sqrtPriceLimitX96)) { _context.next = 35; break; } step = {}; step.sqrtPriceStartX96 = state.sqrtPriceX96; _context.next = 9; return tickDataProvider.nextInitializedTickWithinOneWord(state.tick, zeroForOne, tickSpacing); case 9: _yield$tickDataProvid = _context.sent; step.tickNext = _yield$tickDataProvid[0]; step.initialized = _yield$tickDataProvid[1]; if (step.tickNext < TickMath.MIN_TICK) { step.tickNext = TickMath.MIN_TICK; } else if (step.tickNext > TickMath.MAX_TICK) { step.tickNext = TickMath.MAX_TICK; } step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext); _SwapMath$computeSwap = SwapMath.computeSwapStep(state.sqrtPriceX96, (zeroForOne ? JSBI.lessThan(step.sqrtPriceNextX96, sqrtPriceLimitX96) : JSBI.greaterThan(step.sqrtPriceNextX96, sqrtPriceLimitX96)) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96, state.liquidity, state.amountSpecifiedRemaining, fee); state.sqrtPriceX96 = _SwapMath$computeSwap[0]; step.amountIn = _SwapMath$computeSwap[1]; step.amountOut = _SwapMath$computeSwap[2]; step.feeAmount = _SwapMath$computeSwap[3]; if (exactInput) { state.amountSpecifiedRemaining = JSBI.subtract(state.amountSpecifiedRemaining, JSBI.add(step.amountIn, step.feeAmount)); state.amountCalculated = JSBI.subtract(state.amountCalculated, step.amountOut); } else { state.amountSpecifiedRemaining = JSBI.add(state.amountSpecifiedRemaining, step.amountOut); state.amountCalculated = JSBI.add(state.amountCalculated, JSBI.add(step.amountIn, step.feeAmount)); } // TODO if (!JSBI.equal(state.sqrtPriceX96, step.sqrtPriceNextX96)) { _context.next = 32; break; } if (!step.initialized) { _context.next = 29; break; } _context.t0 = JSBI; _context.next = 25; return tickDataProvider.getTick(step.tickNext); case 25: _context.t1 = _context.sent.liquidityNet; liquidityNet = _context.t0.BigInt.call(_context.t0, _context.t1); // if we're moving leftward, we interpret liquidityNet as the opposite sign // safe because liquidityNet cannot be type(int128).min if (zeroForOne) liquidityNet = JSBI.multiply(liquidityNet, NEGATIVE_ONE); state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet); case 29: state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext; _context.next = 33; break; case 32: if (JSBI.notEqual(state.sqrtPriceX96, step.sqrtPriceStartX96)) { // updated comparison function // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96); } case 33: _context.next = 4; break; case 35: return _context.abrupt("return", { amountCalculated: state.amountCalculated, sqrtRatioX96: state.sqrtPriceX96, liquidity: state.liquidity, tickCurrent: state.tick }); case 36: case "end": return _context.stop(); } }, _callee); })); return _CLSwap.apply(this, arguments); } /** * 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'; /** * Determines if a tick list is sorted * @param list The tick list * @param comparator The comparator * @returns true if sorted */ function isSorted(list, comparator) { for (var i = 0; i < list.length - 1; i++) { if (comparator(list[i], list[i + 1]) > 0) { return false; } } return true; } function tickComparator(a, b) { return a.index - b.index; } /** * Utility methods for interacting with sorted lists of ticks */ var TickList = /*#__PURE__*/function () { /** * Cannot be constructed */ function TickList() {} TickList.validateList = function validateList(ticks, tickSpacing) { !(tickSpacing > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_SPACING_NONZERO') : invariant(false) : void 0; // ensure ticks are spaced appropriately !ticks.every(function (_ref) { var index = _ref.index; return index % tickSpacing === 0; }) ? process.env.NODE_ENV !== "production" ? invariant(false, 'TICK_SPACING') : invariant(false) : void 0; // ensure tick liquidity deltas sum to 0 !JSBI.equal(ticks.reduce(function (accumulator, _ref2) { var liquidityNet = _ref2.liquidityNet; return JSBI.add(accumulator, liquidityNet); }, ZERO), ZERO) ? process.env.NODE_ENV !== "production" ? invariant(false, 'ZERO_NET') : invariant(false) : void 0; !isSorted(ticks, tickComparator) ? process.env.NODE_ENV !== "production" ? invariant(false, 'SORTED') : invariant(false) : void 0; }; TickList.isBelowSmallest = function isBelowSmallest(ticks, tick) { !(ticks.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LENGTH') : invariant(false) : void 0; return tick < ticks[0].index; }; TickList.isAtOrAboveLargest = function isAtOrAboveLargest(ticks, tick) { !(ticks.length > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LENGTH') : invariant(false) : void 0; return tick >= ticks[ticks.length - 1].index; }; TickList.getTick = function getTick(ticks, index) { var tick = ticks[this.binarySearch(ticks, index)]; !(tick.index === index) ? process.env.NODE_ENV !== "production" ? invariant(false, 'NOT_CONTAINED') : invariant(false) : void 0; return tick; } /** * Finds the largest tick in the list of ticks that is less than or equal to tick * @param ticks list of ticks * @param tick tick to find the largest tick that is less than or equal to tick * @private */; TickList.binarySearch = function binarySearch(ticks, tick) { !!this.isBelowSmallest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'BELOW_SMALLEST') : invariant(false) : void 0; var l = 0; var r = ticks.length - 1; var i; while (true) { i = Math.floor((l + r) / 2); if (ticks[i].index <= tick && (i === ticks.length - 1 || ticks[i + 1].index > tick)) { return i; } if (ticks[i].index < tick) { l = i + 1; } else { r = i - 1; } } }; TickList.nextInitializedTick = function nextInitializedTick(ticks, tick, lte) { if (lte) { !!TickList.isBelowSmallest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'BELOW_SMALLEST') : invariant(false) : void 0; if (TickList.isAtOrAboveLargest(ticks, tick)) { return ticks[ticks.length - 1]; } var index = this.binarySearch(ticks, tick); return ticks[index]; } else { !!this.isAtOrAboveLargest(ticks, tick) ? process.env.NODE_ENV !== "production" ? invariant(false, 'AT_OR_ABOVE_LARGEST') : invariant(false) : void 0; if (this.isBelowSmallest(ticks, tick)) { return ticks[0]; } var _index = this.binarySearch(ticks, tick); return ticks[_index + 1]; } }; TickList.nextInitializedTickWithinOneWord = function nextInitializedTickWithinOneWord(ticks, tick, lte, tickSpacing) { var compressed = Math.floor(tick / tickSpacing); // matches rounding in the code if (lte) { var wordPos = compressed >> 8; var minimum = (wordPos << 8) * tickSpacing; if (TickList.isBelowSmallest(ticks, tick)) { return [minimum, false]; } var index = TickList.nextInitializedTick(ticks, tick, lte).index; var nextInitializedTick = Math.max(minimum, index); return [nextInitializedTick, nextInitializedTick === index]; } else { var _wordPos = compressed + 1 >> 8; var maximum = ((_wordPos + 1 << 8) - 1) * tickSpacing; if (this.isAtOrAboveLargest(ticks, tick)) { return [maximum, false]; } var _index2 = this.nextInitializedTick(ticks, tick, lte).index; var _nextInitializedTick = Math.min(maximum, _index2); return [_nextInitializedTick, _nextInitializedTick === _index2]; } }; return TickList; }(); /** * Converts a big int to a hex string * @param bigintIsh * @returns The hex encoded calldata */ function toHex(bigintIsh) { var bigInt = JSBI.BigInt(bigintIsh); var hex = bigInt.toString(16); if (hex.length % 2 !== 0) { hex = "0" + hex; } return "0x" + hex; } /** * Converts a route to a hex encoded path * @param route the CL path to convert to an encoded path * @param exactOutput whether the route should be encoded in reverse, for making exact output swaps */ function encodeRouteToPath(route, exactOutput) { var firstInputToken = route.input.wrapped; var _route$pools$reduce = route.pools.reduce(function (_ref, pool, index) { var inputToken = _ref.inputToken, path = _ref.path, types = _ref.types; var outputToken = pool.token0.equals(inputToken) ? pool.token1 : pool.token0; if (index === 0) { return { inputToken: outputToken, types: ['address', 'uint24', 'address'], path: [inputToken.address, pool.fee, outputToken.address] }; } else { return { inputToken: outputToken, types: [].concat(types, ['uint24', 'address']), path: [].concat(path, [pool.fee, outputToken.address]) }; } }, { inputToken: firstInputToken, path: [], types: [] }), path = _route$pools$reduce.path, types = _route$pools$reduce.types; return exactOutput ? pack(types.reverse(), path.reverse()) : pack(types, path); } /** * Returns the sqrt ratio as a Q64.96 corresponding to a given ratio of amount1 and amount0 * @param amount1 The numerator amount i.e., the amount of token1 * @param amount0 The denominator amount i.e., the amount of token0 * @returns The sqrt ratio */ function encodeSqrtRatioX96(amount1, amount0) { var numerator = JSBI.leftShift(JSBI.BigInt(amount1), JSBI.BigInt(192)); var denominator = JSBI.BigInt(amount0); var ratioX192 = JSBI.divide(numerator, denominator); return sqrt(ratioX192); } /** * Returns an imprecise maximum amount of liquidity received for a given amount of token 0. * This function is available to accommodate LiquidityAmounts#getLiquidityForAmount0 in the CL periphery, * which could be more precise by at least 32 bits by dividing by Q64 instead of Q96 in the intermediate step, * and shifting the subtracted ratio left by 32 bits. This imprecise calculation will likely be replaced in a future * CL router contract. * @param sqrtRatioAX96 The price at the lower boundary * @param sqrtRatioBX96 The price at the upper boundary * @param amount0 The token0 amount * @returns liquidity for amount0, imprecise */ function maxLiquidityForAmount0Imprecise(sqrtRatioAX96, sqrtRatioBX96, amount0) { if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) { var _ref = [sqrtRatioBX96, sqrtRatioAX96]; sqrtRatioAX96 = _ref[0]; sqrtRatioBX96 = _ref[1]; } var intermediate = JSBI.divide(JSBI.multiply(sqrtRatioAX96, sqrtRatioBX96), Q96); return JSBI.divide(JSBI.multiply(JSBI.BigInt(amount0), intermediate), JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96)); } /** * Returns a precise maximum amount of liquidity received for a given amount of token 0 by dividing by Q64 instead of Q96 in the intermediate step, * and shifting the subtracted ratio left by 32 bits. * @param sqrtRatioAX96 The price at the lower boundary * @param sqrtRatioBX96 The price at the upper boundary * @param amount0 The token0 amount * @returns liquidity for amount0, precise */ function maxLiquidityForAmount0Precise(sqrtRatioAX96, sqrtRatioBX96, amount0) { if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) { var _ref2 = [sqrtRatioBX96, sqrtRatioAX96]; sqrtRatioAX96 = _ref2[0]; sqrtRatioBX96 = _ref2[1]; } var numerator = JSBI.multiply(JSBI.multiply(JSBI.BigInt(amount0), sqrtRatioAX96), sqrtRatioBX96); var denominator = JSBI.multiply(Q96, JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96)); return JSBI.divide(numerator, denominator); } /** * Computes the maximum amount of liquidity received for a given amount of token1 * @param sqrtRatioAX96 The price at the lower tick boundary * @param sqrtRatioBX96 The price at the upper tick boundary * @param amount1 The token1 amount * @returns liquidity for amount1 */ function maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1) { if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) { var _ref3 = [sqrtRatioBX96, sqrtRatioAX96]; sqrtRatioAX96 = _ref3[0]; sqrtRatioBX96 = _ref3[1]; } return JSBI.di