UNPKG

@energiswap/v3-sdk

Version:

⚒️ An SDK for building applications on top of Energiswap V3

1,099 lines (1,072 loc) 134 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var sdkCore = require('@energiswap/sdk-core'); var JSBI = _interopDefault(require('jsbi')); var invariant = _interopDefault(require('tiny-invariant')); var abi = require('@ethersproject/abi'); var address = require('@ethersproject/address'); var solidity = require('@ethersproject/solidity'); var IMulticall = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/interfaces/IMulticall.sol/IMulticall.json')); var INonfungiblePositionManager = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json')); var ISelfPermit = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/interfaces/ISelfPermit.sol/ISelfPermit.json')); var IPeripheryPaymentsWithFee = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/interfaces/IPeripheryPaymentsWithFee.sol/IPeripheryPaymentsWithFee.json')); var IQuoter = _interopDefault(require('@uniswap/v3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json')); var IQuoterV2 = _interopDefault(require('@uniswap/swap-router-contracts/artifacts/contracts/lens/QuoterV2.sol/QuoterV2.json')); var IUniswapV3Staker = _interopDefault(require('@uniswap/v3-staker/artifacts/contracts/UniswapV3Staker.sol/UniswapV3Staker.json')); var ISwapRouter = _interopDefault(require('@uniswap/v3-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 _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function (t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () { return this; }), _regeneratorDefine(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function () { return { w: i, m: f }; })(); } function _regeneratorDefine(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine = function (e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { function o(r, n) { _regeneratorDefine(e, r, function (e) { return this._invoke(r, n, e); }); } o("next", 0), o("throw", 1), o("return", 2); } }, _regeneratorDefine(e, r, n, t); } 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 = '0x2BfD24B00413Fd35089cc9E3E6Aa285e4Bd7904d'; var ADDRESS_ZERO = '0x0000000000000000000000000000000000000000'; // @deprecated please use poolInitCodeHash(chainId: ChainId) var POOL_INIT_CODE_HASH = '0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54'; function poolInitCodeHash(chainId) { if (chainId) { return POOL_INIT_CODE_HASH; } else { return POOL_INIT_CODE_HASH; } } (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"; })(exports.FeeAmount || (exports.FeeAmount = {})); /** * The default factory tick spacings by fee amount. */ var TICK_SPACINGS = (_TICK_SPACINGS = {}, _TICK_SPACINGS[exports.FeeAmount.LOWEST] = 1, _TICK_SPACINGS[exports.FeeAmount.LOW_200] = 4, _TICK_SPACINGS[exports.FeeAmount.LOW_300] = 6, _TICK_SPACINGS[exports.FeeAmount.LOW_400] = 8, _TICK_SPACINGS[exports.FeeAmount.LOW] = 10, _TICK_SPACINGS[exports.FeeAmount.MEDIUM] = 60, _TICK_SPACINGS[exports.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 Uniswap V3 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 = solidity.keccak256(['bytes'], [abi.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) { case sdkCore.ChainId.ENERGI: return address.getCreate2Address(factoryAddress, salt, initCodeHash); default: return address.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, sdkCore.MaxUint256); } function addIn256(x, y) { var sum = JSBI.add(x, y); return JSBI.bitwiseAnd(sum, sdkCore.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) ? invariant(false) : void 0; !JSBI.greaterThan(liquidity, ZERO) ? 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) ? invariant(false) : void 0; !JSBI.greaterThan(liquidity, ZERO) ? 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) ? invariant(false) : void 0; !JSBI.greaterThan(numerator1, _product) ? 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) ? 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) ? invariant(false, 'ZERO') : void 0; !JSBI.lessThanOrEqual(x, sdkCore.MaxUint256) ? invariant(false, 'MAX') : 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)) ? invariant(false, 'TICK') : 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(sdkCore.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)) ? invariant(false, 'SQRT_RATIO') : 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 v3Swap(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8, _x9) { return _v3Swap.apply(this, arguments); } function _v3Swap() { _v3Swap = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(fee, sqrtRatioX96, tickCurrent, liquidity, tickSpacing, tickDataProvider, zeroForOne, amountSpecified, sqrtPriceLimitX96) { var exactInput, state, step, _yield$tickDataProvid, _SwapMath$computeSwap, liquidityNet, _t, _t2; return _regenerator().w(function (_context) { while (1) switch (_context.n) { 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) ? invariant(false, 'RATIO_MIN') : void 0; !JSBI.lessThan(sqrtPriceLimitX96, sqrtRatioX96) ? invariant(false, 'RATIO_CURRENT') : void 0; } else { !JSBI.lessThan(sqrtPriceLimitX96, TickMath.MAX_SQRT_RATIO) ? invariant(false, 'RATIO_MAX') : void 0; !JSBI.greaterThan(sqrtPriceLimitX96, sqrtRatioX96) ? invariant(false, 'RATIO_CURRENT') : 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 1: if (!(JSBI.notEqual(state.amountSpecifiedRemaining, ZERO) && state.sqrtPriceX96 !== sqrtPriceLimitX96)) { _context.n = 7; break; } step = {}; step.sqrtPriceStartX96 = state.sqrtPriceX96; _context.n = 2; return tickDataProvider.nextInitializedTickWithinOneWord(state.tick, zeroForOne, tickSpacing); case 2: _yield$tickDataProvid = _context.v; 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.n = 5; break; } if (!step.initialized) { _context.n = 4; break; } _t = JSBI; _context.n = 3; return tickDataProvider.getTick(step.tickNext); case 3: _t2 = _context.v.liquidityNet; liquidityNet = _t.BigInt.call(_t, _t2); // 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 4: state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext; _context.n = 6; break; case 5: 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 6: _context.n = 1; break; case 7: return _context.a(2, { amountCalculated: state.amountCalculated, sqrtRatioX96: state.sqrtPriceX96, liquidity: state.liquidity, tickCurrent: state.tick }); } }, _callee); })); return _v3Swap.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__*/_regenerator().m(function _callee(_tick) { return _regenerator().w(function (_context) { while (1) switch (_context.n) { case 0: throw new Error(NoTickDataProvider.ERROR_MESSAGE); case 1: return _context.a(2); } }, _callee); })); function getTick(_x) { return _getTick.apply(this, arguments); } return getTick; }(); _proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () { var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(_tick, _lte, _tickSpacing) { return _regenerator().w(function (_context2) { while (1) switch (_context2.n) { case 0: throw new Error(NoTickDataProvider.ERROR_MESSAGE); case 1: return _context2.a(2); } }, _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) ? invariant(false, 'TICK_SPACING_NONZERO') : void 0; // ensure ticks are spaced appropriately !ticks.every(function (_ref) { var index = _ref.index; return index % tickSpacing === 0; }) ? invariant(false, 'TICK_SPACING') : 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) ? invariant(false, 'ZERO_NET') : void 0; !isSorted(ticks, tickComparator) ? invariant(false, 'SORTED') : void 0; }; TickList.isBelowSmallest = function isBelowSmallest(ticks, tick) { !(ticks.length > 0) ? invariant(false, 'LENGTH') : void 0; return tick < ticks[0].index; }; TickList.isAtOrAboveLargest = function isAtOrAboveLargest(ticks, tick) { !(ticks.length > 0) ? invariant(false, 'LENGTH') : 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) ? invariant(false, 'NOT_CONTAINED') : 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) ? invariant(false, 'BELOW_SMALLEST') : 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) ? invariant(false, 'BELOW_SMALLEST') : 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) ? invariant(false, 'AT_OR_ABOVE_LARGEST') : 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 v3 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 ? solidity.pack(types.reverse(), path.reverse()) : solidity.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 sdkCore.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 v3 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 * v3 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.divide(JSBI.multiply(JSBI.BigInt(amount1), Q96), JSBI.subtract(sqrtRatioBX96, sqrtRatioAX96)); } /** * Computes the maximum amount of liquidity received for a given amount of token0, token1, * and the prices at the tick boundaries. * @param sqrtRatioCurrentX96 the current price * @param sqrtRatioAX96 price at lower boundary * @param sqrtRatioBX96 price at upper boundary * @param amount0 token0 amount * @param amount1 token1 amount * @param useFullPrecision if false, liquidity will be maximized according to what the router can calculate, * not what core can theoretically support */ function maxLiquidityForAmounts(sqrtRatioCurrentX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1, useFullPrecision) { if (JSBI.greaterThan(sqrtRatioAX96, sqrtRatioBX96)) { var _ref4 = [sqrtRatioBX96, sqrtRatioAX96]; sqrtRatioAX96 = _ref4[0]; sqrtRatioBX96 = _ref4[1]; } var maxLiquidityForAmount0 = useFullPrecision ? maxLiquidityForAmount0Precise : maxLiquidityForAmount0Imprecise; if (JSBI.lessThanOrEqual(sqrtRatioCurrentX96, sqrtRatioAX96)) { return maxLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (JSBI.lessThan(sqrtRatioCurrentX96, sqrtRatioBX96)) { var liquidity0 = maxLiquidityForAmount0(sqrtRatioCurrentX96, sqrtRatioBX96, amount0); var liquidity1 = maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioCurrentX96, amount1); return JSBI.lessThan(liquidity0, liquidity1) ? liquidity0 : liquidity1; } else { return maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /** * Returns the closest tick that is nearest a given tick and usable for the given tick spacing * @param tick the target tick * @param tickSpacing the spacing of the pool */ function nearestUsableTick(tick, tickSpacing) { !(Number.isInteger(tick) && Number.isInteger(tickSpacing)) ? invariant(false, 'INTEGERS') : void 0; !(tickSpacing > 0) ? invariant(false, 'TICK_SPACING') : void 0; !(tick >= TickMath.MIN_TICK && tick <= TickMath.MAX_TICK) ? invariant(false, 'TICK_BOUND') : void 0; var rounded = Math.round(tick / tickSpacing) * tickSpacing; if (rounded < TickMath.MIN_TICK) return rounded + tickSpacing;else if (rounded > TickMath.MAX_TICK) return rounded - tickSpacing;else return rounded; } var Q128 = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(128)); var PositionLibrary = /*#__PURE__*/function () { /** * Cannot be constructed. */ function PositionLibrary() {} // replicates the portions of Position#update required to compute unaccounted fees PositionLibrary.getTokensOwed = function getTokensOwed(feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, feeGrowthInside0X128, feeGrowthInside1X128) { var tokensOwed0 = JSBI.divide(JSBI.multiply(subIn256(feeGrowthInside0X128, feeGrowthInside0LastX128), liquidity), Q128); var tokensOwed1 = JSBI.divide(JSBI.multiply(subIn256(feeGrowthInside1X128, feeGrowthInside1LastX128), liquidity), Q128); return [tokensOwed0, tokensOwed1]; }; return PositionLibrary; }(); /** * Returns a price object corresponding to the input tick and the base/quote token * Inputs must be tokens because the address order is used to interpret the price represented by the tick * @param baseToken the base token of the price * @param quoteToken the quote token of the price * @param tick the tick for which to return the price */ function tickToPrice(baseToken, quoteToken, tick) { var sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); var ratioX192 = JSBI.multiply(sqrtRatioX96, sqrtRatioX96); return baseToken.sortsBefore(quoteToken) ? new sdkCore.Price(baseToken, quoteToken, Q192, ratioX192) : new sdkCore.Price(baseToken, quoteToken, ratioX192, Q192); } /** * Returns the first tick for which the given price is greater than or equal to the tick price * @param price for which to return the closest tick that represents a price less than or equal to the input price, * i.e. the price of the returned tick is less than or equal to the input price */ function priceToClosestTick(price) { var sorted = price.baseCurrency.sortsBefore(price.quoteCurrency); var sqrtRatioX96 = sorted ? encodeSqrtRatioX96(price.numerator, price.denominator) : encodeSqrtRatioX96(price.denominator, price.numerator); var tick = TickMath.getTickAtSqrtRatio(sqrtRatioX96); var nextTickPrice = tickToPrice(price.baseCurrency, price.quoteCurrency, tick + 1); if (sorted) { if (!price.lessThan(nextTickPrice)) { tick++; } } else { if (!price.greaterThan(nextTickPrice)) { tick++; } } return tick; } var Q256 = /*#__PURE__*/JSBI.exponentiate(/*#__PURE__*/JSBI.BigInt(2), /*#__PURE__*/JSBI.BigInt(256)); function subIn256(x, y) { var difference = JSBI.subtract(x, y); if (JSBI.lessThan(difference, ZERO)) { return JSBI.add(Q256, difference); } else { return difference; } } var TickLibrary = /*#__PURE__*/function () { /** * Cannot be constructed. */ function TickLibrary() {} TickLibrary.getFeeGrowthInside = function getFeeGrowthInside(feeGrowthOutsideLower, feeGrowthOutsideUpper, tickLower, tickUpper, tickCurrent, feeGrowthGlobal0X128, feeGrowthGlobal1X128) { var feeGrowthBelow0X128; var feeGrowthBelow1X128; if (tickCurrent >= tickLower) { feeGrowthBelow0X128 = feeGrowthOutsideLower.feeGrowthOutside0X128; feeGrowthBelow1X128 = feeGrowthOutsideLower.feeGrowthOutside1X128; } else { feeGrowthBelow0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideLower.feeGrowthOutside0X128); feeGrowthBelow1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideLower.feeGrowthOutside1X128); } var feeGrowthAbove0X128; var feeGrowthAbove1X128; if (tickCurrent < tickUpper) { feeGrowthAbove0X128 = feeGrowthOutsideUpper.feeGrowthOutside0X128; feeGrowthAbove1X128 = feeGrowthOutsideUpper.feeGrowthOutside1X128; } else { feeGrowthAbove0X128 = subIn256(feeGrowthGlobal0X128, feeGrowthOutsideUpper.feeGrowthOutside0X128); feeGrowthAbove1X128 = subIn256(feeGrowthGlobal1X128, feeGrowthOutsideUpper.feeGrowthOutside1X128); } return [subIn256(subIn256(feeGrowthGlobal0X128, feeGrowthBelow0X128), feeGrowthAbove0X128), subIn256(subIn256(feeGrowthGlobal1X128, feeGrowthBelow1X128), feeGrowthAbove1X128)]; }; return TickLibrary; }(); var Tick = function Tick(_ref) { var index = _ref.index, liquidityGross = _ref.liquidityGross, liquidityNet = _ref.liquidityNet; !(index >= TickMath.MIN_TICK && index <= TickMath.MAX_TICK) ? invariant(false, 'TICK') : 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__*/_regenerator().m(function _callee(tick) { return _regenerator().w(function (_context) { while (1) switch (_context.n) { case 0: return _context.a(2, TickList.getTick(this.ticks, tick)); } }, _callee, this); })); function getTick(_x) { return _getTick.apply(this, arguments); } return getTick; }(); _proto.nextInitializedTickWithinOneWord = /*#__PURE__*/function () { var _nextInitializedTickWithinOneWord = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(tick, lte, tickSpacing) { return _regenerator().w(functio