"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefiEdgeVaultProvider = void 0;
var uniV3Range_1 = require("../uniV3Range");
var vaultProvider_1 = require("./vaultProvider");
var typechain_1 = require("../../../typechain");
var utils_1 = require("../../algebra/utils");
var uniV3Utils_1 = require("../uniV3Utils");
var utils_2 = require("ethers/lib/utils");
var ethers_1 = require("ethers");
var uniV3_1 = require("../../uniV3");
var DefiEdgeVaultProvider = /** @class */ (function (_super) {
    __extends(DefiEdgeVaultProvider, _super);
    function DefiEdgeVaultProvider(params) {
        return _super.call(this, 'defiEdge', 'rebalance', params.vaultContract, __assign({}, params)) || this;
    }
    DefiEdgeVaultProvider.create = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var defiEdge;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        defiEdge = new DefiEdgeVaultProvider(params);
                        return [4 /*yield*/, defiEdge.init(params)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, defiEdge];
                }
            });
        });
    };
    DefiEdgeVaultProvider.prototype.init = function (_a) {
        var baseToken = _a.baseToken, price = _a.price;
        return __awaiter(this, void 0, void 0, function () {
            var poolAddress, _b, token0, token1, _c, t0, t1, _d, dec0, dec1, _e, _f;
            return __generator(this, function (_g) {
                switch (_g.label) {
                    case 0: return [4 /*yield*/, this.vaultContract.pool()];
                    case 1:
                        poolAddress = _g.sent();
                        this.poolContract = typechain_1.IAlgebraPool__factory.connect(poolAddress, this.wallet);
                        return [4 /*yield*/, Promise.all([
                                this.poolContract.token0(),
                                this.poolContract.token1(),
                            ])];
                    case 2:
                        _b = __read.apply(void 0, [_g.sent(), 2]), token0 = _b[0], token1 = _b[1];
                        this.token0 = token0;
                        this.token1 = token1;
                        _c = this;
                        return [4 /*yield*/, this.poolContract.tickSpacing()];
                    case 3:
                        _c.tickSpacing = _g.sent();
                        this.reverse = this.token0.toLowerCase() !== baseToken.toLowerCase();
                        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 4:
                        _d = __read.apply(void 0, [_g.sent(), 2]), dec0 = _d[0], dec1 = _d[1];
                        this.dec0 = dec0;
                        this.dec1 = dec1;
                        _e = this;
                        if (!(price !== null && price !== void 0)) return [3 /*break*/, 5];
                        _f = price;
                        return [3 /*break*/, 7];
                    case 5: return [4 /*yield*/, this.getPrice(0)];
                    case 6:
                        _f = (_g.sent());
                        _g.label = 7;
                    case 7:
                        _e.price = _f;
                        return [4 /*yield*/, this.updateRanges()];
                    case 8:
                        _g.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    DefiEdgeVaultProvider.prototype.updateRanges = function () {
        return __awaiter(this, void 0, void 0, function () {
            var ticks, positions;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.vaultContract.getTicks()];
                    case 1:
                        ticks = _a.sent();
                        if (ticks.length === 0) {
                            this.ranges = [];
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, (0, utils_1.token0AndToken1ByRange)({
                                pool: this.poolContract,
                                strategy: this.vaultContract.address,
                                ticks: ticks,
                            })];
                    case 2:
                        positions = _a.sent();
                        // init ranges
                        this.ranges = positions.map(function (position) {
                            var tickLower = position.tickLower, tickUpper = position.tickUpper, amount0 = position.amount0, amount1 = position.amount1, liquidityAmount = position.liquidityAmount;
                            var _a = _this, dec0 = _a.dec0, dec1 = _a.dec1;
                            var lowerTick = (0, uniV3Utils_1.tickToPrice)(tickLower, dec0, dec1);
                            var upperTick = (0, uniV3Utils_1.tickToPrice)(tickUpper, dec0, dec1);
                            var lowPrice = _this.reverse ? 1 / upperTick : lowerTick;
                            var upperPrice = _this.reverse ? 1 / lowerTick : upperTick;
                            var a0 = parseFloat((0, utils_2.formatUnits)(amount0, dec0));
                            var a1 = parseFloat((0, utils_2.formatUnits)(amount1, dec1));
                            var base = _this.reverse ? a1 : a0;
                            var quote = _this.reverse ? a0 : a1;
                            return new uniV3Range_1.UniV3Range(_this, 0, lowPrice, upperPrice, base, quote, liquidityAmount.toString());
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    DefiEdgeVaultProvider.prototype.getBalances = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, dec0, dec1, ticks, amountsAndFees, _b, token0Balance, token1Balance, _c, total0, total1, totalFees0, totalFees1, totals, allocated;
            var _this = this;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _a = this, dec0 = _a.dec0, dec1 = _a.dec1;
                        return [4 /*yield*/, this.vaultContract.getTicks()];
                    case 1:
                        ticks = _d.sent();
                        return [4 /*yield*/, (0, utils_1.token0AndToken1ByRange)({
                                pool: this.poolContract,
                                strategy: this.vaultContract.address,
                                ticks: ticks,
                            })];
                    case 2:
                        amountsAndFees = _d.sent();
                        return [4 /*yield*/, Promise.all([
                                (function () { return __awaiter(_this, void 0, void 0, function () {
                                    var token0;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                token0 = typechain_1.IERC20__factory.connect(this.token0, this.wallet);
                                                return [4 /*yield*/, token0.balanceOf(this.vaultContract.address)];
                                            case 1: return [2 /*return*/, _a.sent()];
                                        }
                                    });
                                }); })(),
                                (function () { return __awaiter(_this, void 0, void 0, function () {
                                    var token1;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                token1 = typechain_1.IERC20__factory.connect(this.token1, this.wallet);
                                                return [4 /*yield*/, token1.balanceOf(this.vaultContract.address)];
                                            case 1: return [2 /*return*/, _a.sent()];
                                        }
                                    });
                                }); })(),
                            ])];
                    case 3:
                        _b = __read.apply(void 0, [_d.sent(), 2]), token0Balance = _b[0], token1Balance = _b[1];
                        _c = amountsAndFees.reduce(function (acc, _a) {
                            var amount0 = _a.amount0, amount1 = _a.amount1, fees0 = _a.fees0, fees1 = _a.fees1;
                            return {
                                total0: acc.total0.add(amount0),
                                total1: acc.total1.add(amount1),
                                totalFees0: acc.totalFees0.add(fees0),
                                totalFees1: acc.totalFees1.add(fees1),
                            };
                        }, {
                            total0: ethers_1.BigNumber.from(0),
                            total1: ethers_1.BigNumber.from(0),
                            totalFees0: ethers_1.BigNumber.from(0),
                            totalFees1: ethers_1.BigNumber.from(0),
                        }), total0 = _c.total0, total1 = _c.total1, totalFees0 = _c.totalFees0, totalFees1 = _c.totalFees1;
                        totals = [
                            parseFloat((0, utils_2.formatUnits)(total0.add(token0Balance), dec0)),
                            parseFloat((0, utils_2.formatUnits)(total1.add(token1Balance), dec1)),
                        ];
                        allocated = [
                            parseFloat((0, utils_2.formatUnits)(total0.sub(totalFees0), dec0)),
                            parseFloat((0, utils_2.formatUnits)(total1.sub(totalFees1), dec1)),
                        ];
                        if (this.reverse) {
                            totals.reverse();
                            allocated.reverse();
                        }
                        return [2 /*return*/, { totals: totals, allocated: allocated }];
                }
            });
        });
    };
    DefiEdgeVaultProvider.prototype.getRebalanceParams = function () {
        return __awaiter(this, void 0, void 0, function () {
            var swapData, existingTicks, newTicks;
            var _this = this;
            return __generator(this, function (_a) {
                swapData = '0x';
                existingTicks = [];
                newTicks = this.ranges.map(function (range) {
                    // range amounts are in [base, quote] order
                    var amount0 = _this.reverse ? range.quote : range.base;
                    var amount1 = _this.reverse ? range.base : range.quote;
                    var _a = range.getContractRangeParams(), lowerTick = _a.lowerTick, upperTick = _a.upperTick;
                    return {
                        amount0: ethers_1.utils.parseUnits(amount0.toFixed(_this.dec0), _this.dec0),
                        amount1: ethers_1.utils.parseUnits(amount1.toFixed(_this.dec1), _this.dec1),
                        tickLower: lowerTick,
                        tickUpper: upperTick,
                    };
                });
                return [2 /*return*/, [false, 0, false, swapData, existingTicks, newTicks, true]];
            });
        });
    };
    DefiEdgeVaultProvider.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.globalState()];
                    case 1:
                        sqrtPriceX96_1 = (_c.sent()).price;
                        sqrtPrice_1 = parseFloat((0, utils_2.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.getTimepoints(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];
                }
            });
        });
    };
    return DefiEdgeVaultProvider;
}(vaultProvider_1.VaultProvider));
exports.DefiEdgeVaultProvider = DefiEdgeVaultProvider;
//# sourceMappingURL=defiEdgeVaultProvider.js.map