"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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UniV3MMArrakis = void 0;
var typechain_1 = require("../../typechain");
var address_1 = require("../address");
var ethers_1 = require("ethers");
var uniV3Utils_1 = require("./uniV3Utils");
var uniV3Range_1 = require("../marketMaker/uniV3Range");
var uniV3MMMaxLp_1 = require("./uniV3MMMaxLp");
var parseUnits = ethers_1.utils.parseUnits, formatUnits = ethers_1.utils.formatUnits;
var SLIPPAGE = 0.0005; // .05%
var UniV3MMArrakis = /** @class */ (function (_super) {
    __extends(UniV3MMArrakis, _super);
    function UniV3MMArrakis(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.getUniV3Pool = function () { return __awaiter(_this, void 0, void 0, function () {
            var _a, vault, wallet, pools, poolAddr, pool;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this, vault = _a.vault, wallet = _a.wallet;
                        return [4 /*yield*/, vault.getPools()];
                    case 1:
                        pools = _b.sent();
                        poolAddr = pools[0];
                        return [4 /*yield*/, typechain_1.IUniswapV3Pool__factory.connect(poolAddr, wallet)];
                    case 2:
                        pool = _b.sent();
                        return [2 /*return*/, pool];
                }
            });
        }); };
        return _this;
    }
    UniV3MMArrakis.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.vault.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.vault.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(formatUnits(amount0s[i].amount, dec0));
                            var a1 = parseFloat(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*/];
                }
            });
        });
    };
    UniV3MMArrakis.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.vault.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(formatUnits(amount0, dec0)),
                            parseFloat(formatUnits(amount1, dec1)),
                        ];
                        allocated = [
                            parseFloat(formatUnits(amount0.sub(leftOver0).sub(fee0), dec0)),
                            parseFloat(formatUnits(amount1.sub(leftOver1).sub(fee1), dec1)),
                        ];
                        if (this.reverse) {
                            totals.reverse();
                            allocated.reverse();
                        }
                        return [2 /*return*/, {
                                totals: totals,
                                allocated: allocated,
                            }];
                }
            });
        });
    };
    UniV3MMArrakis.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 = getRebalanceParams(ranges, feeTier, reverse, [dec0, dec1]), mints = _b.lpParams, minDeposit0 = _b.min0, minDeposit1 = _b.min1;
                _c = 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];
            });
        });
    };
    UniV3MMArrakis.prototype.executeRebalance = function (rebalanceParams) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, true];
            });
        });
    };
    return UniV3MMArrakis;
}(uniV3MMMaxLp_1.uniV3MMMaxLp));
exports.UniV3MMArrakis = UniV3MMArrakis;
var getRebalanceParams = function (ranges, feeTier, reverse, decimals) {
    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 = parseUnits((min0Float * (1 - SLIPPAGE)).toFixed(decimals[0]), decimals[0]);
    var min1 = parseUnits((min1Flaot * (1 - SLIPPAGE)).toFixed(decimals[1]), decimals[1]);
    // console.log('min0', min0.toString(), 'min1', min1.toString());
    return {
        lpParams: lpParams,
        min0: min0,
        min1: min1,
    };
};
//# sourceMappingURL=uniV3MMArrakis.js.map