"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 __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.ArrakisVaultProvider = void 0;
var uniV3Range_1 = require("../uniV3Range");
var vaultProvider_1 = require("./vaultProvider");
var typechain_1 = require("../../../typechain");
var ethers_1 = require("ethers");
var address_1 = require("../../address");
var uniV3Utils_1 = require("../uniV3Utils");
var utils_1 = require("ethers/lib/utils");
var uniV3_1 = require("../../uniV3");
var ArrakisVaultProvider = /** @class */ (function (_super) {
    __extends(ArrakisVaultProvider, _super);
    function ArrakisVaultProvider(params) {
        return _super.call(this, 'arrakis', 'rebalance', params.vaultContract, params) || this;
    }
    ArrakisVaultProvider.create = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var arrakis;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        arrakis = new ArrakisVaultProvider(params);
                        return [4 /*yield*/, arrakis.init(params)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, arrakis];
                }
            });
        });
    };
    ArrakisVaultProvider.prototype.init = function (_a) {
        var baseToken = _a.baseToken, price = _a.price;
        return __awaiter(this, void 0, void 0, function () {
            var _b, token0, token1, pools, pool, t0, t1, _c, dec0, dec1, _d, _e;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0: return [4 /*yield*/, Promise.all([
                            this.vaultContract.token0(),
                            this.vaultContract.token1(),
                            this.vaultContract.getPools(),
                        ])];
                    case 1:
                        _b = __read.apply(void 0, [_f.sent(), 3]), token0 = _b[0], token1 = _b[1], pools = _b[2];
                        this.token0 = token0;
                        this.token1 = token1;
                        this.reverse = this.token0.toLowerCase() !== baseToken.toLowerCase();
                        pool = pools[0];
                        this.poolContract = typechain_1.IUniswapV3Pool__factory.connect(pool, this.wallet);
                        t0 = typechain_1.ERC20__factory.connect(this.token0, this.wallet);
                        t1 = typechain_1.ERC20__factory.connect(this.token1, this.wallet);
                        return [4 /*yield*/, Promise.all([t0.decimals(), t1.decimals()])];
                    case 2:
                        _c = __read.apply(void 0, [_f.sent(), 2]), dec0 = _c[0], dec1 = _c[1];
                        this.dec0 = dec0;
                        this.dec1 = dec1;
                        _d = this;
                        if (!(price !== null && price !== void 0)) return [3 /*break*/, 3];
                        _e = price;
                        return [3 /*break*/, 5];
                    case 3: return [4 /*yield*/, this.getPrice(0)];
                    case 4:
                        _e = (_f.sent());
                        _f.label = 5;
                    case 5:
                        _d.price = _e;
                        return [4 /*yield*/, this.updateRanges()];
                    case 6:
                        _f.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    ArrakisVaultProvider.prototype.updateRanges = function () {
        return __awaiter(this, void 0, void 0, function () {
            var helper, positions, ranges, _a, amount0s, amount1s;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        helper = typechain_1.IArrakisV2Helper__factory.connect((0, address_1.getArrakisAddr)(this.chain).ArrakisV2Helper, this.wallet);
                        return [4 /*yield*/, helper.totalLiquidity(this.vaultContract.address)];
                    case 1:
                        positions = _b.sent();
                        // if we don't have any positions, abort
                        if (positions.length === 0) {
                            this.ranges = [];
                            return [2 /*return*/];
                        }
                        ranges = positions.map(function (p) { return p.range; });
                        return [4 /*yield*/, helper.token0AndToken1ByRange(ranges, this.token0, this.token1, this.vaultContract.address)];
                    case 2:
                        _a = _b.sent(), amount0s = _a.amount0s, amount1s = _a.amount1s;
                        // init ranges
                        this.ranges = positions.map(function (position, i) {
                            var range = position.range, liquidity = position.liquidity;
                            var _a = _this, dec0 = _a.dec0, dec1 = _a.dec1;
                            var lowerTick = (0, uniV3Utils_1.tickToPrice)(range.lowerTick, dec0, dec1);
                            var upperTick = (0, uniV3Utils_1.tickToPrice)(range.upperTick, dec0, dec1);
                            var lowPrice = _this.reverse ? 1 / upperTick : lowerTick;
                            var upperPrice = _this.reverse ? 1 / lowerTick : upperTick;
                            var a0 = parseFloat((0, utils_1.formatUnits)(amount0s[i].amount, dec0));
                            var a1 = parseFloat((0, utils_1.formatUnits)(amount1s[i].amount, dec1));
                            var base = _this.reverse ? a1 : a0;
                            var quote = _this.reverse ? a0 : a1;
                            return new uniV3Range_1.UniV3Range(_this, 0, lowPrice, upperPrice, base, quote, liquidity.toString());
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    ArrakisVaultProvider.prototype.getBalances = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, dec0, dec1, helper, _b, amount0, amount1, leftOver0, leftOver1, fee0, fee1, totals, allocated;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = this, dec0 = _a.dec0, dec1 = _a.dec1;
                        helper = typechain_1.IArrakisV2Helper__factory.connect((0, address_1.getArrakisAddr)(this.chain).ArrakisV2Helper, this.wallet);
                        return [4 /*yield*/, helper.totalUnderlyingWithFeesAndLeftOver(this.vaultContract.address)];
                    case 1:
                        _b = _c.sent(), amount0 = _b.amount0, amount1 = _b.amount1, leftOver0 = _b.leftOver0, leftOver1 = _b.leftOver1, fee0 = _b.fee0, fee1 = _b.fee1;
                        totals = [
                            parseFloat((0, utils_1.formatUnits)(amount0, dec0)),
                            parseFloat((0, utils_1.formatUnits)(amount1, dec1)),
                        ];
                        allocated = [
                            parseFloat((0, utils_1.formatUnits)(amount0.sub(leftOver0).sub(fee0), dec0)),
                            parseFloat((0, utils_1.formatUnits)(amount1.sub(leftOver1).sub(fee1), dec1)),
                        ];
                        if (this.reverse) {
                            totals.reverse();
                            allocated.reverse();
                        }
                        return [2 /*return*/, {
                                totals: totals,
                                allocated: allocated,
                            }];
                }
            });
        });
    };
    ArrakisVaultProvider.prototype.getRebalanceParams = function (burnRanges) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, ranges, feeTier, reverse, dec0, dec1, _b, mints, minDeposit0, minDeposit1, _c, burns, minBurn0, minBurn1, swap, rebalanceParams;
            return __generator(this, function (_d) {
                _a = this, ranges = _a.ranges, feeTier = _a.feeTier, reverse = _a.reverse, dec0 = _a.dec0, dec1 = _a.dec1;
                _b = ArrakisVaultProvider.getRebalanceParams(ranges, feeTier, reverse, [
                    dec0,
                    dec1,
                ]), mints = _b.lpParams, minDeposit0 = _b.min0, minDeposit1 = _b.min1;
                _c = ArrakisVaultProvider.getRebalanceParams(burnRanges, feeTier, reverse, [
                    dec0,
                    dec1,
                ]), burns = _c.lpParams, minBurn0 = _c.min0, minBurn1 = _c.min1;
                swap = {
                    payload: ethers_1.constants.HashZero,
                    router: ethers_1.constants.AddressZero,
                    amountIn: 0,
                    expectedMinReturn: 0,
                    zeroForOne: false,
                };
                rebalanceParams = {
                    burns: burns,
                    mints: mints,
                    swap: swap,
                    minBurn0: minBurn0,
                    minBurn1: minBurn1,
                    minDeposit0: minDeposit0,
                    minDeposit1: minDeposit1,
                };
                return [2 /*return*/, [rebalanceParams]];
            });
        });
    };
    ArrakisVaultProvider.prototype.getPrice = function (twapInterval) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, reverse, dec0, dec1, sqrtPriceX96_1, sqrtPrice_1, price_1, secondsAgos, _b, tickCumulatives, sqrtPriceX96, price;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = this, reverse = _a.reverse, dec0 = _a.dec0, dec1 = _a.dec1;
                        if (!(twapInterval == null || twapInterval == 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.poolContract.slot0()];
                    case 1:
                        sqrtPriceX96_1 = (_c.sent()).sqrtPriceX96;
                        sqrtPrice_1 = parseFloat((0, utils_1.formatUnits)(sqrtPriceX96_1, 0));
                        price_1 = Math.pow(sqrtPrice_1, 2) / Math.pow(2, 192);
                        return [2 /*return*/, reverse ? 1 / price_1 : price_1];
                    case 2:
                        secondsAgos = [twapInterval, 0];
                        return [4 /*yield*/, this.poolContract.observe(secondsAgos)];
                    case 3:
                        _b = __read.apply(void 0, [_c.sent(), 1]), tickCumulatives = _b[0];
                        sqrtPriceX96 = (0, uniV3_1.getSqrtRatioAtTick)(tickCumulatives[1].sub(tickCumulatives[0]).div(twapInterval).toNumber());
                        price = (0, uniV3_1.sqrtPrice)([dec0, dec1], sqrtPriceX96).toSignificant({
                            reverse: reverse,
                            decimalPlaces: 10,
                        });
                        return [2 /*return*/, price];
                }
            });
        });
    };
    ArrakisVaultProvider.prototype.getTickSpacing = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, uniV3Utils_1.feeTierToTickSpacing[this.feeTier]];
            });
        });
    };
    ArrakisVaultProvider.getRebalanceParams = function (ranges, feeTier, reverse, decimals) {
        var SLIPPAGE = 0.005; // .5%
        var lpParams = ranges.map(function (range) {
            var lowerTick = range.lowerTick, upperTick = range.upperTick, liquidity = range.liquidity;
            var lpParams = {
                liquidity: liquidity,
                range: {
                    lowerTick: lowerTick,
                    upperTick: upperTick,
                    feeTier: feeTier,
                },
            };
            return lpParams;
        });
        var minBase = ranges.reduce(function (a, r) { return r.base + a; }, 0);
        var minQuote = ranges.reduce(function (a, r) { return r.quote + a; }, 0);
        var min0Float = reverse ? minQuote : minBase;
        var min1Flaot = reverse ? minBase : minQuote;
        var min0 = (0, utils_1.parseUnits)((min0Float * (1 - SLIPPAGE)).toFixed(decimals[0]), decimals[0]);
        var min1 = (0, utils_1.parseUnits)((min1Flaot * (1 - SLIPPAGE)).toFixed(decimals[1]), decimals[1]);
        // console.log('min0', min0.toString(), 'min1', min1.toString());
        return {
            lpParams: lpParams,
            min0: min0,
            min1: min1,
        };
    };
    return ArrakisVaultProvider;
}(vaultProvider_1.VaultProvider));
exports.ArrakisVaultProvider = ArrakisVaultProvider;
//# sourceMappingURL=arrakisVaultProvider.js.map