"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniV3MMMaxLp = void 0;
var uniV3Range_1 = require("./uniV3Range");
var uniV3Utils_1 = require("./uniV3Utils");
var types_1 = require("./types");
var uniV3MMUtils_1 = require("./uniV3MMUtils");
var uniV3MM_1 = require("./uniV3MM");
var uniV3MMMaxLp = /** @class */ (function (_super) {
    __extends(uniV3MMMaxLp, _super);
    function uniV3MMMaxLp(vault, wallet, feeTier, // uniswap fee tier
    chain, options, useMovingAvg) {
        if (useMovingAvg === void 0) { useMovingAvg = true; }
        var _this = _super.call(this, vault, wallet, feeTier, chain, options, useMovingAvg) || this;
        _this.vault = vault;
        _this.wallet = wallet;
        _this.feeTier = feeTier;
        _this.chain = chain;
        _this.useMovingAvg = useMovingAvg;
        _this.rebalances = [];
        _this.prevBalances = [0, 0];
        _this.leftoverRebalance = [0, 0];
        _this.tempState = {
            rebalances: [],
            prevBalances: [],
            leftoverRebalance: [],
        };
        return _this;
    }
    uniV3MMMaxLp.prototype.initPosition = function () {
        return __awaiter(this, void 0, void 0, function () {
            var totals;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.prevReb = this.price;
                        return [4 /*yield*/, this.getBalances()];
                    case 1:
                        totals = (_a.sent()).totals;
                        this.prevBalances = __spreadArray([], __read(totals), false);
                        this.rebalances = [];
                        this.leftoverRebalance = [0, 0];
                        return [4 /*yield*/, this.syncToDB()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    uniV3MMMaxLp.prototype.rebalanceRanges = function () {
        return __awaiter(this, void 0, void 0, function () {
            var price, _a, mainLow, mainHigh, secRangeLow, secRangeHigh, _b, totals, allocated, burnRanges, _c, base, quote, maxBase, maxQuote, mainLp, extraBase, extraQuote, _d, secBaseValue, secQuoteValue, low, mainRange, high, hFull, lFull, _e, updatedRanges, leftoverRebalance, _f, l, m, h, rebalanceParams, success;
            return __generator(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        // this can happen async so we want to ensure a flag is set
                        if (this.isRebalancing)
                            return [2 /*return*/];
                        this.isRebalancing = true;
                        price = this.price;
                        _a = this.getRanges(price), mainLow = _a.mainLow, mainHigh = _a.mainHigh, secRangeLow = _a.secRangeLow, secRangeHigh = _a.secRangeHigh;
                        return [4 /*yield*/, this.getBalances()];
                    case 1:
                        _b = _g.sent(), totals = _b.totals, allocated = _b.allocated;
                        this.inventory = totals;
                        this.allocated = allocated;
                        // mutates state
                        this.updateRebalanceRecord();
                        burnRanges = __spreadArray([], __read(this.ranges), false);
                        this.ranges = [];
                        _c = __read((0, uniV3Utils_1.tokensForStrategy)(mainLow, mainHigh, 1, price), 2), base = _c[0], quote = _c[1];
                        maxBase = this.inventory[0] / base;
                        maxQuote = this.inventory[1] / quote;
                        mainLp = Math.min(maxBase, maxQuote) * this.mainRangeShare;
                        extraBase = (this.inventory[0] - mainLp * base) * 0.99;
                        extraQuote = (this.inventory[1] - mainLp * quote) * 0.99;
                        _d = this.getRangeAmounts(mainLp, extraBase, extraQuote), secBaseValue = _d.secBaseValue, secQuoteValue = _d.secQuoteValue;
                        console.log('sec base / quote', mainLp, secBaseValue, secQuoteValue);
                        low = new uniV3Range_1.UniV3Range(this, secQuoteValue, secRangeLow, mainLow);
                        mainRange = new uniV3Range_1.UniV3Range(this, mainLp, mainLow, mainHigh);
                        high = new uniV3Range_1.UniV3Range(this, secBaseValue, mainHigh, secRangeHigh);
                        hFull = new uniV3Range_1.UniV3Range(this, extraBase * price - secBaseValue, secRangeHigh, uniV3Utils_1.MAX_PRICE);
                        lFull = new uniV3Range_1.UniV3Range(this, extraQuote - secQuoteValue, uniV3Utils_1.MIN_PRICE, secRangeLow);
                        return [4 /*yield*/, this.findRangeAmounts([lFull, low, mainRange, high, hFull], mainLp)];
                    case 2:
                        _e = _g.sent(), updatedRanges = _e.updatedRanges, leftoverRebalance = _e.leftoverRebalance;
                        this.tempState.leftoverRebalance = leftoverRebalance;
                        _f = __read(updatedRanges, 3), l = _f[0], m = _f[1], h = _f[2];
                        this.ranges = [l, m, h];
                        this.logRanges();
                        return [4 /*yield*/, this.getRebalanceParams(burnRanges)];
                    case 3:
                        rebalanceParams = _g.sent();
                        return [4 /*yield*/, this.executeRebalance(rebalanceParams)];
                    case 4:
                        success = _g.sent();
                        if (!success) return [3 /*break*/, 6];
                        this.prevReb = price;
                        this.rebalances = __spreadArray([], __read(this.tempState.rebalances), false);
                        this.prevBalances = __spreadArray([], __read(this.tempState.prevBalances), false);
                        this.leftoverRebalance = __spreadArray([], __read(this.tempState.leftoverRebalance), false);
                        // update state store
                        return [4 /*yield*/, this.syncToDB()];
                    case 5:
                        // update state store
                        _g.sent();
                        return [3 /*break*/, 7];
                    case 6:
                        // undo range update if tx failed
                        this.ranges = __spreadArray([], __read(burnRanges), false);
                        _g.label = 7;
                    case 7:
                        this.isRebalancing = false;
                        return [2 /*return*/, rebalanceParams];
                }
            });
        });
    };
    uniV3MMMaxLp.prototype.getRangeAmounts = function (mainLp, extraBase, extraQuote) {
        var _a = this, price = _a.price, rebalances = _a.rebalances, secRangeShare = _a.secRangeShare;
        var _b = (0, uniV3MMUtils_1.getCostBasisParams)(rebalances), dBase = _b.dBase, dQuote = _b.dQuote, adjustLowRange = _b.adjustLowRange, adjustHighRange = _b.adjustHighRange;
        var minBase = mainLp / 100;
        var minQuote = mainLp / 100;
        var adjBaseValue = Math.min((extraBase * price * secRangeShare) / 2, Math.max(minBase, dBase * price - mainLp / 2));
        var adjQuoteValue = Math.min((extraQuote * secRangeShare) / 2, Math.max(minQuote, dQuote - mainLp / 2));
        // adjust range size (this assumes rebalance weight is 1)
        var secBaseValue = adjustHighRange
            ? adjBaseValue
            : (extraBase * price * this.secRangeShare) / 2;
        var secQuoteValue = adjustLowRange
            ? adjQuoteValue
            : (extraQuote * this.secRangeShare) / 2;
        return { secBaseValue: secBaseValue, secQuoteValue: secQuoteValue };
    };
    uniV3MMMaxLp.prototype.getCostBasis = function () {
        var _a = this, inventory = _a.inventory, prevBalances = _a.prevBalances;
        // if prevBalance is 0,0 we don't have a cost basis
        if (prevBalances[0] == 0 && prevBalances[1] == 0)
            return types_1.emptyRecord;
        var dBase = inventory[0] - prevBalances[0];
        var dQuote = inventory[1] - prevBalances[1];
        var costBasis = dBase == 0 || dQuote == 0 ? 0 : (dQuote / dBase) * (dBase > 0 ? 1 : -1);
        // this.prevBalances = [this.base, this.quoteValue];
        return { costBasis: costBasis, dBase: dBase, dQuote: dQuote };
    };
    // This method will update this.tempState so we can clear it
    // in case the rebalance tx reverts
    uniV3MMMaxLp.prototype.updateRebalanceRecord = function () {
        var _a = this, price = _a.price, inventory = _a.inventory;
        var rebRecord = this.getCostBasis();
        var costBasis = rebRecord.costBasis, dBase = rebRecord.dBase, dQuote = rebRecord.dQuote;
        var prevCostBasis = (this.rebalances[this.rebalances.length - 1] || types_1.emptyRecord).costBasis;
        // STATE UPDATES
        // write to temp state in case our tx getx reverted
        this.tempState.prevBalances = __spreadArray([], __read(inventory), false);
        var tmpRebalances = __spreadArray([], __read(this.rebalances), false);
        // const direction = price > this.prevReb ? 1 : -1;
        // if prev reb directions was the same, push to rebalance array
        if ((prevCostBasis == 0 && costBasis != 0) ||
            costBasis / prevCostBasis > 0) {
            // update temp state in case tx reverts
            tmpRebalances.push({ costBasis: costBasis, dBase: dBase, dQuote: dQuote });
        }
        // otherwise pop the array since we're going in opposite direction
        else if (costBasis / prevCostBasis < 0) {
            // remove all elements that are above the current price
            if (prevCostBasis < 0) {
                // temp rebalances state in case tx reverts
                tmpRebalances = tmpRebalances.filter(function (r) { return price < Math.abs(r.costBasis); });
                // remove all elements that are below the current price
            }
            else if (prevCostBasis > 0) {
                console.log('filter out', tmpRebalances.map(function (r) { return r.costBasis; }), price);
                // temp rebalances state in case tx reverts
                tmpRebalances = tmpRebalances.filter(function (r) { return price > Math.abs(r.costBasis); });
            }
            // add leftover base to the last rebalance
            // we do this to make sure we are accounting for
            // under-trading when rebalancing in opposite direction
            var lastRebId = tmpRebalances.length - 1;
            if (tmpRebalances.length) {
                var _b = tmpRebalances[lastRebId], dBase_1 = _b.dBase, costBasis_1 = _b.costBasis;
                var _c = __read(this.leftoverRebalance, 2), leftoverBase = _c[0], leftoverQuote = _c[1];
                // make a copy of the rebalance record we are updating so we don't update both
                var lastReb = __assign({}, tmpRebalances[lastRebId]);
                lastReb.costBasis =
                    (costBasis_1 * dBase_1 + prevCostBasis * leftoverBase) /
                        (dBase_1 + leftoverBase);
                lastReb.dBase += leftoverBase;
                lastReb.dQuote += leftoverQuote;
                tmpRebalances[lastRebId] = lastReb;
                // tmp leftover rebalance state
                this.tempState.leftoverRebalance = [0, 0];
            }
        }
        this.tempState.rebalances = tmpRebalances;
    };
    uniV3MMMaxLp.prototype.findRangeAmounts = function (ranges, mainValue) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, lFull, low, mainRange, high, hFull, _b, price, rebalances, _c, costBasis, adjustHighRange, adjustLowRange, prevCost, adjustCost, expectedCostBasis, leftoverRebalance, matchingCost, i, maxIter, foundMatchingCost, newValue, newValue;
            var _this = this;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _a = __read(ranges, 5), lFull = _a[0], low = _a[1], mainRange = _a[2], high = _a[3], hFull = _a[4];
                        _b = this, price = _b.price, rebalances = _b.rebalances;
                        _c = (0, uniV3MMUtils_1.getCostBasisParams)(rebalances), costBasis = _c.costBasis, adjustHighRange = _c.adjustHighRange, adjustLowRange = _c.adjustLowRange;
                        prevCost = Math.abs(costBasis);
                        adjustCost = 0.1;
                        // if adjust high range we want cost to be higher (we want to sell base tokens for more)
                        // if we adjust low range want cost to be lower (we want to buy base tokens for less)
                        if (!adjustHighRange && !adjustLowRange)
                            return [2 /*return*/, {
                                    updatedRanges: [low, mainRange, high],
                                    leftoverRebalance: [0, 0],
                                }];
                        expectedCostBasis = 0;
                        leftoverRebalance = [0, 0];
                        matchingCost = function () { return __awaiter(_this, void 0, void 0, function () {
                            var _a;
                            return __generator(this, function (_b) {
                                switch (_b.label) {
                                    case 0: return [4 /*yield*/, this.getExpectedCostBasis(low, mainRange, high)];
                                    case 1:
                                        (_a = _b.sent(), expectedCostBasis = _a.expectedCostBasis, leftoverRebalance = _a.leftoverRebalance);
                                        expectedCostBasis = Math.abs(expectedCostBasis);
                                        if (adjustHighRange && expectedCostBasis > prevCost * (1 + adjustCost))
                                            return [2 /*return*/, true];
                                        else if (adjustLowRange &&
                                            expectedCostBasis < prevCost * (1 - adjustCost))
                                            return [2 /*return*/, true];
                                        return [2 /*return*/, false];
                                }
                            });
                        }); };
                        i = 0;
                        maxIter = 10;
                        foundMatchingCost = false;
                        _d.label = 1;
                    case 1:
                        if (!(!foundMatchingCost && i < maxIter)) return [3 /*break*/, 3];
                        if (adjustHighRange) {
                            newValue = 0.95 * (high.base * price + high.quote);
                            if (newValue < mainValue * 0.2)
                                i = maxIter;
                            high = new uniV3Range_1.UniV3Range(this, newValue, high.minRange, high.maxRange);
                        }
                        else if (adjustLowRange) {
                            newValue = 0.95 * (low.base * price + low.quote);
                            if (newValue < mainValue * 0.2)
                                i = maxIter;
                            low = new uniV3Range_1.UniV3Range(this, newValue, low.minRange, low.maxRange);
                        }
                        return [4 /*yield*/, matchingCost()];
                    case 2:
                        foundMatchingCost = _d.sent();
                        i++;
                        return [3 /*break*/, 1];
                    case 3:
                        // console.log(new Date(this.lastTimestamp * 1000));
                        // console.log('prev cost vs price', costBasis, this.price);
                        // console.log(this.rebalances.map((r) => r.costBasis));
                        if (i >= maxIter) {
                            // console.log('could not find matching cost', expectedCostBasis, prevCost);
                        }
                        // console.log(this.rebalances.map((r) => r.dBase));
                        return [2 /*return*/, { updatedRanges: [low, mainRange, high], leftoverRebalance: leftoverRebalance }];
                }
            });
        });
    };
    uniV3MMMaxLp.prototype.getExpectedCostBasis = function (low, mainRange, high) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, price, rebalances, _b, dBase, dQuote, adjustLowRange, _c, mainDBase, mainDQuote, _d, rebalanceLow, rebalanceHigh, mainRangeValue, nextPrice, _e, secDBase, secDQuote, expdBase, leftoverBase, leftoverQuote, _f, bid, ask, nextMainRange, _g, nextMainDBase, nextMainDQuote, totalQuote, totalBase, projectedCostBasis;
            return __generator(this, function (_h) {
                switch (_h.label) {
                    case 0:
                        _a = this, price = _a.price, rebalances = _a.rebalances;
                        _b = (0, uniV3MMUtils_1.getCostBasisParams)(rebalances), dBase = _b.dBase, dQuote = _b.dQuote, adjustLowRange = _b.adjustLowRange;
                        _c = mainRange.dTokensAtPrice(price, adjustLowRange ? mainRange.minRange : mainRange.maxRange), mainDBase = _c.dBase, mainDQuote = _c.dQuote;
                        return [4 /*yield*/, this.getRebalancePoints(price)];
                    case 1:
                        _d = _h.sent(), rebalanceLow = _d.rebalanceLow, rebalanceHigh = _d.rebalanceHigh;
                        mainRangeValue = mainRange.base * price + mainRange.quote;
                        nextPrice = adjustLowRange ? rebalanceLow : rebalanceHigh;
                        _e = adjustLowRange
                            ? low.dTokensAtPrice(low.maxRange, rebalanceLow)
                            : high.dTokensAtPrice(high.minRange, rebalanceHigh), secDBase = _e.dBase, secDQuote = _e.dQuote;
                        expdBase = mainDBase + secDBase;
                        leftoverBase = (dBase - Math.abs(expdBase)) * (expdBase < 0 ? 1 : -1);
                        leftoverQuote = (dQuote - Math.abs(mainDQuote)) * (mainDQuote < 0 ? 1 : -1);
                        _f = this.getBidAsk(nextPrice), bid = _f.bid, ask = _f.ask;
                        nextMainRange = new uniV3Range_1.UniV3Range(this, mainRangeValue, bid, ask, undefined, undefined, undefined, nextPrice);
                        _g = nextMainRange.simulateSwap({
                            dBase: -leftoverBase,
                            dQuote: 0,
                            timestamp: 0,
                        }, nextPrice, true), nextMainDBase = _g.swappedBase, nextMainDQuote = _g.swappedQuote;
                        totalQuote = mainDQuote + secDQuote + nextMainDQuote;
                        totalBase = expdBase + nextMainDBase;
                        projectedCostBasis = (totalQuote / totalBase) * (totalBase > 1 ? 1 : -1);
                        // projected cost basis includes the following rebalance
                        // (its not precise but is a min estimate)
                        // const projectedCostBasis2 =
                        //   (Math.abs(expectedCostBasis) * Math.abs(expdBase) +
                        //     Math.abs(leftoverBase) * nextPrice) /
                        //   dBase;
                        return [2 /*return*/, {
                                expectedCostBasis: Math.abs(projectedCostBasis),
                                leftoverRebalance: [leftoverBase, leftoverQuote],
                            }];
                }
            });
        });
    };
    return uniV3MMMaxLp;
}(uniV3MM_1.UniV3MM));
exports.uniV3MMMaxLp = uniV3MMMaxLp;
//# sourceMappingURL=uniV3MMMaxLp.js.map