"use strict";
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.getVaultCapacity = exports.getLendCapacity = exports.getImxParams = exports.SECONDS_IN_YEAR = void 0;
var ethers_1 = require("ethers");
var typechain_1 = require("../typechain");
var utils_1 = require("../utils");
exports.SECONDS_IN_YEAR = ethers_1.BigNumber.from('31536000');
var ONE = ethers_1.utils.parseUnits('1');
var TWO = ethers_1.utils.parseUnits('2');
var MAX_LEND_UTIL = 2;
// this is how far past the kink we're willing to go
var FRACTION_OF_KINK = 2;
var getImxParams = function (imxLend) { return __awaiter(void 0, void 0, void 0, function () {
    var sBorrowableAddr, uBorrowableAddr, sBorrowable, uBorrowable, borrowRateSec0, borrowRateSec1, borrowRate0, borrowRate1, availableBorrow0, availableBorrow1, capacity;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, imxLend.sBorrowable()];
            case 1:
                sBorrowableAddr = _a.sent();
                return [4 /*yield*/, imxLend.uBorrowable()];
            case 2:
                uBorrowableAddr = _a.sent();
                return [4 /*yield*/, typechain_1.IBorrowable__factory.connect(sBorrowableAddr, imxLend.signer)];
            case 3:
                sBorrowable = _a.sent();
                return [4 /*yield*/, typechain_1.IBorrowable__factory.connect(uBorrowableAddr, imxLend.signer)];
            case 4:
                uBorrowable = _a.sent();
                return [4 /*yield*/, uBorrowable.borrowRate()];
            case 5:
                borrowRateSec0 = _a.sent();
                return [4 /*yield*/, sBorrowable.borrowRate()];
            case 6:
                borrowRateSec1 = _a.sent();
                borrowRate0 = borrowRateSec0.mul(exports.SECONDS_IN_YEAR);
                borrowRate1 = borrowRateSec1.mul(exports.SECONDS_IN_YEAR);
                return [4 /*yield*/, getAvailableBorrow(uBorrowable)];
            case 7:
                availableBorrow0 = _a.sent();
                return [4 /*yield*/, getAvailableBorrow(sBorrowable)];
            case 8:
                availableBorrow1 = _a.sent();
                return [4 /*yield*/, getCapacity(imxLend, availableBorrow0, availableBorrow1)];
            case 9:
                capacity = _a.sent();
                return [2 /*return*/, { borrowRate0: borrowRate0, borrowRate1: borrowRate1, capacity: capacity }];
        }
    });
}); };
exports.getImxParams = getImxParams;
var getCapacity = function (imxLend, uAvail, sAvail) { return __awaiter(void 0, void 0, void 0, function () {
    var tvl, optimalUBorrow, shortToUnderlying;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, imxLend.getTvl()];
            case 1:
                tvl = _a.sent();
                return [4 /*yield*/, getOptimalUBorrow(imxLend)];
            case 2:
                optimalUBorrow = _a.sent();
                return [4 /*yield*/, imxLend.getExpectedPrice()];
            case 3:
                shortToUnderlying = _a.sent();
                return [2 /*return*/, tvl.add((0, utils_1.minBN)(uAvail.mul(ONE).div(optimalUBorrow), sAvail.mul(shortToUnderlying).div(optimalUBorrow.add(ONE))))];
        }
    });
}); };
var getLendCapacity = function (borrowable) { return __awaiter(void 0, void 0, void 0, function () {
    var borrows, available, total, maxTotal, maxLend;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, borrowable.totalBorrows()];
            case 1:
                borrows = _a.sent();
                return [4 /*yield*/, borrowable.totalBalance()];
            case 2:
                available = _a.sent();
                total = borrows.add(available);
                maxTotal = borrows.mul(MAX_LEND_UTIL);
                maxLend = maxTotal.gt(total) ? maxTotal.sub(total) : ethers_1.BigNumber.from(0);
                return [2 /*return*/, maxLend];
        }
    });
}); };
exports.getLendCapacity = getLendCapacity;
var getAvailableBorrow = function (borrowable) { return __awaiter(void 0, void 0, void 0, function () {
    var borrows, available, total, kink, maxU, maxBorrow;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, borrowable.totalBorrows()];
            case 1:
                borrows = _a.sent();
                return [4 /*yield*/, borrowable.totalBalance()];
            case 2:
                available = _a.sent();
                total = borrows.add(available);
                return [4 /*yield*/, borrowable.kinkUtilizationRate()];
            case 3:
                kink = _a.sent();
                maxU = ONE.sub(ONE.sub(kink).div(FRACTION_OF_KINK));
                maxBorrow = total.mul(maxU).div(ONE);
                if (borrows.gt(maxBorrow))
                    return [2 /*return*/, ethers_1.BigNumber.from(0)];
                return [2 /*return*/, maxBorrow.sub(borrows)];
        }
    });
}); };
var getOptimalUBorrow = function (imxLend) { return __awaiter(void 0, void 0, void 0, function () {
    var collateralTokenAddr, collateralToken, l, safeteyMarginSqrt, cSafetyMarginSqrt, s, uBorrow;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, imxLend.collateralToken()];
            case 1:
                collateralTokenAddr = _a.sent();
                return [4 /*yield*/, typechain_1.ICollateral__factory.connect(collateralTokenAddr, imxLend.signer)];
            case 2:
                collateralToken = _a.sent();
                return [4 /*yield*/, collateralToken.liquidationIncentive()];
            case 3:
                l = _a.sent();
                return [4 /*yield*/, imxLend.safetyMarginSqrt()];
            case 4:
                safeteyMarginSqrt = _a.sent();
                return [4 /*yield*/, collateralToken.safetyMarginSqrt()];
            case 5:
                cSafetyMarginSqrt = _a.sent();
                s = cSafetyMarginSqrt.mul(safeteyMarginSqrt).div(ONE);
                uBorrow = ONE.mul(TWO.sub(l.mul(s).div(ONE))).div(l.mul(ONE).div(s).add(l.mul(s).div(ONE)).sub(TWO));
                return [2 /*return*/, uBorrow];
        }
    });
}); };
var getVaultCapacity = function (vault) { return __awaiter(void 0, void 0, void 0, function () {
    var strategies, vaultMax, j, strat, strategy, maxTvl_1, tvl, vaultTvl, nonVaultTvl, maxTvl;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, vault.getAllStrategies()];
            case 1:
                strategies = _a.sent();
                vaultMax = ethers_1.BigNumber.from(0);
                j = 0;
                _a.label = 2;
            case 2:
                if (!(j < strategies.length)) return [3 /*break*/, 8];
                strat = strategies[j];
                return [4 /*yield*/, typechain_1.SCYVault__factory.connect(strat, vault.signer)];
            case 3:
                strategy = _a.sent();
                return [4 /*yield*/, strategy.getMaxTvl()];
            case 4:
                maxTvl_1 = _a.sent();
                return [4 /*yield*/, strategy.getTvl()];
            case 5:
                tvl = _a.sent();
                return [4 /*yield*/, strategy.underlyingBalance(vault.address)];
            case 6:
                vaultTvl = _a.sent();
                nonVaultTvl = tvl.sub(vaultTvl);
                vaultMax = vaultMax.add(maxTvl_1.sub(nonVaultTvl));
                _a.label = 7;
            case 7:
                j++;
                return [3 /*break*/, 2];
            case 8: return [4 /*yield*/, vault.getMaxTvl()];
            case 9:
                maxTvl = _a.sent();
                return [2 /*return*/, { capacity: vaultMax, maxTvl: maxTvl }];
        }
    });
}); };
exports.getVaultCapacity = getVaultCapacity;
//# sourceMappingURL=imxCapacity.js.map