"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.token0AndToken1ByRange = exports.getAmountAndFeesFromLiquidity = exports.underlying = exports.getUnderlyingBalances = exports.getFeesEarned = exports.computeFeesEarned = void 0;
var ethers_1 = require("ethers");
var uniV3_1 = require("../uniV3");
var computeFeesEarned = function (_a) {
    var innerFeeGrowthTokenLast = _a.innerFeeGrowthTokenLast, outerFeeGrowthTokenLower = _a.outerFeeGrowthTokenLower, outerFeeGrowthTokenUpper = _a.outerFeeGrowthTokenUpper, totalFeeGrowthToken = _a.totalFeeGrowthToken, liquidity = _a.liquidity, tick = _a.tick, tickLower = _a.tickLower, tickUpper = _a.tickUpper;
    return __awaiter(void 0, void 0, void 0, function () {
        var feeGrowthLower, feeGrowthUpper, innerFeeGrowthToken, fee;
        return __generator(this, function (_b) {
            feeGrowthLower = (function () {
                if (tick >= tickLower) {
                    return outerFeeGrowthTokenLower;
                }
                else {
                    return totalFeeGrowthToken.sub(outerFeeGrowthTokenLower);
                }
            })();
            feeGrowthUpper = (function () {
                if (tick < tickUpper) {
                    return outerFeeGrowthTokenUpper;
                }
                else {
                    return totalFeeGrowthToken.sub(outerFeeGrowthTokenUpper);
                }
            })();
            innerFeeGrowthToken = totalFeeGrowthToken
                .sub(feeGrowthLower)
                .sub(feeGrowthUpper);
            fee = liquidity
                .mul(innerFeeGrowthToken.sub(innerFeeGrowthTokenLast))
                .div('0x100000000000000000000000000000000');
            return [2 /*return*/, fee];
        });
    });
};
exports.computeFeesEarned = computeFeesEarned;
var getFeesEarned = function (_a) {
    var innerFeeGrowth0TokenLast = _a.innerFeeGrowth0TokenLast, innerFeeGrowth1TokenLast = _a.innerFeeGrowth1TokenLast, liquidityAmount = _a.liquidityAmount, pool = _a.pool, tick = _a.tick, tickLower = _a.tickLower, tickUpper = _a.tickUpper;
    return __awaiter(void 0, void 0, void 0, function () {
        var _b, _c, outerFeeGrowth0TokenLower, outerFeeGrowth1TokenLower, _d, outerFeeGrowth0TokenUpper, outerFeeGrowth1TokenUpper, totalFeeGrowth0Token, totalFeeGrowth1Token, _e, fee0, fee1;
        return __generator(this, function (_f) {
            switch (_f.label) {
                case 0: return [4 /*yield*/, Promise.all([
                        pool.ticks(tickLower),
                        pool.ticks(tickUpper),
                        pool.totalFeeGrowth0Token(),
                        pool.totalFeeGrowth1Token(),
                    ])];
                case 1:
                    _b = __read.apply(void 0, [_f.sent(), 4]), _c = _b[0], outerFeeGrowth0TokenLower = _c.outerFeeGrowth0Token, outerFeeGrowth1TokenLower = _c.outerFeeGrowth1Token, _d = _b[1], outerFeeGrowth0TokenUpper = _d.outerFeeGrowth0Token, outerFeeGrowth1TokenUpper = _d.outerFeeGrowth1Token, totalFeeGrowth0Token = _b[2], totalFeeGrowth1Token = _b[3];
                    return [4 /*yield*/, Promise.all([
                            (0, exports.computeFeesEarned)({
                                innerFeeGrowthTokenLast: innerFeeGrowth0TokenLast,
                                outerFeeGrowthTokenLower: outerFeeGrowth0TokenLower,
                                outerFeeGrowthTokenUpper: outerFeeGrowth0TokenUpper,
                                totalFeeGrowthToken: totalFeeGrowth0Token,
                                liquidity: liquidityAmount,
                                tick: tick,
                                tickLower: tickLower,
                                tickUpper: tickUpper,
                            }),
                            (0, exports.computeFeesEarned)({
                                innerFeeGrowthTokenLast: innerFeeGrowth1TokenLast,
                                outerFeeGrowthTokenLower: outerFeeGrowth1TokenLower,
                                outerFeeGrowthTokenUpper: outerFeeGrowth1TokenUpper,
                                totalFeeGrowthToken: totalFeeGrowth1Token,
                                liquidity: liquidityAmount,
                                tick: tick,
                                tickLower: tickLower,
                                tickUpper: tickUpper,
                            }),
                        ])];
                case 2:
                    _e = __read.apply(void 0, [_f.sent(), 2]), fee0 = _e[0], fee1 = _e[1];
                    return [2 /*return*/, { fee0: fee0, fee1: fee1 }];
            }
        });
    });
};
exports.getFeesEarned = getFeesEarned;
var getAmount0ForLiquidity = function (_a) {
    var liquidity = _a.liquidity, sqrtRatioAX96 = _a.sqrtRatioAX96, sqrtRatioBX96 = _a.sqrtRatioBX96;
    return liquidity
        .shl(96)
        .mul(sqrtRatioBX96.sub(sqrtRatioAX96))
        .div(sqrtRatioBX96)
        .div(sqrtRatioAX96);
};
var getAmount1ForLiquidity = function (_a) {
    var liquidity = _a.liquidity, sqrtRatioAX96 = _a.sqrtRatioAX96, sqrtRatioBX96 = _a.sqrtRatioBX96;
    return liquidity
        .mul(sqrtRatioBX96.sub(sqrtRatioAX96))
        .div('0x1000000000000000000000000');
};
var getAmountsForLiquidity = function (_a) {
    var _b;
    var liquidity = _a.liquidity, sqrtRatioAX96 = _a.sqrtRatioAX96, sqrtRatioBX96 = _a.sqrtRatioBX96, sqrtRatioX96 = _a.sqrtRatioX96;
    var ab = [sqrtRatioAX96, sqrtRatioBX96];
    if (sqrtRatioAX96.gt(sqrtRatioBX96)) {
        ab.reverse();
    }
    _b = __read(ab, 2), sqrtRatioAX96 = _b[0], sqrtRatioBX96 = _b[1];
    if (sqrtRatioX96.lte(sqrtRatioAX96)) {
        return {
            amount0: getAmount0ForLiquidity({
                liquidity: liquidity,
                sqrtRatioAX96: sqrtRatioAX96,
                sqrtRatioBX96: sqrtRatioBX96,
            }),
            amount1: ethers_1.BigNumber.from(0),
        };
    }
    else if (sqrtRatioX96.lt(sqrtRatioBX96)) {
        return {
            amount0: getAmount0ForLiquidity({
                liquidity: liquidity,
                sqrtRatioAX96: sqrtRatioAX96,
                sqrtRatioBX96: sqrtRatioBX96,
            }),
            amount1: getAmount1ForLiquidity({
                liquidity: liquidity,
                sqrtRatioAX96: sqrtRatioAX96,
                sqrtRatioBX96: sqrtRatioBX96,
            }),
        };
    }
    else {
        return {
            amount0: ethers_1.BigNumber.from(0),
            amount1: getAmount1ForLiquidity({
                liquidity: liquidity,
                sqrtRatioAX96: sqrtRatioAX96,
                sqrtRatioBX96: sqrtRatioBX96,
            }),
        };
    }
};
var getUnderlyingBalances = function (_a) {
    var positionId = _a.positionId, pool = _a.pool, sqrtPriceX96 = _a.sqrtPriceX96, tick = _a.tick, tickLower = _a.tickLower, tickUpper = _a.tickUpper;
    return __awaiter(void 0, void 0, void 0, function () {
        var _b, liquidityAmount, innerFeeGrowth0Token, innerFeeGrowth1Token, fees0, fees1, _c, fee0, fee1, _d, amount0, amount1, _e, fees0Res, fees1Res;
        return __generator(this, function (_f) {
            switch (_f.label) {
                case 0: return [4 /*yield*/, pool.positions(positionId)];
                case 1:
                    _b = _f.sent(), liquidityAmount = _b.liquidityAmount, innerFeeGrowth0Token = _b.innerFeeGrowth0Token, innerFeeGrowth1Token = _b.innerFeeGrowth1Token, fees0 = _b.fees0, fees1 = _b.fees1;
                    return [4 /*yield*/, (0, exports.getFeesEarned)({
                            innerFeeGrowth0TokenLast: innerFeeGrowth0Token,
                            innerFeeGrowth1TokenLast: innerFeeGrowth1Token,
                            liquidityAmount: liquidityAmount,
                            pool: pool,
                            tick: tick,
                            tickLower: tickLower,
                            tickUpper: tickUpper,
                        })];
                case 2:
                    _c = _f.sent(), fee0 = _c.fee0, fee1 = _c.fee1;
                    _d = getAmountsForLiquidity({
                        liquidity: liquidityAmount,
                        sqrtRatioAX96: ethers_1.BigNumber.from((0, uniV3_1.getSqrtRatioAtTick)(tickLower.toNumber()).toString()),
                        sqrtRatioBX96: ethers_1.BigNumber.from((0, uniV3_1.getSqrtRatioAtTick)(tickUpper.toNumber()).toString()),
                        sqrtRatioX96: sqrtPriceX96,
                    }), amount0 = _d.amount0, amount1 = _d.amount1;
                    _e = __read([fees0.add(fee0), fees1.add(fee1)], 2), fees0Res = _e[0], fees1Res = _e[1];
                    return [2 /*return*/, {
                            fees0: fees0Res,
                            fees1: fees1Res,
                            amount0: amount0,
                            amount1: amount1,
                            liquidityAmount: liquidityAmount,
                        }];
            }
        });
    });
};
exports.getUnderlyingBalances = getUnderlyingBalances;
var underlying = function (_a) {
    var pool = _a.pool, tickLower = _a.tickLower, tickUpper = _a.tickUpper, sqrtPriceX96 = _a.sqrtPriceX96, strategy = _a.strategy;
    return __awaiter(void 0, void 0, void 0, function () {
        var _b, price, tick, positionIdPacked, positionId;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0: return [4 /*yield*/, pool.globalState()];
                case 1:
                    _b = _c.sent(), price = _b.price, tick = _b.tick;
                    positionIdPacked = ethers_1.utils.solidityPack(['address', 'int24', 'int24'], [strategy, tickLower, tickUpper]);
                    positionId = ethers_1.utils.hexZeroPad(positionIdPacked, 32);
                    return [4 /*yield*/, (0, exports.getUnderlyingBalances)({
                            pool: pool,
                            positionId: positionId,
                            sqrtPriceX96: sqrtPriceX96 !== null && sqrtPriceX96 !== void 0 ? sqrtPriceX96 : price,
                            tick: ethers_1.BigNumber.from(tick),
                            tickLower: tickLower,
                            tickUpper: tickUpper,
                        })];
                case 2: return [2 /*return*/, _c.sent()];
            }
        });
    });
};
exports.underlying = underlying;
var getAmountAndFeesFromLiquidity = function (_a) {
    var strategy = _a.strategy, tickLower = _a.tickLower, tickUpper = _a.tickUpper, pool = _a.pool;
    return __awaiter(void 0, void 0, void 0, function () {
        var _b, amount0, amount1, fees0, fees1, liquidityAmount;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0: return [4 /*yield*/, (0, exports.underlying)({
                        pool: pool,
                        strategy: strategy,
                        tickLower: tickLower,
                        tickUpper: tickUpper,
                    })];
                case 1:
                    _b = _c.sent(), amount0 = _b.amount0, amount1 = _b.amount1, fees0 = _b.fees0, fees1 = _b.fees1, liquidityAmount = _b.liquidityAmount;
                    return [2 /*return*/, {
                            amount0: amount0.add(fees0),
                            amount1: amount1.add(fees1),
                            fees0: fees0,
                            fees1: fees1,
                            liquidityAmount: liquidityAmount,
                        }];
            }
        });
    });
};
exports.getAmountAndFeesFromLiquidity = getAmountAndFeesFromLiquidity;
var token0AndToken1ByRange = function (_a) {
    var pool = _a.pool, ticks = _a.ticks, strategy = _a.strategy;
    return Promise.all(ticks.map(function (_a) {
        var tickLower = _a.tickLower, tickUpper = _a.tickUpper;
        return __awaiter(void 0, void 0, void 0, function () {
            var _b, amount0, amount1, liquidityAmount, fees0, fees1;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, (0, exports.getAmountAndFeesFromLiquidity)({
                            pool: pool,
                            strategy: strategy,
                            tickLower: ethers_1.BigNumber.from(tickLower),
                            tickUpper: ethers_1.BigNumber.from(tickUpper),
                        })];
                    case 1:
                        _b = _c.sent(), amount0 = _b.amount0, amount1 = _b.amount1, liquidityAmount = _b.liquidityAmount, fees0 = _b.fees0, fees1 = _b.fees1;
                        return [2 /*return*/, {
                                amount0: amount0,
                                amount1: amount1,
                                tickLower: tickLower,
                                tickUpper: tickUpper,
                                liquidityAmount: liquidityAmount,
                                fees0: fees0,
                                fees1: fees1,
                            }];
                }
            });
        });
    }));
};
exports.token0AndToken1ByRange = token0AndToken1ByRange;
//# sourceMappingURL=utils.js.map