"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.MaxLpStrategy = exports.defaultConfig = void 0;
var types_1 = require("../types");
var strategy_1 = require("./strategy");
var uniV3Range_1 = require("../uniV3Range");
var uniV3Utils_1 = require("../uniV3Utils");
var arkiveQueries_1 = require("../arkiveQueries");
var uniV3MMUtils_1 = require("../uniV3MMUtils");
exports.defaultConfig = {
    mainRangeOffset: 0.08,
    secondaryRangeOffset: 0.2,
    rebalanceWeight: 0.2,
    mainRangeShare: 0.05,
    secRangeShare: 0.05 * 2,
};
var MA_TIME_INTERVAL = 6 * 30 * 60; // 30 minutes
var MaxLpStrategy = /** @class */ (function (_super) {
    __extends(MaxLpStrategy, _super);
    function MaxLpStrategy(vaultProvider, params) {
        var _this = _super.call(this, vaultProvider) || this;
        _this.state = {
            rebalances: [],
            prevBalances: [0, 0],
            leftoverRebalance: [0, 0],
        };
        _this.tempState = {
            rebalances: [],
            prevBalances: [0, 0],
            leftoverRebalance: [0, 0],
        };
        _this.lastTimestamp = 0;
        _this.inventory = [0, 0];
        _this.allocated = [0, 0];
        _this.prevReb = 0;
        _this.movingAvg = 0;
        _this.maInterval = MA_TIME_INTERVAL;
        _this.isRebalancing = false;
        var mergedParams = __assign(__assign({}, exports.defaultConfig), params);
        _this.vaultProvider = vaultProvider;
        _this.dbProvider = params.dbProvider;
        _this.mainRangeOffset = mergedParams.mainRangeOffset;
        _this.secondaryRangeOffset = mergedParams.secondaryRangeOffset;
        _this.rebalanceWeight = mergedParams.rebalanceWeight;
        _this.mainRangeShare = mergedParams.mainRangeShare;
        _this.secRangeShare = mergedParams.secRangeShare;
        _this.rebalanceLow = mergedParams.secondaryRangeOffset;
        _this.rebalanceHigh = mergedParams.secondaryRangeOffset;
        _this.useMovingAvg = mergedParams.useMovingAvg;
        _this.initPromise = _this.init();
        return _this;
    }
    MaxLpStrategy.create = function (vaultProvider, params) {
        return __awaiter(this, void 0, void 0, function () {
            var strategy;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        strategy = new MaxLpStrategy(vaultProvider, params);
                        return [4 /*yield*/, strategy.ready()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, strategy];
                }
            });
        });
    };
    MaxLpStrategy.prototype.ready = function () {
        return this.initPromise;
    };
    MaxLpStrategy.prototype.init = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.vaultProvider.ranges.length > 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.syncFromDB()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    MaxLpStrategy.prototype.update = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, useMovingAvg, price, movingAvg, _b, isEmpty, _c, rebalanceLow, rebalanceHigh;
            var _this = this;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        if (this.isRebalancing)
                            return [2 /*return*/];
                        _a = this.vaultProvider;
                        return [4 /*yield*/, this.vaultProvider.getPrice(0)];
                    case 1:
                        _a.price = _d.sent();
                        useMovingAvg = this.useMovingAvg;
                        price = this.vaultProvider.price;
                        if (!useMovingAvg) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.updateMovingAvg()];
                    case 2:
                        _b = _d.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        _b = price;
                        _d.label = 4;
                    case 4:
                        movingAvg = _b;
                        isEmpty = function () {
                            return _this.vaultProvider.ranges.length == 0 ||
                                (_this.vaultProvider.ranges.length === 1 &&
                                    _this.vaultProvider.ranges[0].liquidity === '0');
                        };
                        if (!isEmpty()) return [3 /*break*/, 9];
                        // make check if the position has been opened from front end
                        return [4 /*yield*/, this.vaultProvider.updateRanges()];
                    case 5:
                        // make check if the position has been opened from front end
                        _d.sent();
                        if (!isEmpty()) return [3 /*break*/, 6];
                        return [2 /*return*/];
                    case 6: return [4 /*yield*/, this.updateMovingAvg(true)];
                    case 7:
                        _d.sent();
                        return [4 /*yield*/, this.initPosition()];
                    case 8:
                        _d.sent();
                        _d.label = 9;
                    case 9: return [4 /*yield*/, this.getRebalancePoints()];
                    case 10:
                        _c = _d.sent(), rebalanceLow = _c.rebalanceLow, rebalanceHigh = _c.rebalanceHigh;
                        if (!(movingAvg < rebalanceLow || movingAvg > rebalanceHigh)) return [3 /*break*/, 13];
                        return [4 /*yield*/, this.vaultProvider.updateRanges()];
                    case 11:
                        _d.sent();
                        // if the position was closed from the front end
                        // and there are no more ranges, abort
                        if (this.vaultProvider.ranges.length === 0)
                            return [2 /*return*/];
                        return [4 /*yield*/, this.rebalanceRanges()];
                    case 12:
                        _d.sent();
                        _d.label = 13;
                    case 13: return [2 /*return*/];
                }
            });
        });
    };
    MaxLpStrategy.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.vaultProvider.price;
                        return [4 /*yield*/, this.vaultProvider.getBalances()];
                    case 1:
                        totals = (_a.sent()).totals;
                        this.state.prevBalances = __spreadArray([], __read(totals), false);
                        this.state.rebalances = [];
                        this.state.leftoverRebalance = [0, 0];
                        return [4 /*yield*/, this.syncToDB()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    MaxLpStrategy.prototype.updateMovingAvg = function (reInit) {
        if (reInit === void 0) { reInit = false; }
        return __awaiter(this, void 0, void 0, function () {
            var timestamp, price, time;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.dbProvider) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.dbProvider.updateMovingAvg({
                                ma_interval: this.maInterval,
                                price: this.vaultProvider.price,
                                reInit: reInit,
                            })];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        timestamp = Math.round(Date.now() / 1000);
                        price = this.vaultProvider.price;
                        // reset moving avg
                        if (reInit)
                            return [2 /*return*/, (this.movingAvg = price)];
                        time = Math.min(MA_TIME_INTERVAL, timestamp - this.lastTimestamp);
                        this.movingAvg =
                            (this.movingAvg * (MA_TIME_INTERVAL - time)) / MA_TIME_INTERVAL +
                                (price * time) / MA_TIME_INTERVAL;
                        this.lastTimestamp = timestamp;
                        return [2 /*return*/, this.movingAvg];
                }
            });
        });
    };
    MaxLpStrategy.prototype.getClosePositionParams = function () {
        return __awaiter(this, void 0, void 0, function () {
            var burnRanges;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.vaultProvider.updateRanges()];
                    case 1:
                        _a.sent();
                        burnRanges = __spreadArray([], __read(this.vaultProvider.ranges), false);
                        this.vaultProvider.ranges = [];
                        return [4 /*yield*/, this.vaultProvider.getRebalanceParams(burnRanges)];
                    case 2: return [2 /*return*/, (_a.sent())];
                }
            });
        });
    };
    MaxLpStrategy.prototype.rebalanceRanges = function () {
        return __awaiter(this, void 0, void 0, function () {
            var price, tickSpacing, _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, tx;
            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.vaultProvider.price;
                        tickSpacing = this.vaultProvider.tickSpacing;
                        return [4 /*yield*/, this.getRanges(price, tickSpacing)];
                    case 1:
                        _a = _g.sent(), mainLow = _a.mainLow, mainHigh = _a.mainHigh, secRangeLow = _a.secRangeLow, secRangeHigh = _a.secRangeHigh;
                        return [4 /*yield*/, this.vaultProvider.getBalances()];
                    case 2:
                        _b = _g.sent(), totals = _b.totals, allocated = _b.allocated;
                        this.inventory = totals;
                        this.allocated = allocated;
                        // mutates state
                        return [4 /*yield*/, this.updateRebalanceRecord()];
                    case 3:
                        // mutates state
                        _g.sent();
                        burnRanges = this.vaultProvider.ranges.map(function (r) { return (__assign({}, r)); });
                        // const burnRanges = [...this.vaultProvider.ranges];
                        this.vaultProvider.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;
                        low = new uniV3Range_1.UniV3Range(this.vaultProvider, secQuoteValue, secRangeLow, mainLow);
                        mainRange = new uniV3Range_1.UniV3Range(this.vaultProvider, mainLp, mainLow, mainHigh);
                        high = new uniV3Range_1.UniV3Range(this.vaultProvider, secBaseValue, mainHigh, secRangeHigh);
                        hFull = new uniV3Range_1.UniV3Range(this.vaultProvider, extraBase * price - secBaseValue, secRangeHigh, uniV3Utils_1.MAX_PRICE);
                        lFull = new uniV3Range_1.UniV3Range(this.vaultProvider, extraQuote - secQuoteValue, uniV3Utils_1.MIN_PRICE, secRangeLow);
                        return [4 /*yield*/, this.findRangeAmounts([lFull, low, mainRange, high, hFull], mainLp)];
                    case 4:
                        _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.vaultProvider.ranges = [l, m, h];
                        this.logRanges();
                        return [4 /*yield*/, this.vaultProvider.getRebalanceParams(burnRanges)];
                    case 5:
                        rebalanceParams = _g.sent();
                        return [4 /*yield*/, this.vaultProvider.executeRebalance(rebalanceParams)];
                    case 6:
                        tx = _g.sent();
                        if (!tx) return [3 /*break*/, 8];
                        this.prevReb = price;
                        this.state.rebalances = __spreadArray([], __read(this.tempState.rebalances), false);
                        this.state.prevBalances = __spreadArray([], __read(this.tempState.prevBalances), false);
                        this.state.leftoverRebalance = __spreadArray([], __read(this.tempState.leftoverRebalance), false);
                        this.lastRebalanceBlockNumber = tx.blockNumber;
                        // update state store
                        return [4 /*yield*/, this.syncToDB()];
                    case 7:
                        // update state store
                        _g.sent();
                        return [3 /*break*/, 9];
                    case 8:
                        // undo range update if tx failed
                        this.vaultProvider.ranges = __spreadArray([], __read(burnRanges), false);
                        _g.label = 9;
                    case 9:
                        this.isRebalancing = false;
                        return [2 /*return*/, rebalanceParams];
                }
            });
        });
    };
    MaxLpStrategy.prototype.syncToDB = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, ((_a = this.dbProvider) === null || _a === void 0 ? void 0 : _a.syncToDB({
                            rebalances: this.state.rebalances,
                            prevBalances: this.state.prevBalances,
                            leftoverRebalance: this.state.leftoverRebalance,
                            prevReb: this.prevReb,
                        }))];
                    case 1:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    MaxLpStrategy.prototype.logRanges = function () {
        console.log('price ', this.vaultProvider.price);
        this.vaultProvider.ranges.forEach(function (range) {
            console.log('~~~~~');
            console.log('min max', range.minRange, range.maxRange);
            console.log(' base quote', range.base, range.quote);
        });
        console.log('~~~~~');
    };
    MaxLpStrategy.prototype.findRangeAmounts = function (ranges, mainValue) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, lFull, low, mainRange, high, hFull, rebalances, price, _b, costBasis, adjustHighRange, adjustLowRange, prevCost, adjustCost, expectedCostBasis, leftoverRebalance, matchingCost, i, maxIter, foundMatchingCost, newValue, newValue;
            var _this = this;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = __read(ranges, 5), lFull = _a[0], low = _a[1], mainRange = _a[2], high = _a[3], hFull = _a[4];
                        rebalances = this.state.rebalances;
                        price = this.vaultProvider.price;
                        _b = (0, uniV3MMUtils_1.getCostBasisParams)(rebalances), costBasis = _b.costBasis, adjustHighRange = _b.adjustHighRange, adjustLowRange = _b.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;
                        _c.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.vaultProvider, 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.vaultProvider, newValue, low.minRange, low.maxRange);
                        }
                        return [4 /*yield*/, matchingCost()];
                    case 2:
                        foundMatchingCost = _c.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 }];
                }
            });
        });
    };
    MaxLpStrategy.prototype.getExpectedCostBasis = function (low, mainRange, high) {
        return __awaiter(this, void 0, void 0, function () {
            var rebalances, price, _a, dBase, dQuote, adjustLowRange, _b, mainDBase, mainDQuote, _c, rebalanceLow, rebalanceHigh, mainRangeValue, nextPrice, _d, secDBase, secDQuote, expdBase, leftoverBase, leftoverQuote, _e, bid, ask, nextMainRange, _f, nextMainDBase, nextMainDQuote, totalQuote, totalBase, projectedCostBasis;
            return __generator(this, function (_g) {
                rebalances = this.state.rebalances;
                price = this.vaultProvider.price;
                _a = (0, uniV3MMUtils_1.getCostBasisParams)(rebalances), dBase = _a.dBase, dQuote = _a.dQuote, adjustLowRange = _a.adjustLowRange;
                _b = mainRange.dTokensAtPrice(price, adjustLowRange ? mainRange.minRange : mainRange.maxRange), mainDBase = _b.dBase, mainDQuote = _b.dQuote;
                _c = this.getRebalancePoints(price), rebalanceLow = _c.rebalanceLow, rebalanceHigh = _c.rebalanceHigh;
                mainRangeValue = mainRange.base * price + mainRange.quote;
                nextPrice = adjustLowRange ? rebalanceLow : rebalanceHigh;
                _d = adjustLowRange
                    ? low.dTokensAtPrice(low.maxRange, rebalanceLow)
                    : high.dTokensAtPrice(high.minRange, rebalanceHigh), secDBase = _d.dBase, secDQuote = _d.dQuote;
                expdBase = mainDBase + secDBase;
                leftoverBase = (dBase - Math.abs(expdBase)) * (expdBase < 0 ? 1 : -1);
                leftoverQuote = (dQuote - Math.abs(mainDQuote)) * (mainDQuote < 0 ? 1 : -1);
                _e = this.getBidAsk(nextPrice), bid = _e.bid, ask = _e.ask;
                nextMainRange = new uniV3Range_1.UniV3Range(this.vaultProvider, mainRangeValue, bid, ask, undefined, undefined, undefined, nextPrice);
                _f = nextMainRange.simulateSwap({
                    dBase: -leftoverBase,
                    dQuote: 0,
                    timestamp: 0,
                }, nextPrice, true), nextMainDBase = _f.swappedBase, nextMainDQuote = _f.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],
                    }];
            });
        });
    };
    MaxLpStrategy.prototype.getBidAsk = function (price) {
        if (price === void 0) { price = this.vaultProvider.price; }
        var bid = price * (1 - this.mainRangeOffset);
        var ask = price / (1 - this.mainRangeOffset);
        return { bid: bid, ask: ask };
    };
    MaxLpStrategy.prototype.getRebalancePoints = function (prevReb) {
        prevReb = prevReb != null ? prevReb : this.prevReb;
        var rangeDiffLow = this.rebalanceLow - this.mainRangeOffset;
        var rangeDiffHigh = this.rebalanceHigh - this.mainRangeOffset;
        var rebRangeLow = this.mainRangeOffset + rangeDiffLow * this.rebalanceWeight;
        var rebRangeHigh = this.mainRangeOffset + rangeDiffHigh * this.rebalanceWeight;
        var rebalanceLow = prevReb * (1 - rebRangeLow);
        var rebalanceHigh = prevReb / (1 - rebRangeHigh);
        return {
            rebalanceLow: rebalanceLow,
            rebalanceHigh: rebalanceHigh,
        };
    };
    MaxLpStrategy.prototype.getRangeAmounts = function (mainLp, extraBase, extraQuote) {
        var secRangeShare = this.secRangeShare;
        var price = this.vaultProvider.price;
        var rebalances = this.state.rebalances;
        var _a = (0, uniV3MMUtils_1.getCostBasisParams)(rebalances), dBase = _a.dBase, dQuote = _a.dQuote, adjustLowRange = _a.adjustLowRange, adjustHighRange = _a.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 };
    };
    MaxLpStrategy.prototype.updateRebalanceRecord = function () {
        return __awaiter(this, void 0, void 0, function () {
            var inventory, price, rebRecord, costBasis, dBase, dQuote, prevCostBasis, tmpRebalances, lastRebId, _a, dBase_1, costBasis_1, _b, leftoverBase, leftoverQuote, lastReb;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        inventory = this.inventory;
                        price = this.vaultProvider.price;
                        return [4 /*yield*/, this.getCostBasis()];
                    case 1:
                        rebRecord = _c.sent();
                        costBasis = rebRecord.costBasis, dBase = rebRecord.dBase, dQuote = rebRecord.dQuote;
                        prevCostBasis = (this.state.rebalances[this.state.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);
                        tmpRebalances = __spreadArray([], __read(this.state.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) {
                                // temp rebalances state in case tx reverts
                                tmpRebalances = tmpRebalances.filter(function (r) { return price > Math.abs(r.costBasis); });
                            }
                            lastRebId = tmpRebalances.length - 1;
                            if (tmpRebalances.length) {
                                _a = tmpRebalances[lastRebId], dBase_1 = _a.dBase, costBasis_1 = _a.costBasis;
                                _b = __read(this.state.leftoverRebalance, 2), leftoverBase = _b[0], leftoverQuote = _b[1];
                                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;
                        return [2 /*return*/];
                }
            });
        });
    };
    MaxLpStrategy.prototype.getCostBasis = function () {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            var inventory, prevBalances, _c, vaultContract, chain, vaultType, lastRebalanceBlockNumber, withdraws, depos, deposAndWithdraws, e_1, dBase, dQuote, costBasis;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        inventory = this.inventory;
                        prevBalances = this.state.prevBalances;
                        _c = this.vaultProvider, vaultContract = _c.vaultContract, chain = _c.chain, vaultType = _c.vaultType;
                        // if prevBalance is 0,0 we don't have a cost basis
                        if (prevBalances[0] == 0 && prevBalances[1] == 0)
                            return [2 /*return*/, types_1.emptyRecord];
                        lastRebalanceBlockNumber = this.lastRebalanceBlockNumber;
                        withdraws = [0, 0];
                        depos = [0, 0];
                        _d.label = 1;
                    case 1:
                        _d.trys.push([1, 5, , 6]);
                        if (!!lastRebalanceBlockNumber) return [3 /*break*/, 3];
                        return [4 /*yield*/, (0, arkiveQueries_1.fetchLatestRebalance)({
                                vault: vaultContract.address,
                                chain: chain,
                                vaultType: vaultType,
                            })];
                    case 2:
                        lastRebalanceBlockNumber =
                            (_b = (_a = (_d.sent())) === null || _a === void 0 ? void 0 : _a.block) !== null && _b !== void 0 ? _b : 0;
                        _d.label = 3;
                    case 3: return [4 /*yield*/, (0, arkiveQueries_1.fetchDeposAndWithdraws)({
                            vault: vaultContract.address,
                            chain: chain,
                            fromBlock: lastRebalanceBlockNumber,
                            vaultType: vaultType,
                        })];
                    case 4:
                        deposAndWithdraws = _d.sent();
                        depos = deposAndWithdraws.depos.reduce(function (acc, _a) {
                            var amount0 = _a.amount0, amount1 = _a.amount1;
                            return [acc[0] + (amount0 !== null && amount0 !== void 0 ? amount0 : 0), acc[1] + (amount1 !== null && amount1 !== void 0 ? amount1 : 0)];
                        }, [0, 0]);
                        withdraws = deposAndWithdraws.withdraws.reduce(function (acc, _a) {
                            var amount0Out = _a.amount0Out, amount1Out = _a.amount1Out;
                            return [acc[0] + (amount0Out !== null && amount0Out !== void 0 ? amount0Out : 0), acc[1] + (amount1Out !== null && amount1Out !== void 0 ? amount1Out : 0)];
                        }, [0, 0]);
                        return [3 /*break*/, 6];
                    case 5:
                        e_1 = _d.sent();
                        console.error('failed to fetch arakis deposit/withdraw data', e_1);
                        return [3 /*break*/, 6];
                    case 6:
                        dBase = inventory[0] - prevBalances[0] - depos[0] + withdraws[0];
                        dQuote = inventory[1] - prevBalances[1] - depos[1] + withdraws[1];
                        costBasis = dBase == 0 || dQuote == 0 ? 0 : (dQuote / dBase) * (dBase > 0 ? 1 : -1);
                        // this.prevBalances = [this.base, this.quoteValue];
                        return [2 /*return*/, { costBasis: costBasis, dBase: dBase, dQuote: dQuote }];
                }
            });
        });
    };
    MaxLpStrategy.prototype.getRanges = function (price, tickSpacing) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, secondaryRangeOffset, mainRangeOffset, rebalanceWeight, prevReb, mainLow, mainHigh, secRangeLowPreTick, secRangeHighPreTick, secRangeLow, secRangeHigh, rangeDiff, rebRange, rebalanceLowPreTick, rebalanceHighPreTick, rebalanceLow, rebalanceHigh;
            return __generator(this, function (_b) {
                _a = this, secondaryRangeOffset = _a.secondaryRangeOffset, mainRangeOffset = _a.mainRangeOffset, rebalanceWeight = _a.rebalanceWeight, prevReb = _a.prevReb;
                mainLow = price * (1 - mainRangeOffset);
                mainHigh = price / (1 - mainRangeOffset);
                secRangeLowPreTick = price * (1 - secondaryRangeOffset);
                secRangeHighPreTick = price / (1 - secondaryRangeOffset);
                secRangeLow = (0, uniV3Utils_1.priceToTickPrice)(secRangeLowPreTick, { tickSpacing: tickSpacing });
                secRangeHigh = (0, uniV3Utils_1.priceToTickPrice)(secRangeHighPreTick, { tickSpacing: tickSpacing });
                rangeDiff = secondaryRangeOffset - mainRangeOffset;
                rebRange = mainRangeOffset + rangeDiff * rebalanceWeight;
                rebalanceLowPreTick = prevReb * (1 - rebRange);
                rebalanceHighPreTick = prevReb / (1 - rebRange);
                rebalanceLow = (0, uniV3Utils_1.priceToTickPrice)(rebalanceLowPreTick, { tickSpacing: tickSpacing });
                rebalanceHigh = (0, uniV3Utils_1.priceToTickPrice)(rebalanceHighPreTick, {
                    tickSpacing: tickSpacing,
                });
                return [2 /*return*/, {
                        mainLow: (0, uniV3Utils_1.priceToTickPrice)(mainLow, { tickSpacing: tickSpacing }),
                        mainHigh: (0, uniV3Utils_1.priceToTickPrice)(mainHigh, { tickSpacing: tickSpacing }),
                        secRangeLow: secRangeLow,
                        secRangeHigh: secRangeHigh,
                        rebalanceLow: rebalanceLow,
                        rebalanceHigh: rebalanceHigh,
                    }];
            });
        });
    };
    MaxLpStrategy.prototype.syncFromDB = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, vaultContract, chain, key, dbRes, leftoverRebalance, rebalances, prevBalances, prevReb, totals;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!this.dbProvider)
                            return [2 /*return*/];
                        _a = this.vaultProvider, vaultContract = _a.vaultContract, chain = _a.chain;
                        key = "".concat(vaultContract.address, "-").concat(chain);
                        return [4 /*yield*/, this.dbProvider.fetchFromDB()];
                    case 1:
                        dbRes = _b.sent();
                        leftoverRebalance = dbRes.leftoverRebalance, rebalances = dbRes.rebalances;
                        prevBalances = dbRes.prevBalances, prevReb = dbRes.prevReb;
                        // we don't need to init these if they are not initialized - just fall back to defaults
                        this.state.rebalances = rebalances !== null && rebalances !== void 0 ? rebalances : [];
                        this.state.leftoverRebalance = (leftoverRebalance !== null && leftoverRebalance !== void 0 ? leftoverRebalance : [0, 0]);
                        if (!!prevBalances) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.vaultProvider.getBalances()];
                    case 2:
                        totals = (_b.sent()).totals;
                        prevBalances = totals;
                        return [4 /*yield*/, MaxLpStrategy.initMMValue(key, 'prevBalances', JSON.stringify(prevBalances), this.dbProvider)];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4:
                        this.state.prevBalances = prevBalances;
                        if (!!prevReb) return [3 /*break*/, 6];
                        prevReb = this.vaultProvider.price;
                        return [4 /*yield*/, MaxLpStrategy.initMMValue(key, 'prevRebalance', this.vaultProvider.price, this.dbProvider)];
                    case 5:
                        _b.sent();
                        _b.label = 6;
                    case 6:
                        this.prevReb = prevReb;
                        return [2 /*return*/];
                }
            });
        });
    };
    MaxLpStrategy.initMMValue = function (key, field, value, dbProvider) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        console.warn("WARNING ".concat(field, " is not initialized, this should only happen once"));
                        return [4 /*yield*/, (dbProvider === null || dbProvider === void 0 ? void 0 : dbProvider.updateVaultState(key, field, value, true, 'mmVaults'))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return MaxLpStrategy;
}(strategy_1.MMStrategy));
exports.MaxLpStrategy = MaxLpStrategy;
//# sourceMappingURL=maxLpStrategy.js.map