@aryze/v3-sdk
Version:
⚒️ An SDK for building applications on top of MAMA V3
1,148 lines (1,124 loc) • 142 kB
JavaScript
'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('@aryze/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('@aryze/v3-periphery/artifacts/contracts/interfaces/IMulticall.sol/IMulticall.json'));
var INonfungiblePositionManager = _interopDefault(require('@aryze/v3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json'));
var IPeripheryPaymentsWithFee = _interopDefault(require('@aryze/v3-periphery/artifacts/contracts/interfaces/IPeripheryPaymentsWithFee.sol/IPeripheryPaymentsWithFee.json'));
var ISelfPermit = _interopDefault(require('@aryze/v3-periphery/artifacts/contracts/interfaces/ISelfPermit.sol/ISelfPermit.json'));
var IQuoterV2 = _interopDefault(require('@aryze/swap-router-contracts/artifacts/contracts/lens/QuoterV2.sol/QuoterV2.json'));
var IQuoter = _interopDefault(require('@aryze/v3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json'));
var IAryzeV3Staker = _interopDefault(require('@aryze/v3-staker/artifacts/contracts/AryzeV3Staker.sol/AryzeV3Staker.json'));
var ISwapRouter = _interopDefault(require('@aryze/v3-periphery/artifacts/contracts/SwapRouter.sol/SwapRouter.json'));
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 _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 FACTORY_ADDRESS = '0xE7aE959bbC94BDF2E9FF28a214840aB3285d7765';
var ADDRESS_ZERO = '0x0000000000000000000000000000000000000000';
var POOL_INIT_CODE_HASH = '0x8aeb7d9c447c5c3f6ad05ba4da15b42c982c77c5791901c09fef871b1a52e2e2';
(function (FeeAmount) {
FeeAmount[FeeAmount["LOWEST"] = 100] = "LOWEST";
FeeAmount[FeeAmount["LOW"] = 500] = "LOW";
FeeAmount[FeeAmount["LOWER_MEDIUM"] = 1000] = "LOWER_MEDIUM";
FeeAmount[FeeAmount["MEDIA_MEDIUM"] = 2000] = "MEDIA_MEDIUM";
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] = 10, _TICK_SPACINGS[exports.FeeAmount.LOWER_MEDIUM] = 20, _TICK_SPACINGS[exports.FeeAmount.MEDIA_MEDIUM] = 40, _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 Aryze 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
* @returns The pool address
*/
function computePoolAddress(_ref) {
var factoryAddress = _ref.factoryAddress,
tokenA = _ref.tokenA,
tokenB = _ref.tokenB,
fee = _ref.fee,
initCodeHashManualOverride = _ref.initCodeHashManualOverride;
var _ref2 = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA],
token0 = _ref2[0],
token1 = _ref2[1]; // does safety checks
return address.getCreate2Address(factoryAddress, solidity.keccak256(['bytes'], [abi.defaultAbiCoder.encode(['address', 'address', 'uint24'], [token0.address, token1.address, fee])]), initCodeHashManualOverride != null ? initCodeHashManualOverride : POOL_INIT_CODE_HASH);
}
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 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 = {};
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, JSBI.BigInt(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, JSBI.BigInt(feePips), JSBI.subtract(MAX_FEE, JSBI.BigInt(feePips)));
}
return [returnValues.sqrtRatioNextX96, returnValues.amountIn, returnValues.amountOut, returnValues.feeAmount];
};
return SwapMath;
}();
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');
/**
* 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) ? 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(fee