"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MARKET_UPDATER = exports.KaminoManager = void 0;
const kit_1 = require("@solana/kit");
const vault_1 = require("./vault");
const lib_1 = require("../lib");
const programId_1 = require("../@codegen/klend/programId");
const scope_sdk_1 = require("@kamino-finance/scope-sdk");
const TokenMetadatas_1 = require("@kamino-finance/scope-sdk/dist/@codegen/scope/accounts/TokenMetadatas");
const bn_js_1 = __importDefault(require("bn.js"));
const types_1 = require("../@codegen/klend/types");
const decimal_js_1 = __importDefault(require("decimal.js"));
const accounts_1 = require("../@codegen/kvault/accounts");
const utils_1 = require("../utils");
const types_2 = require("../@codegen/kvault/types");
const dist_1 = require("@kamino-finance/farms-sdk/dist");
const multisig_1 = require("../utils/multisig");
const vault_2 = require("../utils/vault");
const signer_1 = require("../utils/signer");
const system_1 = require("@solana-program/system");
const sysvars_1 = require("@solana/sysvars");
const token_1 = require("@solana-program/token");
const configItems_1 = require("./configItems");
const accounts_2 = require("@kamino-finance/scope-sdk/dist/@codegen/scope/accounts");
const farmUtils_1 = require("../utils/farmUtils");
const cdnClient_1 = require("./cdnClient");
const base58Decoder = (0, kit_1.getBase58Decoder)();
/**
 * KaminoManager is a class that provides a high-level interface to interact with the Kamino Lend and Kamino Vault programs, in order to create and manage a market, as well as vaults
 */
