UNPKG

@kamino-finance/klend-sdk

Version:

Typescript SDK for interacting with the Kamino Lending (klend) protocol

791 lines (790 loc) 60.4 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MARKET_UPDATER = exports.KaminoManager = void 0; const web3_js_1 = require("@solana/web3.js"); const vault_1 = require("./vault"); const lib_1 = require("../lib"); const programId_1 = require("../idl_codegen/programId"); const scope_sdk_1 = require("@kamino-finance/scope-sdk"); const bn_js_1 = __importDefault(require("bn.js")); const types_1 = require("../idl_codegen/types"); const decimal_js_1 = __importDefault(require("decimal.js")); const anchor = __importStar(require("@coral-xyz/anchor")); const accounts_1 = require("../idl_codegen_kamino_vault/accounts"); const spl_token_1 = require("@solana/spl-token"); const bs58_1 = __importDefault(require("bs58")); const rpc_1 = require("../utils/rpc"); const types_2 = require("../idl_codegen_kamino_vault/types"); const sbv2_lite_1 = __importDefault(require("@switchboard-xyz/sbv2-lite")); const multisig_1 = require("../utils/multisig"); const vault_2 = require("../utils/vault"); const configItems_1 = require("./configItems"); /** * 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 { _connection; _kaminoVaultProgramId; _kaminoLendProgramId; _vaultClient; recentSlotDurationMs; constructor(connection, recentSlotDurationMs, kaminoLendProgramId, kaminoVaultProgramId) { this._connection = connection; this.recentSlotDurationMs = recentSlotDurationMs; this._kaminoVaultProgramId = kaminoVaultProgramId ? kaminoVaultProgramId : vault_1.kaminoVaultId; this._kaminoLendProgramId = kaminoLendProgramId ? kaminoLendProgramId : programId_1.PROGRAM_ID; this._vaultClient = new vault_1.KaminoVaultClient(connection, this.recentSlotDurationMs, this._kaminoVaultProgramId, this._kaminoLendProgramId); } getConnection() { return this._connection; } 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 = web3_js_1.Keypair.generate(); const size = lib_1.LendingMarket.layout.span + 8; const [lendingMarketAuthority, _] = (0, lib_1.lendingMarketAuthPda)(marketAccount.publicKey, this._kaminoLendProgramId); const createMarketIxs = []; createMarketIxs.push(web3_js_1.SystemProgram.createAccount({ fromPubkey: params.admin, newAccountPubkey: marketAccount.publicKey, lamports: await this._connection.getMinimumBalanceForRentExemption(size), space: size, programId: this._kaminoLendProgramId, })); const accounts = { lendingMarketOwner: params.admin, lendingMarket: marketAccount.publicKey, lendingMarketAuthority: lendingMarketAuthority, systemProgram: web3_js_1.SystemProgram.programId, rent: web3_js_1.SYSVAR_RENT_PUBKEY, }; const args = { quoteCurrency: Array(32).fill(0), }; createMarketIxs.push((0, lib_1.initLendingMarket)(args, accounts, 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._connection, params.marketAddress, this._kaminoLendProgramId); if (!market) { throw new Error('Market not found'); } const marketWithAddress = { address: params.marketAddress, state: market }; const reserveAccount = web3_js_1.Keypair.generate(); const createReserveInstructions = await (0, lib_1.createReserveIxs)(this._connection, params.admin, params.adminLiquiditySource, params.marketAddress, params.assetConfig.mint, reserveAccount.publicKey, this._kaminoLendProgramId); const updateReserveInstructions = await this.updateReserveIxs(marketWithAddress, reserveAccount.publicKey, params.assetConfig.getReserveConfig(), undefined, false); const txnIxs = []; txnIxs.push(createReserveInstructions); txnIxs.push(updateReserveInstructions); return { reserve: reserveAccount, txnIxs }; } /** * 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) { return this._vaultClient.createVaultIxs(vaultConfig); } /** * This method creates an instruction to set the shares metadata for a vault * @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(vault, tokenName, extraName) { const vaultState = await vault.getState(this._connection); return this._vaultClient.getSetSharesMetadataIx(this._connection, vaultState.vaultAdminAuthority, vault.address, vaultState.sharesMint, vaultState.baseVaultAuthority, tokenName, extraName); } /** * 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 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 * @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) { return this._vaultClient.removeReserveFromAllocationIx(vault, reserve); } /** * 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 payer - the payer of the transaction. 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 withdrawEverythingAndBlockInvestReserve(vault, reserve, payer) { return this._vaultClient.withdrawEverythingAndBlockInvestReserve(vault, reserve, payer); } /** * 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 [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, vaultReservesMap, payer) { return this._vaultClient.withdrawEverythingFromAllReservesAndBlockInvest(vault, 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 * @returns - the reserve config */ async getReserveConfig(reserve) { const reserveState = await lib_1.Reserve.fetch(this._connection, reserve); if (!reserveState) { throw new Error('Reserve not found'); } return reserveState.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 market - lending market which owns the reserve * @param reserve - reserve which to be updated * @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(market, reserve, 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: scopeOracleConfig.scopePriceConfigAddress, 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), }, }); return this.updateReserveIxs(market, reserve.address, newReserveConfig, reserve.state); } /** * This function updates the given reserve with a new config. It can either update the entire reserve config or just update fields which differ between given reserve and existing reserve * @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 updateEntireConfig - when set to false, it will only update fields that are different between @param config and reserveState.config, set to true it will always update entire reserve config. An entire reserveConfig update might be too large for a multisig transaction * @returns - an array of multiple update ixs. If there are many fields that are being updated without the updateEntireConfig=true, multiple transactions might be required to fit all ixs. */ async updateReserveIxs(marketWithAddress, reserve, config, reserveStateOverride, updateEntireConfig = false) { const reserveState = reserveStateOverride ? reserveStateOverride : (await lib_1.Reserve.fetch(this._connection, reserve, this._kaminoLendProgramId)); const ixs = []; if (!reserveState || updateEntireConfig) { ixs.push((0, lib_1.updateEntireReserveConfigIx)(marketWithAddress.state.lendingMarketOwner, marketWithAddress.address, reserve, config, this._kaminoLendProgramId)); } else { ixs.push(...(0, lib_1.parseForChangesReserveConfigAndGetIxs)(marketWithAddress, reserveState, reserve, config, this._kaminoLendProgramId)); } 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] - optional parameter; 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 [farmState] - the state of the vault farm, if the vault has a farm. Optional. If not provided, it will be fetched * @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) { return this._vaultClient.depositIxs(user, vault, tokenAmount, vaultReservesMap, farmState); } /** * This function creates instructions to stake the shares in the vault farm if the vault has a 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] - the state of the vault farm, if the vault has a farm. Optional. If not provided, it will be fetched * @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 * @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, signer) { if (typeof mode === 'string') { const field = types_2.VaultConfigField.fromDecoded({ [mode]: '' }); return this._vaultClient.updateVaultConfigIxs(vault, field, value, signer); } return this._vaultClient.updateVaultConfigIxs(vault, mode, value, signer); } /** 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 */ async setVaultFarmIxs(vault, farm, errorOnOverride = true) { return this._vaultClient.setVaultFarmIxs(vault, farm, errorOnOverride); } /** * 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 * @returns - an instruction to accept the ownership of the vault and a list of instructions to update the lookup table */ async acceptVaultOwnershipIxs(vault) { return this._vaultClient.acceptVaultOwnershipIxs(vault); } /** * 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 * @returns - an instruction to give up the specified pending fees */ async giveUpPendingFeesIx(vault, maxAmountToGiveUp) { return this._vaultClient.giveUpPendingFeesIx(vault, maxAmountToGiveUp); } /** * 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] - 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 [farmState] - the state of the vault farm, if the vault has a farm. Optional. If not provided, it will be fetched * @returns an array of instructions to create missing ATAs if needed and the withdraw instructions */ async withdrawFromVaultIxs(user, vault, shareAmount, slot, vaultReservesMap, farmState) { return this._vaultClient.withdrawIxs(user, vault, shareAmount, slot, vaultReservesMap, farmState); } /** * 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 [vaultReservesMap] - 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 * @returns - list of instructions to withdraw all pending fees, including the ATA creation instructions if needed */ async withdrawPendingFeesIxs(vault, slot) { return this._vaultClient.withdrawPendingFeesIxs(vault, slot); } /** * This method inserts the missing keys from the provided keys into an existent lookup table * @param payer - payer wallet pubkey * @param lookupTable - 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 this._vaultClient.insertIntoLookupTableIxs(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 vault the vault to sync and set the LUT for if needed * @param vaultReserves optional; the state of the reserves in the vault allocation * @param [vaultReservesMap] - optional parameter; 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 * @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(vault, vaultReserves) { return this._vaultClient.syncVaultLookupTableIxs(vault, 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. Optional. If not provided, the function will fetch the current slot * @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. Optional. If not provided, the function will fetch the current slot * @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 (staked in vault farm if the vault has a farm and unstaked) 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 vault - 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 = programId_1.PROGRAM_ID) { // Get all lending markets const marketGenerator = (0, lib_1.getAllLendingMarketAccounts)(this.getConnection(), programId); const slotDuration = await (0, lib_1.getMedianSlotDurationInMsFromLastEpochs)(); const lendingMarketPairs = []; for await (const pair of marketGenerator) { lendingMarketPairs.push(pair); } // Get all reserves const allReserveAccounts = await (0, lib_1.getAllReserveAccounts)(this.getConnection()); const reservePairs = []; for await (const pair of allReserveAccounts) { reservePairs.push(pair); } const allReserves = reservePairs.map(([, reserve]) => reserve); // Get all oracle accounts const allOracleAccounts = await (0, lib_1.getAllOracleAccounts)(this.getConnection(), allReserves); const switchboardV2 = await sbv2_lite_1.default.loadMainnet(this.getConnection()); // Group reserves by market const marketToReserve = new lib_1.PubkeyHashMap(); for (const [reserveAddress, reserveState, buffer] of reservePairs) { const marketAddress = reserveState.lendingMarket; if (!marketToReserve.has(marketAddress)) { marketToReserve.set(marketAddress, [[reserveAddress, reserveState, buffer]]); } else { marketToReserve.get(marketAddress)?.push([reserveAddress, reserveState, buffer]); } } const combinedMarkets = lendingMarketPairs.map(([pubkey, market]) => { const reserves = marketToReserve.get(pubkey); const reservesByAddress = new lib_1.PubkeyHashMap(); if (!reserves) { console.log(`Market ${pubkey.toString()} ${(0, lib_1.parseTokenSymbol)(market.name)} has no reserves`); } else { const allBuffers = reserves.map(([, , account]) => account); const allReserves = reserves.map(([, reserve]) => reserve); const reservesAndOracles = (0, lib_1.getTokenOracleDataSync)(allOracleAccounts, switchboardV2, allReserves); reservesAndOracles.forEach(([reserve, oracle], index) => { if (!oracle) { console.log('Manager > getAllMarkets: oracle not found for reserve', reserve.config.tokenInfo.name); return; } const kaminoReserve = lib_1.KaminoReserve.initialize(allBuffers[index], reserves[index][0], reserves[index][1], oracle, this.getConnection(), this.recentSlotDurationMs); reservesByAddress.set(kaminoReserve.address, kaminoReserve); }); } return lib_1.KaminoMarket.loadWithReserves(this.getConnection(), market, reservesByAddress, pubkey, slotDuration); }); 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 filters = [ { dataSize: accounts_1.VaultState.layout.span + 8, }, { memcmp: { offset: 0, bytes: bs58_1.default.encode(accounts_1.VaultState.discriminator), }, }, { memcmp: { offset: 8, bytes: owner.toBase58(), }, }, ]; const kaminoVaults = await (0, rpc_1.getProgramAccounts)(this._connection, this._kaminoVaultProgramId, accounts_1.VaultState.layout.span + 8, { commitment: this._connection.commitment ?? 'processed', filters, }); return kaminoVaults.map((kaminoVault) => { if (kaminoVault.account === null) { throw new Error(`kaminoVault with pubkey ${kaminoVault.pubkey.toString()} does not exist`); } const kaminoVaultAccount = (0, vault_2.decodeVaultState)(kaminoVault.account.data); if (!kaminoVaultAccount) { throw Error(`kaminoVault with pubkey ${kaminoVault.pubkey.toString()} could not be decoded`); } return new vault_1.KaminoVault(kaminoVault.pubkey, kaminoVaultAccount, this._kaminoVaultProgramId); }); } /** * 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._connection.getParsedProgramAccounts(spl_token_1.TOKEN_PROGRAM_ID, { filters: [{ dataSize: 165 }, { memcmp: { offset: 0, bytes: shareMint.toBase58() } }], }); } /** * 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(this._connection); 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(this._connection); const tokenAccounts = await this.getVaultTokenAccounts(vault); const result = []; for (const tokenAccount of tokenAccounts) { const accountData = tokenAccount.account.data; result.push({ holderPubkey: new web3_js_1.PublicKey(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. Optional. If not provided the function will fetch the current slot * @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. Optional. If not provided the function will fetch the current slot * @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 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, actual 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 for. Optional. If not provided the function will fetch the current slot * @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 [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 * @returns an VaultOverview object with details about the tokens available and invested in the vault, denominated in tokens and USD */ async getVaultOverview(vault, price, slot, vaultReserves, kaminoMarkets, currentSlot) { return this._vaultClient.getVaultOverview(vault, price, slot, vaultReserves, kaminoMarkets, currentSlot); } /** * Prints a vault in a human readable form * @param vaultPubkey - the address of the vault * @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, vaultState) { return this._vaultClient.printVault(vaultPubkey, 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 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 [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 * @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 [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 * @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 [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 current slot. Optional. If not provided it will fetch the current 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, vaultReserves, slot, previousTotalAUM, currentSlot) { return this._vaultClient.calculateSimulatedHoldingsWithInterest(vaultState, vaultReserves, slot, 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. Optional. If not provided the function will fetch the current slot * @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 * @returns a struct of simulated management and interest fees */ async calculateSimulatedFees(vaultState, simulatedCurrentHoldingsWithInterest, currentTimestamp) { return this._vaultClient.calculateSimulatedFees(vaultState, simulatedCurrentHoldingsWithInterest, currentTimestamp); } /** * This will compute the PDA that is used as delegatee in Farms program to compute the user state PDA */ computeUserFarmStateForUserInVault(farmProgramID, vault, reserve, user) { return this._vaultClient.computeUserFarmStateDelegateePDAForUserInVault(farmProgramID, reserve, vault, user); } /** * 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 * @returns a hashmap from each reserve pubkey to the reserve state */ async loadVaultsReserves(vaults) { return this._vaultClient.loadVaultsReserves(vaults); } /** * 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 */ getVaultReserves(vault) { return this._vaultClient.getVaultReserves(vault); } /** * 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 * * @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 kaminoVault - vault to invest from * @returns - an array of invest instructions for each invest action required for the vault reserves */ async investAllReservesIxs(payer, kaminoVault) { return this._vaultClient.investAllReservesIxs(payer, kaminoVault); } /** * 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 * @param vault - vault to invest from * @param reserve - 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 * @returns - an array of invest instructions for each invest action required for the vault reserves */ async investSingleReserveIxs(payer, kaminoVault, reserveWithAddress, vaultReservesMap) { return this._vaultClient.investSingleReserveIxs(payer, kaminoVault, reserveWithAddress, vaultReservesMap); } /** * 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);