"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LendingMarket = void 0;
/* eslint-disable @typescript-eslint/no-unused-vars */
const kit_1 = require("@solana/kit");
/* eslint-enable @typescript-eslint/no-unused-vars */
const bn_js_1 = __importDefault(require("bn.js")); // eslint-disable-line @typescript-eslint/no-unused-vars
const borsh = __importStar(require("@coral-xyz/borsh")); // eslint-disable-line @typescript-eslint/no-unused-vars
const utils_1 = require("../utils"); // eslint-disable-line @typescript-eslint/no-unused-vars
const types = __importStar(require("../types")); // eslint-disable-line @typescript-eslint/no-unused-vars
const programId_1 = require("../programId");
class LendingMarket {
    /** Version of lending market */
    version;
    /** Bump seed for derived authority address */
    bumpSeed;
    /** Owner authority which can add new reserves */
    lendingMarketOwner;
    /** Temporary cache of the lending market owner, used in update_lending_market_owner */
    lendingMarketOwnerCached;
    /**
     * Currency market prices are quoted in
     * e.g. "USD" null padded (`*b"USD\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"`) or a SPL token mint pubkey
     */
    quoteCurrency;
    /** Referral fee for the lending market, as bps out of the total protocol fee */
    referralFeeBps;
    emergencyMode;
    /**
     * Whether the obligations on this market should be subject to auto-deleveraging after deposit
     * or borrow limit is crossed.
     * Besides this flag, the particular reserve's flag also needs to be enabled (logical `AND`).
     * **NOTE:** this also affects the individual "target LTV" deleveraging.
     */
    autodeleverageEnabled;
    borrowDisabled;
    /**
     * Refresh price from oracle only if it's older than this percentage of the price max age.
     * e.g. if the max age is set to 100s and this is set to 80%, the price will be refreshed if it's older than 80s.
     * Price is always refreshed if this set to 0.
     */
    priceRefreshTriggerToMaxAgePct;
    /** Percentage of the total borrowed value in an obligation available for liquidation */
    liquidationMaxDebtCloseFactorPct;
    /** Minimum acceptable unhealthy LTV before max_debt_close_factor_pct becomes 100% */
    insolvencyRiskUnhealthyLtvPct;
    /** Minimum liquidation value threshold triggering full liquidation for an obligation */
    minFullLiquidationValueThreshold;
    /** Max allowed liquidation value in one ix call */
    maxLiquidatableDebtMarketValueAtOnce;
    /** [DEPRECATED] Global maximum unhealthy borrow value allowed for any obligation */
    reserved0;
    /** Global maximum allowed borrow value allowed for any obligation */
    globalAllowedBorrowValue;
    /** The address of the risk council, in charge of making parameter and risk decisions on behalf of the protocol */
    riskCouncil;
    /** [DEPRECATED] Reward points multiplier per obligation type */
    reserved1;
    /** Elevation groups are used to group together reserves that have the same risk parameters and can bump the ltv and liquidation threshold */
    elevationGroups;
    elevationGroupPadding;
    /** Min net value accepted to be found in a position after any lending action in an obligation (scaled by quote currency decimals) */
    minNetValueInObligationSf;
    /** Minimum value to enforce smallest ltv priority checks on the collateral reserves on liquidation */
    minValueSkipLiquidationLtvChecks;
    /** Market name, zero-padded. */
    name;
    /** Minimum value to enforce highest borrow factor priority checks on the debt reserves on liquidation */
    minValueSkipLiquidationBfChecks;
    /**
     * Time (in seconds) that must pass before liquidation is allowed on an obligation that has
     * been individually marked for auto-deleveraging (by the risk council).
     */
    individualAutodeleverageMarginCallPeriodSecs;
    /**
     * Minimum amount of deposit at creation of a reserve to prevent artificial inflation
     * Note: this amount cannot be recovered, the ctoken associated are never minted
     */
    minInitialDepositAmount;
    /** Whether the obligation orders should be evaluated during liquidations. */
    obligationOrderExecutionEnabled;
    /** Whether the lending market is set as immutable. */
    immutable;
    /**
     * Whether new obligation orders can be created.
     * Note: updating or cancelling existing orders is *not* affected by this flag.
     */
    obligationOrderCreationEnabled;
    /**
     * Whether the liquidation operations that are triggered by price changes should be disabled.
     * This includes regular liquidation (i.e. LTV exceeding the unhealthy threshold) and some
     * obligation orders' execution.
     *
     * *Caution:* this flag is *disabling* the liquidations when `1` - contrary to all the other
     * liquidation-driving flags (see e.g. [Self::autodeleverage_enabled]).
     */
    priceTriggeredLiquidationDisabled;
    padding2;
    /** Authority that can propose creating of new reserves but cannot enable them. */
    proposerAuthority;
    padding1;
    static discriminator = Buffer.from([
        246, 114, 50, 98, 72, 157, 28, 120,
    ]);
    static layout = borsh.struct([
        borsh.u64("version"),
        borsh.u64("bumpSeed"),
        (0, utils_1.borshAddress)("lendingMarketOwner"),
        (0, utils_1.borshAddress)("lendingMarketOwnerCached"),
        borsh.array(borsh.u8(), 32, "quoteCurrency"),
        borsh.u16("referralFeeBps"),
        borsh.u8("emergencyMode"),
        borsh.u8("autodeleverageEnabled"),
        borsh.u8("borrowDisabled"),
        borsh.u8("priceRefreshTriggerToMaxAgePct"),
        borsh.u8("liquidationMaxDebtCloseFactorPct"),
        borsh.u8("insolvencyRiskUnhealthyLtvPct"),
        borsh.u64("minFullLiquidationValueThreshold"),
        borsh.u64("maxLiquidatableDebtMarketValueAtOnce"),
        borsh.array(borsh.u8(), 8, "reserved0"),
        borsh.u64("globalAllowedBorrowValue"),
        (0, utils_1.borshAddress)("riskCouncil"),
        borsh.array(borsh.u8(), 8, "reserved1"),
        borsh.array(types.ElevationGroup.layout(), 32, "elevationGroups"),
        borsh.array(borsh.u64(), 90, "elevationGroupPadding"),
        borsh.u128("minNetValueInObligationSf"),
        borsh.u64("minValueSkipLiquidationLtvChecks"),
        borsh.array(borsh.u8(), 32, "name"),
        borsh.u64("minValueSkipLiquidationBfChecks"),
        borsh.u64("individualAutodeleverageMarginCallPeriodSecs"),
        borsh.u64("minInitialDepositAmount"),
        borsh.u8("obligationOrderExecutionEnabled"),
        borsh.u8("immutable"),
        borsh.u8("obligationOrderCreationEnabled"),
        borsh.u8("priceTriggeredLiquidationDisabled"),
        borsh.array(borsh.u8(), 4, "padding2"),
        (0, utils_1.borshAddress)("proposerAuthority"),
        borsh.array(borsh.u64(), 165, "padding1"),
    ]);
    constructor(fields) {
        this.version = fields.version;
        this.bumpSeed = fields.bumpSeed;
        this.lendingMarketOwner = fields.lendingMarketOwner;
        this.lendingMarketOwnerCached = fields.lendingMarketOwnerCached;
        this.quoteCurrency = fields.quoteCurrency;
        this.referralFeeBps = fields.referralFeeBps;
        this.emergencyMode = fields.emergencyMode;
        this.autodeleverageEnabled = fields.autodeleverageEnabled;
        this.borrowDisabled = fields.borrowDisabled;
        this.priceRefreshTriggerToMaxAgePct = fields.priceRefreshTriggerToMaxAgePct;
        this.liquidationMaxDebtCloseFactorPct =
            fields.liquidationMaxDebtCloseFactorPct;
        this.insolvencyRiskUnhealthyLtvPct = fields.insolvencyRiskUnhealthyLtvPct;
        this.minFullLiquidationValueThreshold =
            fields.minFullLiquidationValueThreshold;
        this.maxLiquidatableDebtMarketValueAtOnce =
            fields.maxLiquidatableDebtMarketValueAtOnce;
        this.reserved0 = fields.reserved0;
        this.globalAllowedBorrowValue = fields.globalAllowedBorrowValue;
        this.riskCouncil = fields.riskCouncil;
        this.reserved1 = fields.reserved1;
        this.elevationGroups = fields.elevationGroups.map((item) => new types.ElevationGroup({ ...item }));
        this.elevationGroupPadding = fields.elevationGroupPadding;
        this.minNetValueInObligationSf = fields.minNetValueInObligationSf;
        this.minValueSkipLiquidationLtvChecks =
            fields.minValueSkipLiquidationLtvChecks;
        this.name = fields.name;
        this.minValueSkipLiquidationBfChecks =
            fields.minValueSkipLiquidationBfChecks;
        this.individualAutodeleverageMarginCallPeriodSecs =
            fields.individualAutodeleverageMarginCallPeriodSecs;
        this.minInitialDepositAmount = fields.minInitialDepositAmount;
        this.obligationOrderExecutionEnabled =
            fields.obligationOrderExecutionEnabled;
        this.immutable = fields.immutable;
        this.obligationOrderCreationEnabled = fields.obligationOrderCreationEnabled;
        this.priceTriggeredLiquidationDisabled =
            fields.priceTriggeredLiquidationDisabled;
        this.padding2 = fields.padding2;
        this.proposerAuthority = fields.proposerAuthority;
        this.padding1 = fields.padding1;
    }
    static async fetch(rpc, address, programId = programId_1.PROGRAM_ID) {
        const info = await (0, kit_1.fetchEncodedAccount)(rpc, address);
        if (!info.exists) {
            return null;
        }
        if (info.programAddress !== programId) {
            throw new Error(`LendingMarketFields account ${address} belongs to wrong program ${info.programAddress}, expected ${programId}`);
        }
        return this.decode(Buffer.from(info.data));
    }
    static async fetchMultiple(rpc, addresses, programId = programId_1.PROGRAM_ID) {
        const infos = await (0, kit_1.fetchEncodedAccounts)(rpc, addresses);
        return infos.map((info) => {
            if (!info.exists) {
                return null;
            }
            if (info.programAddress !== programId) {
                throw new Error(`LendingMarketFields account ${info.address} belongs to wrong program ${info.programAddress}, expected ${programId}`);
            }
            return this.decode(Buffer.from(info.data));
        });
    }
    static decode(data) {
        if (!data.slice(0, 8).equals(LendingMarket.discriminator)) {
            throw new Error("invalid account discriminator");
        }
        const dec = LendingMarket.layout.decode(data.slice(8));
        return new LendingMarket({
            version: dec.version,
            bumpSeed: dec.bumpSeed,
            lendingMarketOwner: dec.lendingMarketOwner,
            lendingMarketOwnerCached: dec.lendingMarketOwnerCached,
            quoteCurrency: dec.quoteCurrency,
            referralFeeBps: dec.referralFeeBps,
            emergencyMode: dec.emergencyMode,
            autodeleverageEnabled: dec.autodeleverageEnabled,
            borrowDisabled: dec.borrowDisabled,
            priceRefreshTriggerToMaxAgePct: dec.priceRefreshTriggerToMaxAgePct,
            liquidationMaxDebtCloseFactorPct: dec.liquidationMaxDebtCloseFactorPct,
            insolvencyRiskUnhealthyLtvPct: dec.insolvencyRiskUnhealthyLtvPct,
            minFullLiquidationValueThreshold: dec.minFullLiquidationValueThreshold,
            maxLiquidatableDebtMarketValueAtOnce: dec.maxLiquidatableDebtMarketValueAtOnce,
            reserved0: dec.reserved0,
            globalAllowedBorrowValue: dec.globalAllowedBorrowValue,
            riskCouncil: dec.riskCouncil,
            reserved1: dec.reserved1,
            elevationGroups: dec.elevationGroups.map((item /* eslint-disable-line @typescript-eslint/no-explicit-any */) => types.ElevationGroup.fromDecoded(item)),
            elevationGroupPadding: dec.elevationGroupPadding,
            minNetValueInObligationSf: dec.minNetValueInObligationSf,
            minValueSkipLiquidationLtvChecks: dec.minValueSkipLiquidationLtvChecks,
            name: dec.name,
            minValueSkipLiquidationBfChecks: dec.minValueSkipLiquidationBfChecks,
            individualAutodeleverageMarginCallPeriodSecs: dec.individualAutodeleverageMarginCallPeriodSecs,
            minInitialDepositAmount: dec.minInitialDepositAmount,
            obligationOrderExecutionEnabled: dec.obligationOrderExecutionEnabled,
            immutable: dec.immutable,
            obligationOrderCreationEnabled: dec.obligationOrderCreationEnabled,
            priceTriggeredLiquidationDisabled: dec.priceTriggeredLiquidationDisabled,
            padding2: dec.padding2,
            proposerAuthority: dec.proposerAuthority,
            padding1: dec.padding1,
        });
    }
    toJSON() {
        return {
            version: this.version.toString(),
            bumpSeed: this.bumpSeed.toString(),
            lendingMarketOwner: this.lendingMarketOwner,
            lendingMarketOwnerCached: this.lendingMarketOwnerCached,
            quoteCurrency: this.quoteCurrency,
            referralFeeBps: this.referralFeeBps,
            emergencyMode: this.emergencyMode,
            autodeleverageEnabled: this.autodeleverageEnabled,
            borrowDisabled: this.borrowDisabled,
            priceRefreshTriggerToMaxAgePct: this.priceRefreshTriggerToMaxAgePct,
            liquidationMaxDebtCloseFactorPct: this.liquidationMaxDebtCloseFactorPct,
            insolvencyRiskUnhealthyLtvPct: this.insolvencyRiskUnhealthyLtvPct,
            minFullLiquidationValueThreshold: this.minFullLiquidationValueThreshold.toString(),
            maxLiquidatableDebtMarketValueAtOnce: this.maxLiquidatableDebtMarketValueAtOnce.toString(),
            reserved0: this.reserved0,
            globalAllowedBorrowValue: this.globalAllowedBorrowValue.toString(),
            riskCouncil: this.riskCouncil,
            reserved1: this.reserved1,
            elevationGroups: this.elevationGroups.map((item) => item.toJSON()),
            elevationGroupPadding: this.elevationGroupPadding.map((item) => item.toString()),
            minNetValueInObligationSf: this.minNetValueInObligationSf.toString(),
            minValueSkipLiquidationLtvChecks: this.minValueSkipLiquidationLtvChecks.toString(),
            name: this.name,
            minValueSkipLiquidationBfChecks: this.minValueSkipLiquidationBfChecks.toString(),
            individualAutodeleverageMarginCallPeriodSecs: this.individualAutodeleverageMarginCallPeriodSecs.toString(),
            minInitialDepositAmount: this.minInitialDepositAmount.toString(),
            obligationOrderExecutionEnabled: this.obligationOrderExecutionEnabled,
            immutable: this.immutable,
            obligationOrderCreationEnabled: this.obligationOrderCreationEnabled,
            priceTriggeredLiquidationDisabled: this.priceTriggeredLiquidationDisabled,
            padding2: this.padding2,
            proposerAuthority: this.proposerAuthority,
            padding1: this.padding1.map((item) => item.toString()),
        };
    }
    static fromJSON(obj) {
        return new LendingMarket({
            version: new bn_js_1.default(obj.version),
            bumpSeed: new bn_js_1.default(obj.bumpSeed),
            lendingMarketOwner: (0, kit_1.address)(obj.lendingMarketOwner),
            lendingMarketOwnerCached: (0, kit_1.address)(obj.lendingMarketOwnerCached),
            quoteCurrency: obj.quoteCurrency,
            referralFeeBps: obj.referralFeeBps,
            emergencyMode: obj.emergencyMode,
            autodeleverageEnabled: obj.autodeleverageEnabled,
            borrowDisabled: obj.borrowDisabled,
            priceRefreshTriggerToMaxAgePct: obj.priceRefreshTriggerToMaxAgePct,
            liquidationMaxDebtCloseFactorPct: obj.liquidationMaxDebtCloseFactorPct,
            insolvencyRiskUnhealthyLtvPct: obj.insolvencyRiskUnhealthyLtvPct,
            minFullLiquidationValueThreshold: new bn_js_1.default(obj.minFullLiquidationValueThreshold),
            maxLiquidatableDebtMarketValueAtOnce: new bn_js_1.default(obj.maxLiquidatableDebtMarketValueAtOnce),
            reserved0: obj.reserved0,
            globalAllowedBorrowValue: new bn_js_1.default(obj.globalAllowedBorrowValue),
            riskCouncil: (0, kit_1.address)(obj.riskCouncil),
            reserved1: obj.reserved1,
            elevationGroups: obj.elevationGroups.map((item) => types.ElevationGroup.fromJSON(item)),
            elevationGroupPadding: obj.elevationGroupPadding.map((item) => new bn_js_1.default(item)),
            minNetValueInObligationSf: new bn_js_1.default(obj.minNetValueInObligationSf),
            minValueSkipLiquidationLtvChecks: new bn_js_1.default(obj.minValueSkipLiquidationLtvChecks),
            name: obj.name,
            minValueSkipLiquidationBfChecks: new bn_js_1.default(obj.minValueSkipLiquidationBfChecks),
            individualAutodeleverageMarginCallPeriodSecs: new bn_js_1.default(obj.individualAutodeleverageMarginCallPeriodSecs),
            minInitialDepositAmount: new bn_js_1.default(obj.minInitialDepositAmount),
            obligationOrderExecutionEnabled: obj.obligationOrderExecutionEnabled,
            immutable: obj.immutable,
            obligationOrderCreationEnabled: obj.obligationOrderCreationEnabled,
            priceTriggeredLiquidationDisabled: obj.priceTriggeredLiquidationDisabled,
            padding2: obj.padding2,
            proposerAuthority: (0, kit_1.address)(obj.proposerAuthority),
            padding1: obj.padding1.map((item) => new bn_js_1.default(item)),
        });
    }
}
exports.LendingMarket = LendingMarket;
//# sourceMappingURL=LendingMarket.js.map