class KaminoManager {
    _rpc;
    _kaminoVaultProgramId;
    _kaminoLendProgramId;
    _farmsProgramId;
    _vaultClient;
    recentSlotDurationMs;
    constructor(rpc, recentSlotDurationMs, kaminoLendProgramId, kaminoVaultProgramId, cdnResources, farmsProgramId) {
        this._rpc = rpc;
        this.recentSlotDurationMs = recentSlotDurationMs ?? lib_1.DEFAULT_RECENT_SLOT_DURATION_MS;
        this._kaminoVaultProgramId = kaminoVaultProgramId ? kaminoVaultProgramId : vault_1.kaminoVaultId;
        this._kaminoLendProgramId = kaminoLendProgramId ? kaminoLendProgramId : programId_1.PROGRAM_ID;
        this._farmsProgramId = farmsProgramId;
        this._vaultClient = new vault_1.KaminoVaultClient(rpc, this.recentSlotDurationMs, this._kaminoVaultProgramId, this._kaminoLendProgramId, cdnResources, farmsProgramId);
    }
    getRpc() {
        return this._rpc;
    }
    getProgramID() {
        return this._kaminoVaultProgramId;
    }
    /**
     * This is a function that helps quickly setting up a reserve for an asset with a default config. The config can be modified later on.
     * @param params.admin - the admin of the market
     * @returns market keypair - keypair used for market account creation -> to be signed with when executing the transaction
     * @returns ixs - an array of ixs for creating and initializing the market account
     */
    async createMarketIxs(params) {
        const marketAccount = await (0, kit_1.generateKeyPairSigner)();
        const size = BigInt(lib_1.LendingMarket.layout.span + 8);
        const [lendingMarketAuthority] = await (0, lib_1.lendingMarketAuthPda)(marketAccount.address, this._kaminoLendProgramId);
        const createMarketIxs = [];
        createMarketIxs.push((0, system_1.getCreateAccountInstruction)({
            payer: params.admin,
            newAccount: marketAccount,
            space: size,
            lamports: await this._rpc.getMinimumBalanceForRentExemption(size).send(),
            programAddress: this._kaminoLendProgramId,
        }));
        const accounts = {
            lendingMarketOwner: params.admin,
            lendingMarket: marketAccount.address,
            lendingMarketAuthority: lendingMarketAuthority,
            systemProgram: system_1.SYSTEM_PROGRAM_ADDRESS,
            rent: sysvars_1.SYSVAR_RENT_ADDRESS,
        };
        const args = {
            quoteCurrency: Array(32).fill(0),
        };
        createMarketIxs.push((0, lib_1.initLendingMarket)(args, accounts, undefined, this._kaminoLendProgramId));
        return { market: marketAccount, ixs: createMarketIxs };
    }
    /**
     * This is a function that helps quickly setting up a reserve for an asset with a default config. The config can be modified later on.
     * @param params.admin - the admin of the reserve
     * @param params.marketAddress - the market to create a reserve for, only the market admin can create a reserve for the market
     * @param params.assetConfig - an object that helps generate a default reserve config with some inputs which have to be configured before calling this function
     * @returns reserve - keypair used for reserve creation -> to be signed with when executing the transaction
     * @returns txnIxs - an array of arrays of ixs -> first array for reserve creation, second for updating it with correct params
     */
    async addAssetToMarketIxs(params) {
        const market = await lib_1.LendingMarket.fetch(this._rpc, params.marketAddress, this._kaminoLendProgramId);
        if (!market) {
            throw new Error('Market not found');
        }
        const marketWithAddress = { address: params.marketAddress, state: market };
        const reserve = await lib_1.Reserve.fetch(this._rpc, params.reserveKeypair.address, this._kaminoLendProgramId);
        let createReserveInstructions = [];
        if (!reserve) {
            createReserveInstructions = await (0, lib_1.createReserveIxs)(this._rpc, params.admin, params.adminLiquiditySource, params.marketAddress, params.assetConfig.mint, params.assetConfig.mintTokenProgram, params.reserveKeypair, this._kaminoLendProgramId);
        }
        else {
            console.log('Reserve already exists, skipping creation');
        }
        const configUpdateIxs = await this.updateReserveIxs(params.admin, marketWithAddress, params.reserveKeypair.address, params.assetConfig.getReserveConfig(), undefined, params.globalAdminSigner);
        return { createReserveIxs: createReserveInstructions, configUpdateIxs };
    }
    /**
     * This method initializes the kvault global config (one off, needs to be signed by program owner)
     * @param admin - the admin of the kvault program
     * @returns - an instruction to initialize the kvault global config
     */
    async initKvaultGlobalConfigIx(admin) {
        return this._vaultClient.initKvaultGlobalConfigIx(admin);
    }
    /**
     * This method will create a vault with a given config. The config can be changed later on, but it is recommended to set it up correctly from the start
     * @param vaultConfig - the config object used to create a vault
     * @returns vault: the keypair of the vault, used to sign the initialization transaction; initVaultIxs: a struct with ixs to initialize the vault and its lookup table + populateLUTIxs, a list to populate the lookup table which has to be executed in a separate transaction
     */
    async createVaultIxs(vaultConfig, useDevnetFarms = false) {
        return this._vaultClient.createVaultIxs(vaultConfig, useDevnetFarms);
    }
    /**
     * This method creates a farm for a vault
     * @param admin - the admin of the vault
     * @param vault - the vault to create a farm for (the vault should be already initialized)
     * @returns a struct with the farm, the setup farm ixs and the update farm ixs
     */
    async createVaultFarmIxs(admin, vault) {
        const vaultState = await vault.getState();
        if (!vaultState) {
            throw new Error('Vault not initialized');
        }
        if (vaultState.vaultFarm !== lib_1.DEFAULT_PUBLIC_KEY) {
            throw new Error('Vault already has a farm');
        }
        return this._vaultClient.createVaultFarm(admin, vault.address, vaultState.sharesMint);
    }
    /**
     * This method creates an instruction to set the shares metadata for a vault
     * @param authority - the vault admin
     * @param vault - the vault to set the shares metadata for
     * @param tokenName - the name of the token in the vault (symbol; e.g. "USDC" which becomes "kVUSDC")
     * @param extraName - the extra string appended to the prefix("Kamino Vault USDC <extraName>")
     * @returns - an instruction to set the shares metadata for the vault
     */
    async getSetSharesMetadataIx(authority, vault, tokenName, extraName, metadataProgramId, kvaultProgramId) {
        const vaultState = await vault.getState();
        return this._vaultClient.getSetSharesMetadataIx(this._rpc, authority, vault.address, vaultState.sharesMint, vaultState.baseVaultAuthority, tokenName, extraName, metadataProgramId, kvaultProgramId);
    }
    /**
     * This method updates the vault reserve allocation cofnig for an exiting vault reserve, or adds a new reserve to the vault if it does not exist.
     * @param vault - vault to be updated
     * @param reserveAllocationConfig - new reserve allocation config
     * @param [signer] - optional parameter to pass a different signer for the instruction. If not provided, the admin of the vault will be used
     * @returns - a struct with an instruction to update the reserve allocation and an optional list of instructions to update the lookup table for the allocation changes
     */
    async updateVaultReserveAllocationIxs(vault, reserveAllocationConfig, signer) {
        return this._vaultClient.updateReserveAllocationIxs(vault, reserveAllocationConfig, signer);
    }
    /**
     * This method updates the unallocated weight and cap of a vault (both are optional, if not provided the current values will be used)
     * @param vault - the vault to update the unallocated weight and cap for
     * @param [vaultAdminAuthority] - vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
     * @param [unallocatedWeight] - the new unallocated weight to set. If not provided, the current unallocated weight will be used
     * @param [unallocatedCap] - the new unallocated cap to set. If not provided, the current unallocated cap will be used
     * @returns - a list of instructions to update the unallocated weight and cap
     */
    async updateVaultUnallocatedWeightAndCapIxs(vault, vaultReservesMap, vaultAdminAuthority, unallocatedWeight, unallocatedCap) {
        return this._vaultClient.updateVaultUnallocatedWeightAndCapIxs(vault, vaultReservesMap, vaultAdminAuthority, unallocatedWeight, unallocatedCap);
    }
    /**
     * This method removes a reserve from the vault allocation strategy if already part of the allocation strategy
     * @param vault - vault to remove the reserve from
     * @param reserve - reserve to remove from the vault allocation strategy
     * @param [vaultAdminAuthority] - vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
     * @returns - an instruction to remove the reserve from the vault allocation strategy or undefined if the reserve is not part of the allocation strategy
     */
    async removeReserveFromAllocationIx(vault, reserve, vaultAdminAuthority) {
        return this._vaultClient.removeReserveFromAllocationIx(vault, reserve, vaultAdminAuthority);
    }
    /**
     * This method sets weight to 0, remove tokens and remove from allocation a reserve from the vault
     * @param signer - signer to use for the transaction
     * @param kaminoVault - vault to remove the reserve from
     * @param reserveAddress - reserve to remove from the vault allocation strategy
     * @param currentSlot - current slot, fetched from chain
     * @param [reserveState] - optional parameter to pass a reserve state. If not provided, the reserve will be fetched from the connection
     * @returns - an array of instructions to set the reserve allocation to 0, invest the reserve if it has tokens, and remove the reserve from the allocation
     */
    async fullRemoveReserveFromVaultIxs(signer, kaminoVault, reserveAddress, currentSlot, reserveState) {
        const connection = this.getRpc();
        const vaultState = await kaminoVault.getState();
        const allocations = this.getVaultReserves(vaultState);
        if (!allocations.includes(reserveAddress)) {
            throw new Error('Reserve not found in vault allocations');
        }
        const fetchedReserveState = reserveState ?? (await lib_1.Reserve.fetch(connection, reserveAddress, this._kaminoLendProgramId));
        if (!fetchedReserveState) {
            throw new Error('Reserve not found');
        }
        const reserveWithAddress = {
            address: reserveAddress,
            state: fetchedReserveState,
        };
        const kaminoReserve = await lib_1.KaminoReserve.initializeFromAddress(reserveAddress, connection, this.recentSlotDurationMs, fetchedReserveState);
        const reserveAllocationConfig = new vault_1.ReserveAllocationConfig(reserveWithAddress, 0, new decimal_js_1.default(0));
        const setAllocationToZeroIx = await this.updateVaultReserveAllocationIxs(kaminoVault, reserveAllocationConfig, signer);
        const vaultReservesMap = await this.loadVaultReserves(vaultState);
        const investIx = await this.investSingleReserveIxs(signer, kaminoVault, reserveWithAddress, vaultReservesMap);
        const removeAllocationIx = await this.removeReserveFromAllocationIx(kaminoVault, reserveAddress, signer);
        const ixs = [setAllocationToZeroIx.updateReserveAllocationIx];
        const suppliedInReserve = this.getSuppliedInReserve(vaultState, currentSlot, kaminoReserve);
        if (suppliedInReserve.gt(new decimal_js_1.default(0))) {
            ixs.push(...investIx);
        }
        if (removeAllocationIx) {
            ixs.push(removeAllocationIx);
        }
        return ixs;
    }
    /**
     * This method withdraws all the funds from a reserve and blocks it from being invested by setting its weight and ctoken allocation to 0
     * @param vault - the vault to withdraw the funds from
     * @param reserve - the reserve to withdraw the funds from
     * @param [vaultAdminAuthority] - vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
     * @returns - a struct with an instruction to update the reserve allocation and an optional list of instructions to update the lookup table for the allocation changes
     */
    async withdrawEverythingAndBlockInvestReserve(vault, reserve, vaultAdminAuthority) {
        return this._vaultClient.withdrawEverythingAndBlockInvestReserve(vault, reserve, vaultAdminAuthority);
    }
    /**
     * This method withdraws all the funds from all the reserves and blocks them from being invested by setting their weight and ctoken allocation to 0
     * @param vault - the vault to withdraw the invested funds from
     * @param slot - current slot used for reserve and vault calculations
     * @param [vaultReservesMap] - optional parameter to pass a map of the vault reserves. If not provided, the reserves will be loaded from the vault
     * @param [payer] - optional parameter to pass a different payer for the transaction. If not provided, the admin of the vault will be used; this is the payer for the invest ixs and it should have an ATA and some lamports (2x no_of_reserves) of the token vault
     * @returns - a struct with an instruction to update the reserve allocation and an optional list of instructions to update the lookup table for the allocation changes
     */
    async withdrawEverythingFromAllReservesAndBlockInvest(vault, slot, vaultReservesMap, payer) {
        return this._vaultClient.withdrawEverythingFromAllReservesAndBlockInvest(vault, slot, vaultReservesMap, payer);
    }
    /**
     * This method disinvests all the funds from all the reserves and set their weight to 0; for vaults that are managed by external bot/crank, the bot can change the weight and invest in the reserves again
     * @param vault - the vault to disinvest the invested funds from
     * @param slot - current slot used for reserve and vault calculations
     * @param [vaultReservesMap] - optional parameter to pass a map of the vault reserves. If not provided, the reserves will be loaded from the vault
     * @param [payer] - optional parameter to pass a different payer for the transaction. If not provided, the admin of the vault will be used; this is the payer for the invest ixs and it should have an ATA and some lamports (2x no_of_reserves) of the token vault
     * @returns - a struct with an instruction to update the reserve allocations to 0 weight and a list of instructions to disinvest the funds in the reserves
     */
    async disinvestAllReservesIxs(vault, slot, vaultReservesMap, payer) {
        return this._vaultClient.disinvestAllReservesIxs(vault, slot, vaultReservesMap, payer);
    }
    // async closeVault(vault: KaminoVault): Promise<TransactionInstruction> {
    //   return this._vaultClient.closeVaultIx(vault);
    // }
    /**
     * This method retruns the reserve config for a given reserve
     * @param reserve - reserve to get the config for
     * @param [reserveState] - optional reserve state. If provided, the fetch will be skipped
     * @returns - the reserve config
     */
    async getReserveConfig(reserve, reserveState) {
        const state = reserveState ?? (await lib_1.Reserve.fetch(this._rpc, reserve));
        if (!state) {
            throw new Error('Reserve not found');
        }
        return state.config;
    }
    /**
     * This function enables the update of the scope oracle configuration. In order to get a list of scope prices, getScopeOracleConfigs can be used
     * @param lendingMarketOwner - market admin
     * @param market - lending market which owns the reserve
     * @param reserve - reserve which to be updated
     * @param oraclePrices - scope OraclePrices account pubkey
     * @param scopeOracleConfig - new scope oracle config
     * @param scopeTwapConfig - new scope twap config
     * @param maxAgeBufferSeconds - buffer to be added to onchain max_age - if oracle price is older than that, txns interacting with the reserve will fail
     * @returns - an array of instructions used update the oracle configuration
     */
    async updateReserveScopeOracleConfigurationIxs(lendingMarketOwner, market, reserve, oraclePrices, scopeOracleConfig, scopeTwapConfig, maxAgeBufferSeconds = 20) {
        const reserveConfig = reserve.state.config;
        let scopeTwapId = scope_sdk_1.U16_MAX;
        if (scopeTwapConfig) {
            scopeTwapId = scopeTwapConfig.oracleId;
            // if(scopeTwapConfig.twapSourceId !== scopeOracleConfig.oracleId) {
            //   throw new Error('Twap source id must match oracle id');
            // }
        }
        const { scopeConfiguration } = (0, lib_1.getReserveOracleConfigs)({
            scopePriceConfigAddress: oraclePrices,
            scopeChain: [scopeOracleConfig.oracleId],
            scopeTwapChain: [scopeTwapId],
        });
        const newReserveConfig = new types_1.ReserveConfig({
            ...reserveConfig,
            tokenInfo: {
                ...reserveConfig.tokenInfo,
                scopeConfiguration: scopeConfiguration,
                // TODO: Decide if we want to keep this maxAge override for twap & price
                maxAgeTwapSeconds: scopeTwapConfig
                    ? new bn_js_1.default(scopeTwapConfig.max_age + maxAgeBufferSeconds)
                    : reserveConfig.tokenInfo.maxAgeTwapSeconds,
                maxAgePriceSeconds: new bn_js_1.default(scopeOracleConfig.max_age + maxAgeBufferSeconds),
            },
        });
        const updateIxs = await this.updateReserveIxs(lendingMarketOwner, market, reserve.address, newReserveConfig, reserve.state);
        return updateIxs.map((item) => item.ix);
    }
    /**
     * This function updates the given reserve with a new config. It updates fields which differ between given reserve config and existing reserve config
     * @param lendingMarketOwner - market authority
     * @param marketWithAddress - the market that owns the reserve to be updated
     * @param reserve - the reserve to be updated
     * @param config - the new reserve configuration to be used for the update
     * @param reserveStateOverride - the reserve state, useful to provide, if already fetched outside this method, in order to avoid an extra rpc call to fetch it. Make sure the reserveConfig has not been updated since fetching the reserveState that you pass in.
     * @param globalAdminSigner - optional global admin signer for config modes that require it
     * @returns - an array of update instructions with metadata indicating if global admin is required as signer.
     * If there are many fields that are being updated, multiple transactions might be required to fit all ixs.
     */
    async updateReserveIxs(lendingMarketOwner, marketWithAddress, reserve, config, reserveStateOverride, globalAdminSigner) {
        const reserveState = reserveStateOverride
            ? reserveStateOverride
            : (await lib_1.Reserve.fetch(this._rpc, reserve, this._kaminoLendProgramId));
        const ixs = [];
        ixs.push(...(await (0, lib_1.parseForChangesReserveConfigAndGetIxs)(marketWithAddress, reserveState, reserve, config, this._kaminoLendProgramId, lendingMarketOwner, globalAdminSigner)));
        return ixs;
    }
    /**
     * This function creates instructions to deposit into a vault. It will also create ATA creation instructions for the vault shares that the user receives in return
     * @param user - user to deposit
     * @param vault - vault to deposit into (if the state is not provided, it will be fetched)
     * @param tokenAmount - token amount to be deposited, in decimals (will be converted in lamports)
     * @param vaultReservesMap - preloaded reserve states for every reserve in the vault allocation
     * @param farmState - preloaded vault farm state; provide this to stake into the vault farm
     * @param flcFarmState - preloaded first loss capital farm state; provide this to stake into the first loss capital farm
     * Pass only one of `farmState` or `flcFarmState`, depending on whether you want vault-farm or first loss capital farm behavior. Pass neither to skip staking.
     * @param [memo] - optional memo string to append as a memo SPL instruction
     * @returns - an instance of DepositIxs which contains the instructions to deposit in vault and the instructions to stake the shares in the farm if the vault has a farm
     */
    async depositToVaultIxs(user, vault, tokenAmount, vaultReservesMap, farmState, flcFarmState, payer, memo) {
        return this._vaultClient.depositIxs(user, vault, tokenAmount, vaultReservesMap, farmState, flcFarmState, payer, memo);
    }
    /**
     * This function creates instructions to buy shares (i.e. deposit) into a vault. It will also create ATA creation instructions for the vault shares that the user receives in return
     * @param user - user to nuy shares
     * @param vault - vault to buy shares from (if the state is not provided, it will be fetched)
     * @param tokenAmount - token amount to be swapped for shares, in decimals (will be converted in lamports)
     * @param vaultReservesMap - preloaded reserve states for every reserve in the vault allocation
     * @param farmState - preloaded vault farm state; provide this to stake into the vault farm
     * @param flcFarmState - preloaded first loss capital farm state; provide this to stake into the first loss capital farm
     * Pass only one of `farmState` or `flcFarmState`, depending on whether you want vault-farm or first loss capital farm behavior. Pass neither to skip staking.
     * @param [payer] - optional parameter to pass a different payer for ATA creation rent. If not provided, the user will be used
     * @returns - an instance of DepositIxs which contains the instructions to buy shares in vault and the instructions to stake the shares in the farm if the vault has a farm
     */
    async buyVaultSharesIxs(user, vault, tokenAmount, vaultReservesMap, farmState, flcFarmState, payer) {
        return this._vaultClient.buySharesIxs(user, vault, tokenAmount, vaultReservesMap, farmState, flcFarmState, payer);
    }
    /**
     * This function creates instructions to stake the shares in the vault farm if the vault has a configured vault farm
     * @param user - user to stake
     * @param vault - vault to deposit into its farm (if the state is not provided, it will be fetched)
     * @param [sharesAmount] - token amount to be deposited, in decimals (will be converted in lamports). Optional. If not provided, the user's share balance will be used
     * @param farmState - preloaded vault farm state; required when the vault has a configured vault farm
     * @returns - a list of instructions for the user to stake shares into the vault's farm, including the creation of prerequisite accounts if needed
     */
    async stakeSharesIxs(user, vault, sharesAmount, farmState) {
        return this._vaultClient.stakeSharesIxs(user, vault, sharesAmount, farmState);
    }
    /**
     * Update a field of the vault. If the field is a pubkey it will return an extra instruction to add that account into the lookup table
     * @param vault the vault to update
     * @param mode the field to update (based on VaultConfigFieldKind enum)
     * @param value the value to update the field with
     * @param [signer] the signer of the transaction. Optional. If not provided the admin of the vault will be used. It should be used when changing the admin of the vault if we want to build or batch multiple ixs in the same tx
     * @param [lutIxsSigner] the signer of the transaction to be used for the lookup table instructions. Optional. If not provided the admin of the vault will be used. It should be used when changing the admin of the vault if we want to build or batch multiple ixs in the same tx
     * @param [skipLutUpdate] if true, the lookup table instructions will not be included in the returned instructions
     * @param errorOnOverride throw error if vault already has a farm
     * @param bypassConfigValidations if true, the config validations will not be performed
     * @returns a struct that contains the instruction to update the field and an optional list of instructions to update the lookup table
     */
    async updateVaultConfigIxs(vault, mode, value, vaultReservesMap, signer, lutIxsSigner, skipLutUpdate = false, errorOnOverride = true, bypassConfigValidations = false) {
        if (typeof mode === 'string') {
            const field = types_2.VaultConfigField.fromDecoded({ [mode]: '' });
            return this._vaultClient.updateVaultConfigIxs(vault, field, value, vaultReservesMap, signer, lutIxsSigner, skipLutUpdate, errorOnOverride, bypassConfigValidations);
        }
        return this._vaultClient.updateVaultConfigIxs(vault, mode, value, vaultReservesMap, signer, lutIxsSigner, skipLutUpdate, errorOnOverride, bypassConfigValidations);
    }
    /**
     * Append the remaining reserve accounts required by vault instructions.
     * @param ix - the instruction to append the remaining accounts to
     * @param vaultReserves - the vault reserve addresses to append
     * @param vaultReservesState - preloaded reserve state for each vault reserve
     * @returns the instruction with reserve remaining accounts appended
     */
    appendRemainingAccountsForVaultReserves(ix, vaultReserves, vaultReservesState) {
        return this._vaultClient.appendRemainingAccountsForVaultReserves(ix, vaultReserves, vaultReservesState);
    }
    /**
     * Update the vault performance fee (in bps).
     */
    async updateVaultPerfFeeIxs(vault, feeBps, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultPerfFeeIxs(vault, feeBps, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault management fee (in bps).
     */
    async updateVaultMgmtFeeIxs(vault, feeBps, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultMgmtFeeIxs(vault, feeBps, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the pending admin for the vault (step 1/2 of the ownership transfer).
     */
    async updateVaultPendingAdminIxs(vault, newAdmin, vaultReservesMap, vaultAdminAuthority, lutIxsSigner, skipLutUpdate = false) {
        return this._vaultClient.updateVaultPendingAdminIxs(vault, newAdmin, vaultReservesMap, vaultAdminAuthority, lutIxsSigner, skipLutUpdate);
    }
    /**
     * Update the vault name.
     */
    async updateVaultNameIxs(vault, name, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultNameIxs(vault, name, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault lookup table address.
     */
    async updateVaultLookupTableIxs(vault, lookupTable, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultLookupTableIxs(vault, lookupTable, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault allocation admin.
     */
    async updateVaultAllocationAdminIxs(vault, allocationAdmin, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultAllocationAdminIxs(vault, allocationAdmin, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault unallocated weight.
     */
    async updateVaultUnallocatedWeightIxs(vault, unallocatedWeight, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultUnallocatedWeightIxs(vault, unallocatedWeight, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault unallocated tokens cap.
     */
    async updateVaultUnallocatedTokensCapIxs(vault, unallocatedTokensCap, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultUnallocatedTokensCapIxs(vault, unallocatedTokensCap, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault farm address.
     */
    async updateVaultFarmIxs(vault, farm, vaultReservesMap, errorOnOverride = true, vaultAdminAuthority, lutIxsSigner, skipLutUpdate = false) {
        return this._vaultClient.updateVaultFarmIxs(vault, farm, vaultReservesMap, errorOnOverride, vaultAdminAuthority, lutIxsSigner, skipLutUpdate);
    }
    /**
     * Update the first loss capital farm address.
     */
    async updateVaultFirstLossCapitalFarmIxs(vault, farm, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultFirstLossCapitalFarmIxs(vault, farm, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault min deposit amount (in lamports).
     */
    async updateVaultMinDepositAmountIxs(vault, minDepositAmount, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultMinDepositAmountIxs(vault, minDepositAmount, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault min withdraw amount (in lamports).
     */
    async updateVaultMinWithdrawAmountIxs(vault, minWithdrawAmount, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultMinWithdrawAmountIxs(vault, minWithdrawAmount, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault min invest amount (in lamports).
     */
    async updateVaultMinInvestAmountIxs(vault, minInvestAmount, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultMinInvestAmountIxs(vault, minInvestAmount, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault min invest delay (in slots).
     */
    async updateVaultMinInvestDelaySlotsIxs(vault, minInvestDelaySlots, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultMinInvestDelaySlotsIxs(vault, minInvestDelaySlots, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault crank fund fee per reserve (in lamports).
     */
    async updateVaultCrankFundFeePerReserveIxs(vault, crankFundFeePerReserve, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultCrankFundFeePerReserveIxs(vault, crankFundFeePerReserve, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault withdrawal penalty (in lamports).
     */
    async updateVaultWithdrawalPenaltyLamportsIxs(vault, withdrawalPenaltyLamports, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultWithdrawalPenaltyLamportsIxs(vault, withdrawalPenaltyLamports, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update the vault withdrawal penalty (in bps).
     */
    async updateVaultWithdrawalPenaltyBpsIxs(vault, withdrawalPenaltyBps, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.updateVaultWithdrawalPenaltyBpsIxs(vault, withdrawalPenaltyBps, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * Update whether allocations are restricted to whitelisted reserves only.
     */
    async updateVaultAllowAllocationsInWhitelistedReservesOnlyIxs(vault, allowWhitelistedOnly, vaultReservesMap, adminAuthority) {
        return this._vaultClient.updateVaultAllowAllocationsInWhitelistedReservesOnlyIxs(vault, allowWhitelistedOnly, vaultReservesMap, adminAuthority);
    }
    /**
     * Update whether invest is restricted to whitelisted reserves only.
     */
    async updateVaultAllowInvestInWhitelistedReservesOnlyIxs(vault, allowWhitelistedOnly, vaultReservesMap, adminAuthority) {
        return this._vaultClient.updateVaultAllowInvestInWhitelistedReservesOnlyIxs(vault, allowWhitelistedOnly, vaultReservesMap, adminAuthority);
    }
    /**
     * Add or update a reserve whitelist entry. This controls whether the reserve is whitelisted for adding/updating
     * allocations or for invest, depending on the mode parameter.
     *
     * @param reserve - Address of the reserve to whitelist
     * @param mode - The whitelist mode: either 'Invest' or 'AddAllocation' with a value (1 = add, 0 = remove)
     * @param globalAdmin - The global admin that signs the transaction
     * @returns - An instruction to add/update the whitelisted reserve entry
     */
    async addUpdateWhitelistedReserveIx(reserve, mode, globalAdmin) {
        return this._vaultClient.addUpdateWhitelistedReserveIx(reserve, mode, globalAdmin);
    }
    /** Sets the farm where the shares can be staked. This is store in vault state and a vault can only have one farm, so the new farm will ovveride the old farm
     * @param vault - vault to set the farm for
     * @param farm - the farm where the vault shares can be staked
     * @param [errorOnOverride] - if true, the function will throw an error if the vault already has a farm. If false, it will override the farm
     * @param [vaultAdminAuthority] - vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
     * @param [lutIxsSigner] (optional) signer of the LUT ixs
     * @param skipLutUpdate  if true, the lookup table instructions will not be included in the returned instructions
     */
    async setVaultFarmIxs(vault, farm, vaultReservesMap, errorOnOverride = true, vaultAdminAuthority, lutIxsSigner, skipLutUpdate = false) {
        return this._vaultClient.setVaultFarmIxs(vault, farm, vaultReservesMap, errorOnOverride, vaultAdminAuthority, lutIxsSigner, skipLutUpdate);
    }
    /**
     * This function creates the instruction for the `pendingAdmin` of the vault to accept to become the owner of the vault (step 2/2 of the ownership transfer)
     * @param vault - vault to change the ownership for
     * @param [pendingAdmin] - pending vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
     * @returns - an instruction to accept the ownership of the vault and a list of instructions to update the lookup table
     */
    async acceptVaultOwnershipIxs(vault, vaultReservesMap, pendingAdmin) {
        return this._vaultClient.acceptVaultOwnershipIxs(vault, vaultReservesMap, pendingAdmin);
    }
    /**
     * This function creates the instruction for the admin to give up a part of the pending fees (which will be accounted as part of the vault)
     * @param vault - vault to give up pending fees for
     * @param maxAmountToGiveUp - the maximum amount of fees to give up, in tokens
     * @param [vaultAdminAuthority] - vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
     * @returns - an instruction to give up the specified pending fees
     */
    async giveUpPendingFeesIx(vault, maxAmountToGiveUp, vaultAdminAuthority) {
        return this._vaultClient.giveUpPendingFeesIx(vault, maxAmountToGiveUp, vaultAdminAuthority);
    }
    /**
     * This function will return the missing ATA creation instructions, as well as one or multiple withdraw instructions, based on how many reserves it's needed to withdraw from. This might have to be split in multiple transactions
     * @param user - user to withdraw
     * @param vault - vault to withdraw from
     * @param shareAmount - share amount to withdraw (in tokens, not lamports), in order to withdraw everything, any value > user share amount
     * @param slot - current slot, used to estimate the interest earned in the different reserves with allocation from the vault
     * @param vaultReservesMap - preloaded reserve states for every reserve in the vault allocation
     * @param farmState - preloaded vault farm state; provide this to unstake from the vault farm
     * @param flcFarmState - preloaded first loss capital farm state; provide this to unstake from the first loss capital farm
     * Pass only one of `farmState` or `flcFarmState`, depending on whether you want vault-farm or first loss capital farm behavior. Pass neither to skip unstaking.
     * @returns an array of instructions to create missing ATAs if needed and the withdraw instructions
     */
    async withdrawFromVaultIxs(user, vault, shareAmount, slot, vaultReservesMap, farmState, flcFarmState, payer) {
        return this._vaultClient.withdrawIxs(user, vault, shareAmount, slot, vaultReservesMap, farmState, flcFarmState, payer);
    }
    /**
     * Redeem shares in kind (receive cTokens instead of underlying tokens).
     * Reserves are selected by highest available liquidity (same order as withdraw).
     * @param user - user to redeem shares
     * @param vault - vault to redeem from
     * @param shareAmount - share amount to redeem (in tokens, not lamports)
     * @param slot - current slot
     * @param vaultReservesMap - preloaded reserve states for every reserve in the vault allocation
     * @param vaultState - preloaded vault state; call `vault.getState()` / `vault.reloadState()` before building instructions
     * @param globalConfigState - preloaded KVault global config; call `manager.loadKVaultGlobalConfig()` before building instructions
     * @param farmState - preloaded vault farm state; provide this to unstake from the vault farm
     * @param flcFarmState - preloaded first loss capital farm state; provide this to unstake from the first loss capital farm
     * Pass only one of `farmState` or `flcFarmState`, depending on whether you want vault-farm or first loss capital farm behavior. Pass neither to skip unstaking.
     * @param [payer] - optional different payer for ATA creation
     * @returns RedeemInKindIxs with setup, redeemInKind, cleanup instructions and luts
     */
    async redeemInKindIxs(user, vault, shareAmount, slot, vaultReservesMap, vaultState, globalConfigState, farmState, flcFarmState, payer) {
        return this._vaultClient.redeemInKindIxs(user, vault, shareAmount, slot, vaultReservesMap, vaultState, globalConfigState, farmState, flcFarmState, payer);
    }
    /**
     * Withdraw as much as possible instantly, then redeem in kind the remaining shares.
     * The withdraw handles farm unstaking for the full exit amount so redeemInKind does not duplicate the unstake.
     * @param user - user to withdraw/redeem
     * @param vault - vault to withdraw/redeem from
     * @param shareAmount - total share amount to exit (in tokens, not lamports)
     * @param slot - current slot
     * @param vaultReservesMap - preloaded reserve states for every reserve in the vault allocation
     * @param vaultState - preloaded vault state; call `vault.getState()` / `vault.reloadState()` before building instructions
     * @param globalConfigState - preloaded KVault global config; call `manager.loadKVaultGlobalConfig()` before building instructions
     * @param farmState - preloaded vault farm state when exiting from the vault farm
     * @param flcFarmState - preloaded first loss capital farm state when exiting from the first loss capital farm
     * Pass only one of `farmState` or `flcFarmState`, depending on whether you want vault-farm or first loss capital farm behavior. Pass neither if no farm exit is needed.
     * @param [payer] - optional different payer for ATA creation
     * @returns WithdrawAndRedeemInKindIxs with both withdraw and redeemInKind instructions
     */
    async withdrawAndRedeemInKindIfNeededIxs(user, vault, shareAmount, slot, vaultReservesMap, vaultState, globalConfigState, farmState, flcFarmState, payer) {
        return this._vaultClient.withdrawAndRedeemInKindIfNeededIxs(user, vault, shareAmount, slot, vaultReservesMap, vaultState, globalConfigState, farmState, flcFarmState, payer);
    }
    /**
     * Withdraw, redeem in kind, and enqueue cTokens into the klend withdrawal queue.
     * This is the top-level function that handles the full exit flow: instant withdraw for available
     * liquidity, redeemInKind for the remainder, and enqueue to eventually receive underlying tokens.
     * @param user - user to withdraw/redeem/enqueue
     * @param vault - vault to withdraw/redeem from
     * @param shareAmount - total share amount to exit (in tokens, not lamports)
     * @param slot - current slot
     * @param vaultReservesMap - preloaded reserve states for every reserve in the vault allocation
     * @param vaultState - preloaded vault state; call `vault.getState()` / `vault.reloadState()` before building instructions
     * @param globalConfigState - preloaded KVault global config; call `manager.loadKVaultGlobalConfig()` before building instructions
     * @param farmState - preloaded vault farm state when exiting from the vault farm
     * @param flcFarmState - preloaded first loss capital farm state when exiting from the first loss capital farm
     * Pass only one of `farmState` or `flcFarmState`, depending on whether you want vault-farm or first loss capital farm behavior. Pass neither if no farm exit is needed.
     * @param [payer] - optional different payer for ATA creation
     * @returns WithdrawRedeemAndEnqueueIxs with withdraw, redeemInKind, and enqueue instructions
     */
    async withdrawRedeemAndEnqueueIxs(user, vault, shareAmount, slot, vaultReservesMap, vaultState, globalConfigState, farmState, flcFarmState, payer) {
        return this._vaultClient.withdrawRedeemAndEnqueueIxs(user, vault, shareAmount, slot, vaultReservesMap, vaultState, globalConfigState, farmState, flcFarmState, payer);
    }
    /**
     * This function will return the missing ATA creation instructions, as well as one or multiple withdraw instructions, based on how many reserves it's needed to withdraw from. This might have to be split in multiple transactions
     * @param user - user to sell shares for vault tokens
     * @param vault - vault to sell shares from
     * @param shareAmount - share amount to sell (in tokens, not lamports), in order to withdraw everything, any value > user share amount
     * @param slot - current slot, used to estimate the interest earned in the different reserves with allocation from the vault
     * @param vaultReservesMap - preloaded reserve states for every reserve in the vault allocation
     * @param farmState - preloaded vault farm state when exiting from the vault farm
     * @param flcFarmState - preloaded first loss capital farm state when exiting from the first loss capital farm
     * Pass only one of `farmState` or `flcFarmState`, depending on whether you want vault-farm or first loss capital farm behavior. Pass neither if no farm exit is needed.
     * @param [payer] - optional parameter to pass a different payer for ATA creation rent. If not provided, the user will be used
     * @returns an array of instructions to create missing ATAs if needed and the withdraw instructions
     */
    async sellVaultSharesIxs(user, vault, shareAmount, slot, vaultReservesMap, farmState, flcFarmState, payer) {
        return this._vaultClient.sellSharesIxs(user, vault, shareAmount, slot, vaultReservesMap, farmState, flcFarmState, payer);
    }
    /**
     * This method withdraws all the pending fees from the vault to the owner's token ATA
     * @param vault - vault for which the admin withdraws the pending fees
     * @param slot - current slot, used to estimate the interest earned in the different reserves with allocation from the vault
     * @param [vaultAdminAuthority] - vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
     * @param [vaultReservesMap] - optional parameter; a hashmap from each reserve pubkey to the reserve state. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @returns - list of instructions to withdraw all pending fees, including the ATA creation instructions if needed
     */
    async withdrawPendingFeesIxs(vault, slot, vaultReservesMap, vaultAdminAuthority) {
        return this._vaultClient.withdrawPendingFeesIxs(vault, slot, vaultReservesMap, vaultAdminAuthority);
    }
    /**
     * This method inserts the missing keys from the provided keys into an existent lookup table
     * @param payer - payer wallet pubkey
     * @param lut - lookup table to insert the keys into
     * @param keys - keys to insert into the lookup table
     * @param [accountsInLUT] - the existent accounts in the lookup table. Optional. If provided, the function will not fetch the accounts in the lookup table
     * @returns - an array of instructions to insert the missing keys into the lookup table
     */
    async insertIntoLutIxs(payer, lut, keys, accountsInLUT) {
        return (0, lib_1.insertIntoLookupTableIxs)(this._vaultClient.getConnection(), payer, lut, keys, accountsInLUT);
    }
    /**
     * Sync a vault for lookup table; create and set the LUT for the vault if needed and fill it with all the needed accounts
     * @param authority - vault admin
     * @param vault - the vault to sync and set the LUT for if needed
     * @param [vaultReserves] - optional; the state of the reserves in the vault allocation
     * @returns a struct that contains a list of ix to create the LUT and assign it to the vault if needed + a list of ixs to insert all the accounts in the LUT
     */
    async syncVaultLUTIxs(authority, vault, slot, vaultReserves) {
        return this._vaultClient.syncVaultLookupTableIxs(authority, vault, slot, vaultReserves);
    }
    /**
     * This method calculates the token per share value. This will always change based on interest earned from the vault, but calculating it requires a bunch of rpc requests. Caching this for a short duration would be optimal
     * @param vault - vault to calculate tokensPerShare for
     * @param slot - the slot at which we retrieve the tokens per share
     * @param [vaultReservesMap] - hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @param [currentSlot] - the latest confirmed slot. Optional. If provided the function will be  faster as it will not have to fetch the latest slot
     * @returns - token per share value
     */
    async getTokensPerShareSingleVault(vault, slot, vaultReservesMap, currentSlot) {
        return this._vaultClient.getTokensPerShareSingleVault(vault, slot, vaultReservesMap, currentSlot);
    }
    /**
     * This method calculates the price of one vault share(kToken)
     * @param vault - vault to calculate sharePrice for
     * @param tokenPrice - the price of the vault token (e.g. SOL) in USD
     * @param slot - the slot at which we retrieve the tokens per share
     * @param [vaultReservesMap] - hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @param [currentSlot] - the latest confirmed slot. Optional. If provided the function will be  faster as it will not have to fetch the latest slot
     * @returns - share value in USD
     */
    async getSharePriceInUSD(vault, tokenPrice, slot, vaultReservesMap, currentSlot) {
        const tokensPerShare = await this.getTokensPerShareSingleVault(vault, slot, vaultReservesMap, currentSlot);
        return tokensPerShare.mul(tokenPrice);
    }
    /**
     * This method returns the user shares balance for a given vault
     * @param user - user to calculate the shares balance for
     * @param vault - vault to calculate shares balance for
     * @returns - a struct of user share balance (unstaked plus shares staked in either configured farm) in decimal (not lamports)
     */
    async getUserSharesBalanceSingleVault(user, vault) {
        return this._vaultClient.getUserSharesBalanceSingleVault(user, vault);
    }
    /**
     * This method returns the user shares balance for all existing vaults
     * @param user - user to calculate the shares balance for
     * @param vaultsOverride - the kamino vaults if already fetched, in order to reduce rpc calls
     * @returns - hash map with keyh as vault address and value as user share balance in decimal (not lamports)
     */
    async getUserSharesBalanceAllVaults(user, vaultsOverride) {
        return this._vaultClient.getUserSharesBalanceAllVaults(user, vaultsOverride);
    }
    /**
     * This method returns the management and performance fee percentages
     * @param vaultState - vault to retrieve the fees percentages from
     * @returns - VaultFeesPct containing management and performance fee percentages
     */
    getVaultFeesPct(vaultState) {
        return this._vaultClient.getVaultFeesPct(vaultState);
    }
    /**
     * This method returns the vault name
     * @param vaultState - vault to retrieve the onchain name for
     * @returns - the vault name as string
     */
    getDecodedVaultName(vaultState) {
        return this._vaultClient.decodeVaultName(vaultState.name);
    }
    /**
     * @returns - the KaminoVault client
     */
    getKaminoVaultClient() {
        return this._vaultClient;
    }
    /**
     * Get all vaults
     * @returns an array of all vaults
     */
    async getAllVaults() {
        return this._vaultClient.getAllVaults();
    }
    /**
     * Get all lending markets
     * @returns an array of all lending markets
     */
    async getAllMarkets(programId = this._kaminoLendProgramId) {
        // Get all lending markets
        const marketGenerator = (0, lib_1.getAllLendingMarketAccounts)(this.getRpc(), programId);
        const lendingMarketPairs = [];
        for await (const pair of marketGenerator) {
            lendingMarketPairs.push(pair);
        }
        // Get all reserves
        const allReserveAccounts = (0, lib_1.getAllReserveAccounts)(this.getRpc(), programId);
        const reservePairs = [];
        for await (const pair of allReserveAccounts) {
            reservePairs.push(pair);
        }
        const allReserves = reservePairs.map(([, reserve]) => reserve);
        // Get all oracle accounts
        const [allOracleAccounts, cdnResourcesData] = await Promise.all([
            (0, lib_1.getAllOracleAccounts)(this.getRpc(), allReserves),
            cdnClient_1.kaminoCdn.getData(),
        ]);
        // Group reserves by market
        const marketToReserve = new Map();
        for (const [reserveAddress, reserveState] of reservePairs) {
            const marketAddress = reserveState.lendingMarket;
            if (!marketToReserve.has(marketAddress)) {
                marketToReserve.set(marketAddress, [
                    {
                        address: reserveAddress,
                        state: reserveState,
                    },
                ]);
            }
            else {
                marketToReserve.get(marketAddress)?.push({
                    address: reserveAddress,
                    state: reserveState,
                });
            }
        }
        const combinedMarkets = lendingMarketPairs.map(([pubkey, market]) => {
            const reserves = marketToReserve.get(pubkey);
            const reservesByAddress = new Map();
            if (!reserves) {
                console.log(`Market ${pubkey.toString()} ${(0, lib_1.parseTokenSymbol)(market.name)} has no reserves`);
            }
            else {
                const reservesAndOracles = (0, lib_1.getTokenOracleDataSync)(allOracleAccounts, reserves);
                reservesAndOracles.forEach(([{ address: reserveAddress, state: reserve }, oracle]) => {
                    if (!oracle) {
                        console.log('Manager > getAllMarkets: oracle not found for reserve', reserve.config.tokenInfo.name);
                        return;
                    }
                    const kaminoReserve = lib_1.KaminoReserve.initialize(reserveAddress, reserve, oracle, this.getRpc(), this.recentSlotDurationMs, cdnResourcesData);
                    reservesByAddress.set(kaminoReserve.address, kaminoReserve);
                });
            }
            return lib_1.KaminoMarket.loadWithReserves(this.getRpc(), market, reservesByAddress, pubkey, this.recentSlotDurationMs);
        });
        return combinedMarkets;
    }
    /**
     * Get all vaults for owner
     * @param owner the pubkey of the vaults owner
     * @returns an array of all vaults owned by a given pubkey
     */
    async getAllVaultsForOwner(owner) {
        const size = accounts_1.VaultState.layout.span + 8;
        const filters = [
            {
                dataSize: BigInt(size),
            },
            {
                memcmp: {
                    offset: 0n,
                    bytes: base58Decoder.decode(accounts_1.VaultState.discriminator),
                    encoding: 'base58',
                },
            },
            {
                memcmp: {
                    offset: 8n,
                    bytes: owner.toString(),
                    encoding: 'base58',
                },
            },
        ];
        const kaminoVaults = await (0, utils_1.getProgramAccounts)(this._rpc, this._kaminoVaultProgramId, size, filters);
        return kaminoVaults.map((kaminoVault) => {
            const kaminoVaultAccount = (0, vault_2.decodeVaultState)(kaminoVault.data);
            if (!kaminoVaultAccount) {
                throw Error(`kaminoVault with pubkey ${kaminoVault.address} could not be decoded`);
            }
            return vault_1.KaminoVault.loadWithClientAndState(this._vaultClient, kaminoVault.address, kaminoVaultAccount);
        });
    }
    /**
     * Get a list of kaminoVaults
     * @param vaults - a list of vaults to get the states for; if not provided, all vaults will be fetched
     * @returns a list of KaminoVaults
     */
    async getVaults(vaults) {
        return this._vaultClient.getVaults(vaults);
    }
    /**
     * Get all token accounts that hold shares for a specific share mint
     * @param shareMint
     * @returns an array of all holders tokenAccounts pubkeys and their account info
     */
    async getShareTokenAccounts(shareMint) {
        //how to get all token accounts for specific mint: https://spl.solana.com/token#finding-all-token-accounts-for-a-specific-mint
        //get it from the hardcoded token program and create a filter with the actual mint address
        //datasize:165 filter selects all token accounts, memcmp filter selects based on the mint address withing each token account
        return this._rpc
            .getProgramAccounts(token_1.TOKEN_PROGRAM_ADDRESS, {
            filters: [
                { dataSize: 165n },
                { memcmp: { offset: 0n, bytes: shareMint.toString(), encoding: 'base58' } },
            ],
            encoding: 'jsonParsed',
        })
            .send();
    }
    /**
     * Get all token accounts that hold shares for a specific vault; if you already have the vault state use it in the param so you don't have to fetch it again
     * @param vault
     * @returns an array of all holders tokenAccounts pubkeys and their account info
     */
    async getVaultTokenAccounts(vault) {
        const vaultState = await vault.getState();
        return this.getShareTokenAccounts(vaultState.sharesMint);
    }
    /**
     * Get all vault token holders
     * @param vault
     * @returns an array of all vault holders with their pubkeys and amounts
     */
    getVaultHolders = async (vault) => {
        await vault.getState();
        const tokenAccounts = await this.getVaultTokenAccounts(vault);
        const result = [];
        for (const tokenAccount of tokenAccounts) {
            const accountData = tokenAccount.account.data;
            result.push({
                holderPubkey: (0, kit_1.address)(accountData.parsed.info.owner),
                amount: new decimal_js_1.default(accountData.parsed.info.tokenAmount.uiAmountString),
            });
        }
        return result;
    };
    /**
     * Get all vaults for a given token
     * @param token - the token to get all vaults for
     * @returns an array of all vaults for the given token
     */
    async getAllVaultsForToken(token) {
        return this._vaultClient.getAllVaultsForToken(token);
    }
    /**
     * This will return an VaultHoldings object which contains the amount available (uninvested) in vault, total amount invested in reseves and a breakdown of the amount invested in each reserve
     * @param vault - the kamino vault to get available liquidity to withdraw for
     * @param slot - the slot for which to calculate the holdings
     * @param [vaultReserves] - a hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @param [currentSlot] - the latest confirmed slot. Optional. If provided the function will be  faster as it will not have to fetch the latest slot
     * @returns an VaultHoldings object
     */
    async getVaultHoldings(vault, slot, vaultReserves, currentSlot) {
        return this._vaultClient.getVaultHoldings(vault, slot, vaultReserves, currentSlot);
    }
    /**
     * This will return an VaultHoldingsWithUSDValue object which contains an holdings field representing the amount available (uninvested) in vault, total amount invested in reseves and a breakdown of the amount invested in each reserve and additional fields for the total USD value of the available and invested amounts
     * @param vault - the kamino vault to get available liquidity to withdraw for
     * @param price - the price of the token in the vault (e.g. USDC)
     * @param slot - the slot for which to calculate the holdings
     * @param [vaultReserves]
     * @param [currentSlot] - the latest confirmed slot. Optional. If provided the function will be  faster as it will not have to fetch the latest slot
     * @returns an VaultHoldingsWithUSDValue object with details about the tokens available and invested in the vault, denominated in tokens and USD
     */
    async getVaultHoldingsWithPrice(vault, price, slot, vaultReserves, currentSlot) {
        return this._vaultClient.getVaultHoldingsWithPrice(vault, price, slot, vaultReserves, currentSlot);
    }
    /**
     * This will return an VaultOverview object that encapsulates all the information about the vault, including the holdings, reserves details, theoretical APY, utilization ratio and total borrowed amount
     * @param vault - the kamino vault to get available liquidity to withdraw for
     * @param price - the price of the token in the vault (e.g. USDC)
     * @param slot - the slot for which to retrieve the vault overview
     * @param [vaultReserves] - hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @param [kaminoMarkets] - a list of all kamino markets. Optional. If provided the function will be significantly faster as it will not have to fetch the markets
     * @param [currentSlot] - the latest confirmed slot. Optional. If provided the function will be  faster as it will not have to fetch the latest slot
     * @param [tokensPrices] - a hashmap from a token pubkey to the price of the token in USD. Optional. If some tokens are not in the map, the function will fetch the price
     * @returns an VaultOverview object with details about the tokens available and invested in the vault, denominated in tokens and USD, along sie APYs
     */
    async getVaultOverview(vault, price, slot, vaultReserves, kaminoMarkets, farmsMap, farmsClient, globalConfig, currentSlot, tokensPrices) {
        return this._vaultClient.getVaultOverview(vault, price, slot, vaultReserves, kaminoMarkets, farmsMap, farmsClient, globalConfig, currentSlot, tokensPrices);
    }
    /**
     * Prints a vault in a human readable form
     * @param vaultPubkey - the address of the vault
     * @param slot - slot to use for vault calculations
     * @param [vaultState] - optional parameter to pass the vault state directly; this will save a network call
     * @returns - void; prints the vault to the console
     */
    async printVault(vaultPubkey, slot, vaultState) {
        return this._vaultClient.printVault(vaultPubkey, slot, vaultState);
    }
    /**
     * This will return an aggregation of the current state of the vault with all the invested amounts and the utilization ratio of the vault
     * @param vault - the kamino vault to get available liquidity to withdraw for
     * @param slot - current slot
     * @param vaultReserves - optional parameter; a hashmap from each reserve pubkey to the reserve state. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @returns an VaultReserveTotalBorrowedAndInvested object with the total invested amount, total borrowed amount and the utilization ratio of the vault
     */
    async getTotalBorrowedAndInvested(vault, slot, vaultReserves) {
        return this._vaultClient.getTotalBorrowedAndInvested(vault, slot, vaultReserves);
    }
    /**
     * This will return a map of the cumulative rewards issued for all the delegated farms, per token
     * @param [vaults] - the vaults to get the cumulative rewards for; if not provided, the function will get the cumulative rewards for all the vaults
     * @returns a map of the cumulative rewards issued for all the delegated farms, per token, in lamports
     */
    async getCumulativeDelegatedFarmsRewardsIssuedForAllVaults(vaults) {
        return this._vaultClient.getCumulativeDelegatedFarmsRewardsIssuedForAllVaults(vaults);
    }
    /**
     * This will return a map of the vault address and the delegated farm address for that vault
     * @returns a map of the vault address and the delegated farm address for that vault
     */
    async getVaultsWithDelegatedFarm() {
        return this._vaultClient.getVaultsWithDelegatedFarm();
    }
    /**
     * This will return an overview of each reserve that is part of the vault allocation
     * @param vault - the kamino vault to get available liquidity to withdraw for
     * @param slot - current slot
     * @param vaultReserves - optional parameter; a hashmap from each reserve pubkey to the reserve state. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @returns a hashmap from vault reserve pubkey to ReserveOverview object
     */
    async getVaultReservesDetails(vault, slot, vaultReserves) {
        return this._vaultClient.getVaultReservesDetails(vault, slot, vaultReserves);
    }
    /**
     * This will return the APY of the vault under the assumption that all the available tokens in the vault are all the time invested in the reserves as ratio; for percentage it needs multiplication by 100
     * @param vault - the kamino vault to get APY for
     * @param slot - current slot
     * @param [vaultReserves] - hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @returns a struct containing estimated gross APY and net APY (gross - vault fees) for the vault
     */
    async getVaultTheoreticalAPY(vault, slot, vaultReserves) {
        return this._vaultClient.getVaultTheoreticalAPY(vault, slot, vaultReserves);
    }
    /**
     * This will return the APY of the vault based on the current invested amounts; for percentage it needs multiplication by 100
     * @param vault - the kamino vault to get APY for
     * @param slot - current slot
     * @param [vaultReserves] - hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @returns a struct containing estimated gross APY and net APY (gross - vault fees) for the vault
     */
    async getVaultActualAPY(vault, slot, vaultReserves) {
        return this._vaultClient.getVaultActualAPY(vault, slot, vaultReserves);
    }
    /**
     * Retrive the total amount of interest earned by the vault since its inception, up to the last interaction with the vault on chain, including what was charged as fees
     * @param vaultState the kamino vault state to get total net yield for
     * @returns a struct containing a Decimal representing the net number of tokens earned by the vault since its inception and the timestamp of the last fee charge
     */
    async getVaultCumulativeInterest(vaultState) {
        return this._vaultClient.getVaultCumulativeInterest(vaultState);
    }
    /**
     * Simulate the current holdings of the vault and the earned interest
     * @param vaultState the kamino vault state to get simulated holdings and earnings for
     * @param [vaultReserves] - hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @param slot - latest slot
     * @param [previousTotalAUM] - the previous AUM of the vault to compute the earned interest relative to this value. Optional. If not provided the function will estimate the total AUM at the slot of the last state update on chain
     * @param [currentSlot] - the latest confirmed slot. Optional. If provided the function will be  faster as it will not have to fetch the latest slot
     * @returns a struct of simulated vault holdings and earned interest
     */
    async calculateSimulatedHoldingsWithInterest(vaultState, slot, vaultReserves, previousTotalAUM, currentSlot) {
        return this._vaultClient.calculateSimulatedHoldingsWithInterest(vaultState, slot, vaultReserves, previousTotalAUM, currentSlot);
    }
    /** Read the total holdings of a vault and the reserve weights and returns a map from each reserve to how many tokens should be deposited.
     * @param vaultState - the vault state to calculate the allocation for
     * @param slot - the slot for which to calculate the allocation
     * @param [vaultReserves] - a hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @param [currentSlot] - the latest confirmed slot. Optional. If provided the function will be  faster as it will not have to fetch the latest slot
     * @returns - a map from each reserve to how many tokens should be invested into
     */
    async getVaultComputedReservesAllocation(vaultState, slot, vaultReserves, currentSlot) {
        return this._vaultClient.getVaultComputedReservesAllocation(vaultState, slot, vaultReserves, currentSlot);
    }
    /**
     * Simulate the current holdings and compute the fees that would be charged
     * @param vaultState the kamino vault state to get simulated fees for
     * @param simulatedCurrentHoldingsWithInterest optional; the simulated holdings and interest earned by the vault
     * @param [currentTimestamp] the current date. Optional. If not provided it will fetch the current unix timestamp
     * @param [vaultReservesMap] - hashmap from each reserve pubkey to the reserve state. Optional. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @param slot - the slot at which to compute the fees
     * @param [previousNetAUM] - the previous AUM of the vault to compute the fees relative to this value. Optional. If not provided the function will estimate the total AUM at the slot of the last state update on chain
     * @param [currentSlot] - the latest confirmed slot. Optional. If provided the function will be  faster as it will not have to fetch the latest slot
     * @returns a struct of simulated management and interest fees
     */
    async calculateSimulatedFees(vaultState, slot, vaultReservesMap, simulatedCurrentHoldingsWithInterest, currentTimestamp, previousNetAUM, currentSlot) {
        return this._vaultClient.calculateSimulatedFees(vaultState, slot, vaultReservesMap, simulatedCurrentHoldingsWithInterest, currentTimestamp, previousNetAUM, currentSlot);
    }
    /**
     * This will compute the PDA that is used as delegatee in Farms program to compute the user state PDA for vault depositor investing in vault with reserve having a supply farm
     */
    computeUserFarmStateForUserInVault(farmsProgramId, vault, reserve, user) {
        return this._vaultClient.computeUserFarmStateDelegateePDAForUserInVault(farmsProgramId, reserve, vault, user);
    }
    /**
     * Read the APY of the farm built on top of the vault (farm in vaultState.vaultFarm)
     * @param vault - the vault to read the farm APY for
     * @param vaultTokenPrice - the price of the vault token in USD (e.g. 1.0 for USDC)
     * @param [farmsClient] - the farms client to use. Optional. If not provided, the function will create a new one
     * @param slot - the slot to read the farm APY for
     * @param [tokensPrices] - the prices of the tokens in USD. Optional. If not provided, the function will fetch the prices
     * @returns the APY of the farm built on top of the vault
     */
    async getVaultFarmRewardsAPY(vault, vaultTokenPrice, slot, vaultReservesMap, farmsClient, farmState, currentSlot, tokensPrices) {
        return this._vaultClient.getVaultRewardsAPY(vault, vaultTokenPrice, slot, vaultReservesMap, farmsClient, farmState, currentSlot, tokensPrices);
    }
    /**
     * Read the APY of the delegated farm providing incentives for vault depositors
     * @param vault - the vault to read the farm APY for
     * @param vaultTokenPrice - the price of the vault token in USD (e.g. 1.0 for USDC)
     * @param farmsClient - the farms client to use
     * @param slot - the slot to read the farm APY for
     * @param farmState - the farm state; pass null if not available (will return empty incentives)
     * @param [tokensPrices] - the prices of the tokens in USD. Optional. If not provided, the function will fetch the prices
     * @returns the APY of the delegated farm providing incentives for vault depositors
     */
    async getVaultDelegatedFarmRewardsAPY(vault, vaultTokenPrice, slot, vaultReservesMap, farmsClient, farmState, currentSlot, tokensPrices) {
        return this._vaultClient.getVaultDelegatedFarmRewardsAPY(vault, vaultTokenPrice, slot, vaultReservesMap, farmsClient, farmState, currentSlot, tokensPrices);
    }
    /**
     * This will read the pending rewards for a user in the vault farm, the reserves farms of the vault and the delegated vault farm
     * @param user - the user address
     * @param vault - the vault
     * @param [vaultReservesMap] - the vault reserves map to get the reserves for; if not provided, the function will fetch the reserves
     * @returns a struct containing the pending rewards in the vault farm, the reserves farms of the vault and the delegated vault farm, and the total pending rewards in lamports
     */
    async getAllPendingRewardsForUserInVault(user, vault, vaultReservesMap) {
        return this._vaultClient.getAllPendingRewardsForUserInVault(user, vault, vaultReservesMap);
    }
    /**
     * This function will return the instructions to claim the rewards for the farm of a vault, the delegated farm of the vault and the reserves farms of the vault
     * @param user - the user to claim the rewards
     * @param vault - the vault
     * @param [vaultReservesMap] - the vault reserves map to get the reserves for; if not provided, the function will fetch the reserves
     * @returns the instructions to claim the rewards for the farm of the vault, the delegated farm of the vault and the reserves farms of the vault
     */
    async getClaimAllRewardsForVaultIxs(user, vault, vaultReservesMap) {
        return this._vaultClient.getClaimAllRewardsForVaultIxs(user, vault, vaultReservesMap);
    }
    /**
     * This function will return the instructions to claim the rewards for the farm of a vault
     * @param user - the user to claim the rewards
     * @param vault - the vault
     * @returns the instructions to claim the rewards for the farm of the vault
     */
    async getClaimVaultFarmRewardsIxs(user, vault) {
        return this._vaultClient.getClaimVaultFarmRewardsIxs(user, vault);
    }
    /**
     * This function will return the instructions to claim the rewards for the delegated farm of a vault
     * @param user - the user to claim the rewards
     * @param vault - the vault
     * @returns the instructions to claim the rewards for the delegated farm of the vault
     */
    async getClaimVaultDelegatedFarmRewardsIxs(user, vault) {
        return this._vaultClient.getClaimVaultDelegatedFarmRewardsIxs(user, vault);
    }
    /**
     * This function will return the instructions to claim the rewards for the reserves farms of a vault
     * @param user - the user to claim the rewards
     * @param vault - the vault
     * @param [vaultReservesMap] - the vault reserves map to get the reserves for; if not provided, the function will fetch the reserves
     * @returns the instructions to claim the rewards for the reserves farms of the vault
     */
    async getClaimVaultReservesFarmsRewardsIxs(user, vault, vaultReservesMap) {
        return this._vaultClient.getClaimVaultReservesFarmsRewardsIxs(user, vault, vaultReservesMap);
    }
    /**
     * Get all the token mints of the vault, vault farm rewards and the allocation  rewards
     * @param vaults - the vaults to get the token mints for
     * @param [vaultReservesMap] - the vault reserves map to get the reserves for; if not provided, the function will fetch the reserves
     * @param farmsMap - the farms map to get the farms for
     * @returns a map of token mints (keys) and number of decimals (values)
     */
    async getAllVaultsTokenMintsIncludingRewards(vaults, vaultReservesMap, farmsMap) {
        return this._vaultClient.getAllVaultsTokenMintsIncludingRewards(vaults, vaultReservesMap, farmsMap);
    }
    /**
     * This will return the APY of the reserve farms (debt and supply)
     * @param reserve - the reserve to get the farms APY for
     * @param reserveTokenPrice - the price of the reserve token in USD (e.g. 1.0 for USDC)
     * @param [farmsClient] - the farms client to use. Optional. If not provided, the function will create a new one
     * @param slot - the slot to read the farm APY for
     * @param [reserveState] - the reserve state. Optional. If not provided, the function will fetch the reserve state
     * @returns the APY of the farm built on top of the reserve
     */
    async getReserveFarmRewardsAPY(reserve, reserveTokenPrice, slot, farmsClient, reserveState) {
        return (0, farmUtils_1.getReserveFarmRewardsAPY)(this._rpc, this.recentSlotDurationMs, reserve, reserveTokenPrice, this._kaminoLendProgramId, farmsClient ? farmsClient : new dist_1.Farms(this._rpc, this._farmsProgramId), slot, reserveState);
    }
    /**
     * This will load the onchain state for all the reserves that the vault has allocations for
     * @param vaultState - the vault state to load reserves for
     * @returns a hashmap from each reserve pubkey to the reserve state
     */
    async loadVaultReserves(vaultState) {
        return this._vaultClient.loadVaultReserves(vaultState);
    }
    /**
     * This will load the onchain state for all the reserves that the vaults have allocations for, deduplicating the reserves
     * @param vaults - the vault states to load reserves for
     * @param oracleAccounts (optional) all reserve oracle accounts, if not supplied will make an additional rpc call to fetch these accounts
     * @returns a hashmap from each reserve pubkey to the reserve state
     */
    async loadVaultsReserves(vaults, oracleAccounts) {
        return this._vaultClient.loadVaultsReserves(vaults, oracleAccounts);
    }
    /**
     * This will load the onchain state for all the reserves that the vault has allocations for
     * @param vault - the vault state to load reserves for
     * @returns a hashmap from each reserve pubkey to the reserve state
     */
    getVaultReserves(vault) {
        return this._vaultClient.getVaultReserves(vault);
    }
    /**
     * Batch-load all farm states referenced by the given vault states (vault farm, FLC farm, delegated farms).
     * Cache the returned map and pass individual entries to methods like getVaultRewardsAPY or getVaultFlcFarmStats.
     * @param vaultStates - vault states to collect farm addresses from
     * @returns a map from farm address to FarmState
     */
    async loadVaultFarmStates(vaultStates, vaultReservesMap) {
        return this._vaultClient.loadVaultFarmStates(vaultStates, vaultReservesMap);
    }
    /**
     * Load the FarmState for a single vault. Returns null if the vault has no farm.
     * Cache and pass the result to depositIxs / withdrawIxs / etc. to avoid per-call FarmState.fetch().
     * @param vaultState - the vault state
     * @returns FarmState if the vault has a farm, null otherwise
     */
    async loadVaultFarmState(vaultState) {
        return this._vaultClient.loadVaultFarmState(vaultState);
    }
    /**
     * Load KaminoMarket instances for all unique lending markets referenced by the given reserves.
     * Cache the returned map and pass it to getVaultCollaterals / getVaultOverview.
     * @param vaultReservesMap - the reserves map (as returned by loadVaultReserves / loadVaultsReserves)
     * @returns a map from lending market address to KaminoMarket
     */
    async loadKaminoMarketsForVaultReserves(vaultReservesMap) {
        return this._vaultClient.loadKaminoMarketsForVaultReserves(vaultReservesMap);
    }
    /**
     * Pre-load the KVault global config. Can be called once and the result passed to methods like getVaultOverview and getVaultWithdrawPenalties.
     * @returns the KVaultGlobalConfig state
     */
    async loadKVaultGlobalConfig() {
        return this._vaultClient.loadKVaultGlobalConfig();
    }
    /**
     * This will retrieve all the tokens that can be use as collateral by the users who borrow the token in the vault alongside details about the min and max loan to value ratio
     * @param vaultState - the vault state to load reserves for
     *
     * @param slot - current slot
     * @param vaultReservesMap - cached vault reserves map
     * @param kaminoMarkets - cached kamino markets
     * @returns a hashmap from each reserve pubkey to the market overview of the collaterals that can be used and the min and max loan to value ratio in that market
     */
    async getVaultCollaterals(vaultState, slot, vaultReservesMap, kaminoMarkets) {
        return this._vaultClient.getVaultCollaterals(vaultState, slot, vaultReservesMap, kaminoMarkets);
    }
    /**
     * This will trigger invest by balancing, based on weights, the reserve allocations of the vault. It can either withdraw or deposit into reserves to balance them. This is a function that should be cranked
     * @param payer
     * @param kaminoVault - vault to invest from
     * @param slot - current slot used for invest calculations
     * @param skipComputationChecks - if true, the function will skip the computation checks and will invest all the reserves
     * @returns - an array of invest instructions for each invest action required for the vault reserves
     */
    async investAllReservesIxs(payer, kaminoVault, slot, skipComputationChecks = false) {
        return this._vaultClient.investAllReservesIxs(payer, kaminoVault, slot, skipComputationChecks);
    }
    /**
     * This will trigger invest by balancing, based on weights, the reserve allocation of the vault. It can either withdraw or deposit into the given reserve to balance it
     * @param payer wallet pubkey - the instruction is permissionless and does not require the vault admin, due to rounding between cTokens and the underlying, the payer may have to contribute 1 or more lamports of the underlying from their token account
     * @param kaminoVault - vault to invest from
     * @param reserveWithAddress - reserve to invest into or disinvest from
     * @param [vaultReservesMap] - optional parameter; a hashmap from each reserve pubkey to the reserve state. If provided the function will be significantly faster as it will not have to fetch the reserves
     * @param [createAtaIfNeeded] - if true, the function will create an ATA for the payer if needed
     * @returns - an array of invest instructions for each invest action required for the vault reserves
     */
    async investSingleReserveIxs(payer, kaminoVault, reserveWithAddress, vaultReservesMap, createAtaIfNeeded = true) {
        return this._vaultClient.investSingleReserveIxs(payer, kaminoVault, reserveWithAddress, vaultReservesMap, createAtaIfNeeded);
    }
    /**
     * This will return the a map between reserve pubkey and the pct of the vault invested amount in each reserve
     * @param vaultState - the kamino vault to get reserves distribution for
     * @returns a map between reserve pubkey and the allocation pct for the reserve
     */
    getAllocationsDistribuionPct(vaultState) {
        return this._vaultClient.getAllocationsDistribuionPct(vaultState);
    }
    /**
     * This will return the a map between reserve pubkey and the allocation overview for the reserve
     * @param vaultState - the kamino vault to get reserves allocation overview for
     * @returns a map between reserve pubkey and the allocation overview for the reserve
     */
    getVaultAllocations(vaultState) {
        return this._vaultClient.getVaultAllocations(vaultState);
    }
    /**
     * This will return the amount of token invested from the vault into the given reserve
     * @param vaultState - the kamino vault to get invested amount in reserve for
     * @param slot - current slot
     * @param reserve - the reserve state to get vault invested amount in
     * @returns vault amount supplied in reserve in decimal
     */
    getSuppliedInReserve(vaultState, slot, reserve) {
        return this._vaultClient.getSuppliedInReserve(vaultState, slot, reserve);
    }
    /**
     * This returns an array of scope oracle configs to be used to set the scope price and twap oracles for a reserve
     * @param market kamino market
     * @param cluster - cluster to fetch from, this should be left unchanged unless working on devnet or locally
     * @returns - a map with keys as scope OraclePrices pubkeys and values of scope oracle configs
     */
    async getScopeOracleConfigs(market, cluster = 'mainnet-beta') {
        const scopeOracleConfigs = new Map();
        const scope = new scope_sdk_1.Scope(cluster, this._rpc);
        const configs = (await scope.getAllConfigurations()).filter(([_, config]) => market.scopeFeeds.has(config.oraclePrices));
        if (!configs || configs.length === 0) {
            return scopeOracleConfigs;
        }
        const configOracleMappings = await accounts_2.OracleMappings.fetchMultiple(this._rpc, configs.map(([_, config]) => config.oracleMappings), scope.config.programId);
        const configTokenMetadatas = await TokenMetadatas_1.TokenMetadatas.fetchMultiple(this._rpc, configs.map(([_, config]) => config.tokensMetadata), scope.config.programId);
        const decoder = new TextDecoder('utf-8');
        for (let i = 0; i < configs.length; i++) {
            const [configPubkey, config] = configs[i];
            const oracleMappings = configOracleMappings[i];
            const tokenMetadatas = configTokenMetadatas[i];
            if (!oracleMappings) {
                throw new Error(`OracleMappings account not found for config ${configPubkey}`);
            }
            if (!tokenMetadatas) {
                throw new Error(`TokenMetadatas account not found for config ${configPubkey}`);
            }
            for (let j = 0; j < oracleMappings.priceInfoAccounts.length; j++) {
                if (oracleMappings.priceInfoAccounts[j] !== lib_1.DEFAULT_PUBLIC_KEY) {
                    const name = decoder.decode(Uint8Array.from(tokenMetadatas.metadatasArray[j].name)).replace(/\0/g, '');
                    const oracleType = (0, lib_1.parseOracleType)(oracleMappings.priceTypes[j]);
                    (0, lib_1.setOrAppend)(scopeOracleConfigs, config.oraclePrices, {
                        name: name,
                        oracleType: oracleType,
                        oracleId: j,
                        oracleAccount: oracleMappings.priceInfoAccounts[j],
                        twapEnabled: oracleMappings.twapEnabled[j] === 1,
                        twapSourceId: oracleMappings.twapSource[j],
                        max_age: tokenMetadatas.metadatasArray[j].maxAgePriceSlots.toNumber(),
                    });
                }
            }
        }
        return scopeOracleConfigs;
    }
    /**
     * This retruns an array of instructions to be used to update the lending market configurations
     * @param lendingMarketOwner - market admin
     * @param marketWithAddress - the market address and market state object
     * @param newMarket - the lending market state with the new configuration - to be build we new config options from the previous state
     * @returns - an array of instructions
     */
    updateLendingMarketIxs(lendingMarketOwner, marketWithAddress, newMarket) {
        return parseForChangesMarketConfigAndGetIxs(lendingMarketOwner, marketWithAddress, newMarket, this._kaminoLendProgramId);
    }
    /**
     * This retruns an array of instructions to be used to update the pending lending market admin; if the admin is the same the list will be empty otherwise it will have an instruction to update the cached (pending) admin
     * @param currentAdmin - current lending market owner
     * @param marketWithAddress - the market address and market state object
     * @param newAdmin - the new admin
     * @returns - an array of instructions
     */
    updatePendingLendingMarketAdminIx(currentAdmin, marketWithAddress, newAdmin) {
        const newMarket = new lib_1.LendingMarket({ ...marketWithAddress.state, lendingMarketOwnerCached: newAdmin });
        return this.updateLendingMarketIxs(currentAdmin, marketWithAddress, newMarket);
    }
    /**
     * This returns an instruction to be used to update the market owner. This can only be executed by the current lendingMarketOwnerCached
     * @param marketWithAddress - the market address and market state object
     * @param lendingMarketOwnerCached - lendingMarketOwnerCached signer - a noop signer suitable for multisigs is used if not provided
     * @returns - an instruction for the new owner
     */
    updateLendingMarketOwnerIxs(marketWithAddress, lendingMarketOwnerCached = (0, signer_1.noopSigner)(marketWithAddress.state.lendingMarketOwnerCached)) {
        const accounts = {
            lendingMarketOwnerCached,
            lendingMarket: marketWithAddress.address,
        };
        return (0, lib_1.updateLendingMarketOwner)(accounts, undefined, this._kaminoLendProgramId);
    }
    /**
     * Check if a vault has all the needed criteria to be released
     * @param vault - the vault to check
     * @returns the release check result with errors, warnings, and success flag
     */
    async checkVaultReleaseStatus(vault) {
        return this._vaultClient.checkVaultReleaseStatus(vault);
    }
    /**
     * This will check if the given wallet is a squads multisig
     * @param wallet - the wallet to check
     * @returns true if the wallet is a squads multisig, false otherwise
     */
    static async walletIsSquadsMultisig(wallet) {
        return (0, multisig_1.walletIsSquadsMultisig)(wallet);
    }
    /**
     * This will get the wallet type, admins number and threshold for the given wallet
     * @param wallet - the wallet to get the wallet info for
     * @returns the wallet type, admins number and threshold
     */
    static async getWalletType(wallet) {
        return KaminoManager.getWalletInfo(wallet);
    }
    /**
     * This will get the wallet type, admins number and threshold for the given authority
     * @param rpc - the rpc to use
     * @param address - the address to get the wallet info for
     * @returns the wallet type, admins number and threshold
     */
    static async getMarketOrVaultAdminInfo(rpc, address) {
        try {
            // Try to fetch vault state first
            const vaultState = await accounts_1.VaultState.fetch(rpc, address);
            if (!vaultState) {
                throw new Error('Vault not found');
            }
            return await KaminoManager.getWalletInfo(vaultState.vaultAdminAuthority);
        }
        catch (error) {
            // If vault not found, try to fetch market state
            const market = await lib_1.LendingMarket.fetch(rpc, address);
            if (!market) {
                return undefined;
            }
            return await KaminoManager.getWalletInfo(market.lendingMarketOwner);
        }
    }
    /**
     * Helper method to get wallet information for a given authority
     */
    static async getWalletInfo(authority) {
        const isSquadsMultisig = await KaminoManager.walletIsSquadsMultisig(authority);
        let walletAdminsNumber = 1;
        let walletThreshold = 1;
        if (isSquadsMultisig) {
            const { adminsNumber, threshold } = await (0, multisig_1.getSquadsMultisigAdminsAndThreshold)(authority);
            walletAdminsNumber = adminsNumber;
            walletThreshold = threshold;
        }
        return {
            walletType: isSquadsMultisig ? 'squadsMultisig' : 'simpleWallet',
            walletAdminsNumber,
            walletThreshold,
        };
    }
} // KaminoManager
exports.KaminoManager = KaminoManager;
exports.MARKET_UPDATER = new configItems_1.ConfigUpdater(types_1.UpdateLendingMarketMode.fromDecoded, lib_1.LendingMarket, (config) => ({
    [types_1.UpdateLendingMarketMode.UpdateOwner.kind]: config.lendingMarketOwnerCached,
    [types_1.UpdateLendingMarketMode.UpdateImmutableFlag.kind]: config.immutable,
    [types_1.UpdateLendingMarketMode.UpdateEmergencyMode.kind]: config.emergencyMode,
    [types_1.UpdateLendingMarketMode.UpdateLiquidationCloseFactor.kind]: config.liquidationMaxDebtCloseFactorPct,
    [types_1.UpdateLendingMarketMode.UpdateLiquidationMaxValue.kind]: config.maxLiquidatableDebtMarketValueAtOnce,
    [types_1.UpdateLendingMarketMode.DeprecatedUpdateGlobalUnhealthyBorrow.kind]: [], // deprecated
    [types_1.UpdateLendingMarketMode.UpdateGlobalAllowedBorrow.kind]: config.globalAllowedBorrowValue,
    [types_1.UpdateLendingMarketMode.UpdateEmergencyCouncil.kind]: config.emergencyCouncil,
    [types_1.UpdateLendingMarketMode.UpdateMinFullLiquidationThreshold.kind]: config.minFullLiquidationValueThreshold,
    [types_1.UpdateLendingMarketMode.UpdateInsolvencyRiskLtv.kind]: config.insolvencyRiskUnhealthyLtvPct,
    [types_1.UpdateLendingMarketMode.UpdateElevationGroup.kind]: (0, configItems_1.arrayElementConfigItems)(config.elevationGroups),
    [types_1.UpdateLendingMarketMode.UpdateReferralFeeBps.kind]: config.referralFeeBps,
    [types_1.UpdateLendingMarketMode.DeprecatedUpdateMultiplierPoints.kind]: [], // deprecated
    [types_1.UpdateLendingMarketMode.UpdatePriceRefreshTriggerToMaxAgePct.kind]: config.priceRefreshTriggerToMaxAgePct,
    [types_1.UpdateLendingMarketMode.UpdateAutodeleverageEnabled.kind]: config.autodeleverageEnabled,
    [types_1.UpdateLendingMarketMode.UpdateBorrowingDisabled.kind]: config.borrowDisabled,
    [types_1.UpdateLendingMarketMode.UpdateMinNetValueObligationPostAction.kind]: config.minNetValueInObligationSf,
    [types_1.UpdateLendingMarketMode.UpdateMinValueLtvSkipPriorityLiqCheck.kind]: config.minValueSkipLiquidationLtvChecks,
    [types_1.UpdateLendingMarketMode.UpdateMinValueBfSkipPriorityLiqCheck.kind]: config.minValueSkipLiquidationBfChecks,
    [types_1.UpdateLendingMarketMode.UpdatePaddingFields.kind]: [], // we do not update padding this way
    [types_1.UpdateLendingMarketMode.UpdateName.kind]: config.name,
    [types_1.UpdateLendingMarketMode.UpdateIndividualAutodeleverageMarginCallPeriodSecs.kind]: config.individualAutodeleverageMarginCallPeriodSecs,
    [types_1.UpdateLendingMarketMode.UpdateInitialDepositAmount.kind]: config.minInitialDepositAmount,
    [types_1.UpdateLendingMarketMode.UpdateObligationOrderCreationEnabled.kind]: config.obligationOrderCreationEnabled,
    [types_1.UpdateLendingMarketMode.UpdateObligationOrderExecutionEnabled.kind]: config.obligationOrderExecutionEnabled,
    [types_1.UpdateLendingMarketMode.UpdateProposerAuthority.kind]: config.proposerAuthority,
    [types_1.UpdateLendingMarketMode.UpdatePriceTriggeredLiquidationDisabled.kind]: config.priceTriggeredLiquidationDisabled,
    [types_1.UpdateLendingMarketMode.UpdateMatureReserveDebtLiquidationEnabled.kind]: config.matureReserveDebtLiquidationEnabled,
    [types_1.UpdateLendingMarketMode.UpdateObligationBorrowDebtTermLiquidationEnabled.kind]: config.obligationBorrowDebtTermLiquidationEnabled,
    [types_1.UpdateLendingMarketMode.UpdateBorrowOrderCreationEnabled.kind]: config.borrowOrderCreationEnabled,
    [types_1.UpdateLendingMarketMode.UpdateBorrowOrderExecutionEnabled.kind]: config.borrowOrderExecutionEnabled,
    [types_1.UpdateLendingMarketMode.UpdateMinBorrowOrderFillValue.kind]: config.minBorrowOrderFillValue,
    [types_1.UpdateLendingMarketMode.UpdateWithdrawTicketIssuanceEnabled.kind]: config.withdrawTicketIssuanceEnabled,
    [types_1.UpdateLendingMarketMode.UpdateWithdrawTicketRedemptionEnabled.kind]: config.withdrawTicketRedemptionEnabled,
    [types_1.UpdateLendingMarketMode.UpdateMinWithdrawQueuedLiquidityValue.kind]: config.minWithdrawQueuedLiquidityValue,
    [types_1.UpdateLendingMarketMode.UpdateFixedTermRolloverWindowDurationSeconds.kind]: config.fixedTermRolloverWindowDurationSeconds,
    [types_1.UpdateLendingMarketMode.UpdateOpenTermRolloverWindowDurationSeconds.kind]: config.openTermRolloverWindowDurationSeconds,
    [types_1.UpdateLendingMarketMode.UpdateObligationBorrowRolloverConfigurationEnabled.kind]: config.obligationBorrowRolloverConfigurationEnabled,
    [types_1.UpdateLendingMarketMode.UpdateTermBasedFullLiquidationDurationSecs.kind]: config.termBasedFullLiquidationDurationSecs,
    [types_1.UpdateLendingMarketMode.UpdateObligationBorrowMigrationToFixedExecutionEnabled.kind]: config.obligationBorrowMigrationToFixedExecutionEnabled,
    [types_1.UpdateLendingMarketMode.UpdateMinPartialRolloverValue.kind]: config.minPartialRolloverValue,
    [types_1.UpdateLendingMarketMode.UpdateWithdrawTicketCancellationEnabled.kind]: config.withdrawTicketCancellationEnabled,
    [types_1.UpdateLendingMarketMode.UpdatePermissioningAuthority.kind]: config.permissioningAuthority,
    [types_1.UpdateLendingMarketMode.UpdatePermissionedOps.kind]: config.permissionedOps,
    [types_1.UpdateLendingMarketMode.DeprecatedUpdateReserveRewardsMaxAprPct.kind]: [], // deprecated
    [types_1.UpdateLendingMarketMode.UpdateReserveRewardsMaxAprBps.kind]: config.reserveRewardsMaxAprBps,
}));
const PRIORITY_ORDERED_MARKET_UPDATER = new configItems_1.PriorityOrderedConfigUpdater(exports.MARKET_UPDATER);
// Lowest priority gets updated first
function marketUpdatePriorityOf(mode) {
    switch (mode.discriminator) {
        // MinBorrowOrderFillValue must be set before execution can be enabled
        case types_1.UpdateLendingMarketMode.UpdateMinBorrowOrderFillValue.discriminator:
            return 0;
        case types_1.UpdateLendingMarketMode.UpdateBorrowOrderExecutionEnabled.discriminator:
            return 1;
        default:
            return 10;
    }
}
function parseForChangesMarketConfigAndGetIxs(lendingMarketOwner, marketWithAddress, newMarket, programId) {
    const encodedMarketUpdates = PRIORITY_ORDERED_MARKET_UPDATER.encodeAllUpdates(marketWithAddress.state, newMarket, marketUpdatePriorityOf);
    return encodedMarketUpdates.map((encodedMarketUpdate) => updateMarketConfigIx(lendingMarketOwner, marketWithAddress, encodedMarketUpdate.mode, encodedMarketUpdate.value, programId));
}
function updateMarketConfigIx(lendingMarketOwner, marketWithAddress, mode, value, programId) {
    const accounts = {
        signer: lendingMarketOwner,
        lendingMarket: marketWithAddress.address,
    };
    const args = {
        mode: new bn_js_1.default(mode.discriminator),
        // NOTE: the Market's update handler expects a `[u8; 72]` (contrary to e.g. the Reserve's update handler accepting
        // `Vec<u8>`). Hence, we need to add explicit padding here:
        value: [...value, ...Array(72 - value.length).fill(0)],
    };
    const ix = (0, lib_1.updateLendingMarket)(args, accounts, undefined, programId);
    return ix;
}
//# sourceMappingURL=manager.js.map