UNPKG

@kamino-finance/klend-sdk

Version:

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

812 lines 128 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ReserveAllocationConfig = exports.KaminoVaultConfig = exports.KaminoVault = exports.KaminoVaultClient = exports.INITIAL_DEPOSIT_LAMPORTS = exports.METADATA_PROGRAM_ID = exports.METADATA_SEED = exports.kaminoVaultStagingId = exports.kaminoVaultId = void 0; exports.getCTokenVaultPda = getCTokenVaultPda; exports.getEventAuthorityPda = getEventAuthorityPda; exports.printHoldings = printHoldings; const anchor_1 = require("@coral-xyz/anchor"); const web3_js_1 = require("@solana/web3.js"); const spl_token_1 = require("@solana/spl-token"); const lib_1 = require("../lib"); const instructions_1 = require("../idl_codegen_kamino_vault/instructions"); const types_1 = require("../idl_codegen_kamino_vault/types"); const accounts_1 = require("../idl_codegen_kamino_vault/accounts"); const decimal_js_1 = __importDefault(require("decimal.js")); const utils_1 = require("./utils"); const instructions_2 = require("../idl_codegen_kamino_vault/instructions"); const instructions_3 = require("../idl_codegen_kamino_vault/instructions"); const programId_1 = require("../idl_codegen/programId"); const fraction_1 = require("./fraction"); const utils_2 = require("../utils"); const bs58_1 = __importDefault(require("bs58")); const rpc_1 = require("../utils/rpc"); const kliquidity_sdk_1 = require("@kamino-finance/kliquidity-sdk"); const CreationParameters_1 = require("@kamino-finance/kliquidity-sdk/dist/utils/CreationParameters"); const dist_1 = require("@kamino-finance/farms-sdk/dist"); const lookupTable_1 = require("../utils/lookupTable"); const farm_utils_1 = require("./farm_utils"); const metadata_1 = require("../utils/metadata"); const vault_1 = require("../utils/vault"); exports.kaminoVaultId = new web3_js_1.PublicKey('KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd'); exports.kaminoVaultStagingId = new web3_js_1.PublicKey('stKvQfwRsQiKnLtMNVLHKS3exFJmZFsgfzBPWHECUYK'); const TOKEN_VAULT_SEED = 'token_vault'; const CTOKEN_VAULT_SEED = 'ctoken_vault'; const BASE_VAULT_AUTHORITY_SEED = 'authority'; const SHARES_SEED = 'shares'; const EVENT_AUTHORITY_SEED = '__event_authority'; exports.METADATA_SEED = 'metadata'; exports.METADATA_PROGRAM_ID = new web3_js_1.PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s'); exports.INITIAL_DEPOSIT_LAMPORTS = 1000; /** * KaminoVaultClient is a class that provides a high-level interface to interact with the Kamino Vault program. */ class KaminoVaultClient { _connection; _kaminoVaultProgramId; _kaminoLendProgramId; recentSlotDurationMs; constructor(connection, recentSlotDurationMs, kaminoVaultprogramId, kaminoLendProgramId) { this._connection = connection; this.recentSlotDurationMs = recentSlotDurationMs; this._kaminoVaultProgramId = kaminoVaultprogramId ? kaminoVaultprogramId : exports.kaminoVaultId; this._kaminoLendProgramId = kaminoLendProgramId ? kaminoLendProgramId : programId_1.PROGRAM_ID; } getConnection() { return this._connection; } getProgramID() { return this._kaminoVaultProgramId; } hasFarm() { return; } /** * 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) { const vault = vaultState ? vaultState : await accounts_1.VaultState.fetch(this.getConnection(), vaultPubkey); if (!vault) { console.log(`Vault ${vaultPubkey.toString()} not found`); return; } const kaminoVault = new KaminoVault(vaultPubkey, vault, this._kaminoVaultProgramId); const vaultName = this.decodeVaultName(vault.name); const slot = await this.getConnection().getSlot('confirmed'); const tokensPerShare = await this.getTokensPerShareSingleVault(kaminoVault, slot); const holdings = await this.getVaultHoldings(vault, slot); const sharesIssued = new decimal_js_1.default(vault.sharesIssued.toString()).div(new decimal_js_1.default(vault.sharesMintDecimals.toString())); console.log('Name: ', vaultName); console.log('Shares issued: ', sharesIssued); printHoldings(holdings); console.log('Tokens per share: ', tokensPerShare); } /** * 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) { const vaultState = web3_js_1.Keypair.generate(); const size = accounts_1.VaultState.layout.span + 8; const createVaultIx = web3_js_1.SystemProgram.createAccount({ fromPubkey: vaultConfig.admin, newAccountPubkey: vaultState.publicKey, lamports: await this.getConnection().getMinimumBalanceForRentExemption(size), space: size, programId: this._kaminoVaultProgramId, }); const tokenVault = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from(TOKEN_VAULT_SEED), vaultState.publicKey.toBytes()], this._kaminoVaultProgramId)[0]; const baseVaultAuthority = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from(BASE_VAULT_AUTHORITY_SEED), vaultState.publicKey.toBytes()], this._kaminoVaultProgramId)[0]; const sharesMint = web3_js_1.PublicKey.findProgramAddressSync([Buffer.from(SHARES_SEED), vaultState.publicKey.toBytes()], this._kaminoVaultProgramId)[0]; let adminTokenAccount; const prerequisiteIxs = []; const cleanupIxs = []; if (vaultConfig.tokenMint.equals(spl_token_1.NATIVE_MINT)) { const { wsolAta, createAtaIxs, closeAtaIxs } = await (0, utils_2.createWsolAtaIfMissing)(this.getConnection(), new decimal_js_1.default(utils_2.VAULT_INITIAL_DEPOSIT), vaultConfig.admin); adminTokenAccount = wsolAta; prerequisiteIxs.push(...createAtaIxs); cleanupIxs.push(...closeAtaIxs); } else { adminTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(vaultConfig.tokenMint, vaultConfig.admin, false, vaultConfig.tokenMintProgramId); } const initVaultAccounts = { adminAuthority: vaultConfig.admin, vaultState: vaultState.publicKey, baseTokenMint: vaultConfig.tokenMint, tokenVault, baseVaultAuthority, sharesMint, systemProgram: web3_js_1.SystemProgram.programId, rent: web3_js_1.SYSVAR_RENT_PUBKEY, tokenProgram: vaultConfig.tokenMintProgramId, sharesTokenProgram: spl_token_1.TOKEN_PROGRAM_ID, adminTokenAccount, }; const initVaultIx = (0, instructions_1.initVault)(initVaultAccounts, this._kaminoVaultProgramId); // create and set up the vault lookup table const slot = await this.getConnection().getSlot(); const [createLUTIx, lut] = (0, lookupTable_1.initLookupTableIx)(vaultConfig.admin, slot); const accountsToBeInserted = [ vaultConfig.admin, vaultState.publicKey, vaultConfig.tokenMint, vaultConfig.tokenMintProgramId, baseVaultAuthority, sharesMint, web3_js_1.SystemProgram.programId, web3_js_1.SYSVAR_RENT_PUBKEY, spl_token_1.TOKEN_PROGRAM_ID, this._kaminoLendProgramId, web3_js_1.SYSVAR_INSTRUCTIONS_PUBKEY, ]; const insertIntoLUTIxs = await this.insertIntoLookupTableIxs(vaultConfig.admin, lut, accountsToBeInserted, []); const setLUTIx = this.updateUninitialisedVaultConfigIx(vaultConfig.admin, vaultState.publicKey, new types_1.VaultConfigField.LookupTable(), lut.toString()); const ixs = [createVaultIx, initVaultIx, setLUTIx]; if (vaultConfig.getPerformanceFeeBps() > 0) { const setPerformanceFeeIx = this.updateUninitialisedVaultConfigIx(vaultConfig.admin, vaultState.publicKey, new types_1.VaultConfigField.PerformanceFeeBps(), vaultConfig.getPerformanceFeeBps().toString()); ixs.push(setPerformanceFeeIx); } if (vaultConfig.getManagementFeeBps() > 0) { const setManagementFeeIx = this.updateUninitialisedVaultConfigIx(vaultConfig.admin, vaultState.publicKey, new types_1.VaultConfigField.ManagementFeeBps(), vaultConfig.getManagementFeeBps().toString()); ixs.push(setManagementFeeIx); } if (vaultConfig.name && vaultConfig.name.length > 0) { const setNameIx = this.updateUninitialisedVaultConfigIx(vaultConfig.admin, vaultState.publicKey, new types_1.VaultConfigField.Name(), vaultConfig.name); ixs.push(setNameIx); } const metadataIx = await this.getSetSharesMetadataIx(this.getConnection(), vaultConfig.admin, vaultState.publicKey, sharesMint, baseVaultAuthority, vaultConfig.vaultTokenSymbol, vaultConfig.vaultTokenName); return { vault: vaultState, initVaultIxs: { createAtaIfNeededIxs: prerequisiteIxs, initVaultIxs: ixs, createLUTIx, populateLUTIxs: insertIntoLUTIxs, cleanupIxs, initSharesMetadataIx: metadataIx, }, }; } /** * 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(connection, vaultAdmin, vault, sharesMint, baseVaultAuthority, tokenName, extraName) { const [sharesMintMetadata] = (0, utils_2.getKVaultSharesMetadataPda)(sharesMint); const { name, symbol, uri } = (0, metadata_1.resolveMetadata)(sharesMint, extraName, tokenName); const ix = (await connection.getAccountInfo(sharesMintMetadata)) === null ? await (0, metadata_1.getInitializeKVaultSharesMetadataIx)(connection, vaultAdmin, vault, sharesMint, baseVaultAuthority, name, symbol, uri) : await (0, metadata_1.getUpdateSharesMetadataIx)(connection, vaultAdmin, vault, sharesMint, baseVaultAuthority, name, symbol, uri); return ix; } /** * 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 updateReserveAllocationIxs(vault, reserveAllocationConfig, signer) { const vaultState = await vault.getState(this.getConnection()); const reserveState = reserveAllocationConfig.getReserveState(); const cTokenVault = getCTokenVaultPda(vault.address, reserveAllocationConfig.getReserveAddress(), this._kaminoVaultProgramId); const allocationSigner = signer ? signer : vaultState.vaultAdminAuthority; const updateReserveAllocationAccounts = { signer: allocationSigner, vaultState: vault.address, baseVaultAuthority: vaultState.baseVaultAuthority, reserveCollateralMint: reserveState.collateral.mintPubkey, reserve: reserveAllocationConfig.getReserveAddress(), ctokenVault: cTokenVault, systemProgram: web3_js_1.SystemProgram.programId, rent: web3_js_1.SYSVAR_RENT_PUBKEY, reserveCollateralTokenProgram: spl_token_1.TOKEN_PROGRAM_ID, }; const updateReserveAllocationArgs = { weight: new anchor_1.BN(reserveAllocationConfig.targetAllocationWeight), cap: new anchor_1.BN(reserveAllocationConfig.getAllocationCapLamports().floor().toString()), }; const updateReserveAllocationIx = (0, instructions_1.updateReserveAllocation)(updateReserveAllocationArgs, updateReserveAllocationAccounts, this._kaminoVaultProgramId); const accountsToAddToLUT = [ reserveAllocationConfig.getReserveAddress(), cTokenVault, ...this.getReserveAccountsToInsertInLut(reserveState), ]; const lendingMarketAuth = (0, utils_2.lendingMarketAuthPda)(reserveState.lendingMarket, this._kaminoLendProgramId)[0]; accountsToAddToLUT.push(lendingMarketAuth); const insertIntoLUTIxs = await this.insertIntoLookupTableIxs(vaultState.vaultAdminAuthority, vaultState.vaultLookupTable, accountsToAddToLUT); const updateReserveAllocationIxs = { updateReserveAllocationIx, updateLUTIxs: insertIntoLUTIxs, }; return updateReserveAllocationIxs; } /** * 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) { const vaultState = await vault.getState(this.getConnection()); const reserveIsPartOfAllocation = vaultState.vaultAllocationStrategy.some((allocation) => allocation.reserve.equals(reserve)); const withdrawAndBlockReserveIxs = { updateReserveAllocationIxs: [], investIxs: [], }; if (!reserveIsPartOfAllocation) { return withdrawAndBlockReserveIxs; } const reserveState = await lib_1.Reserve.fetch(this.getConnection(), reserve); if (!reserveState) { return withdrawAndBlockReserveIxs; } const reserveWithAddress = { address: reserve, state: reserveState, }; const reserveAllocationConfig = new ReserveAllocationConfig(reserveWithAddress, 0, new decimal_js_1.default(0)); // update allocation to have 0 weight and 0 cap const updateAllocIxs = await this.updateReserveAllocationIxs(vault, reserveAllocationConfig); const investPayer = payer ? payer : vaultState.vaultAdminAuthority; const investIx = await this.investSingleReserveIxs(investPayer, vault, reserveWithAddress); withdrawAndBlockReserveIxs.updateReserveAllocationIxs = [updateAllocIxs.updateReserveAllocationIx]; withdrawAndBlockReserveIxs.investIxs = investIx; return withdrawAndBlockReserveIxs; } /** * 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) { const vaultState = await vault.getState(this.getConnection()); const reserves = this.getVaultReserves(vaultState); const withdrawAndBlockReserveIxs = { updateReserveAllocationIxs: [], investIxs: [], }; if (!vaultReservesMap) { vaultReservesMap = await this.loadVaultReserves(vaultState); } for (const reserve of reserves) { const reserveWithAddress = { address: reserve, state: vaultReservesMap.get(reserve).state, }; const reserveAllocationConfig = new ReserveAllocationConfig(reserveWithAddress, 0, new decimal_js_1.default(0)); // update allocation to have 0 weight and 0 cap const updateAllocIxs = await this.updateReserveAllocationIxs(vault, reserveAllocationConfig); withdrawAndBlockReserveIxs.updateReserveAllocationIxs.push(updateAllocIxs.updateReserveAllocationIx); } const investPayer = payer ? payer : vaultState.vaultAdminAuthority; const investIxs = await this.investAllReservesIxs(investPayer, vault); withdrawAndBlockReserveIxs.investIxs = investIxs; return withdrawAndBlockReserveIxs; } /** * 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) { const vaultState = await vault.getState(this.getConnection()); const reserveIsPartOfAllocation = vaultState.vaultAllocationStrategy.some((allocation) => allocation.reserve.equals(reserve)); if (!reserveIsPartOfAllocation) { return undefined; } const accounts = { vaultAdminAuthority: vaultState.vaultAdminAuthority, vaultState: vault.address, reserve, }; return (0, instructions_1.removeAllocation)(accounts); } /** * 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) { const vaultState = await vault.getState(this.getConnection()); const updateVaultConfigAccs = { vaultAdminAuthority: vaultState.vaultAdminAuthority, vaultState: vault.address, klendProgram: this._kaminoLendProgramId, }; if (signer) { updateVaultConfigAccs.vaultAdminAuthority = signer; } const updateVaultConfigArgs = { entry: mode, data: Buffer.from([0]), }; if (isNaN(+value)) { if (mode.kind === new types_1.VaultConfigField.Name().kind) { const data = Array.from(this.encodeVaultName(value)); updateVaultConfigArgs.data = Buffer.from(data); } else { const data = new web3_js_1.PublicKey(value); updateVaultConfigArgs.data = data.toBuffer(); } } else { const buffer = Buffer.alloc(8); buffer.writeBigUInt64LE(BigInt(value.toString())); updateVaultConfigArgs.data = buffer; } const vaultReserves = this.getVaultReserves(vaultState); const vaultReservesState = await this.loadVaultReserves(vaultState); let vaultReservesAccountMetas = []; let vaultReservesLendingMarkets = []; vaultReserves.forEach((reserve) => { const reserveState = vaultReservesState.get(reserve); if (reserveState === undefined) { throw new Error(`Reserve ${reserve.toBase58()} not found`); } vaultReservesAccountMetas = vaultReservesAccountMetas.concat([ { pubkey: reserve, isSigner: false, isWritable: true }, ]); vaultReservesLendingMarkets = vaultReservesLendingMarkets.concat([ { pubkey: reserveState.state.lendingMarket, isSigner: false, isWritable: false }, ]); }); const updateVaultConfigIx = (0, instructions_1.updateVaultConfig)(updateVaultConfigArgs, updateVaultConfigAccs, this._kaminoVaultProgramId); updateVaultConfigIx.keys = updateVaultConfigIx.keys.concat(vaultReservesAccountMetas); updateVaultConfigIx.keys = updateVaultConfigIx.keys.concat(vaultReservesLendingMarkets); const updateLUTIxs = []; if (mode.kind === new types_1.VaultConfigField.PendingVaultAdmin().kind) { const newPubkey = new web3_js_1.PublicKey(value); const insertIntoLutIxs = await this.insertIntoLookupTableIxs(vaultState.vaultAdminAuthority, vaultState.vaultLookupTable, [newPubkey]); updateLUTIxs.push(...insertIntoLutIxs); } else if (mode.kind === new types_1.VaultConfigField.Farm().kind) { const keysToAddToLUT = [new web3_js_1.PublicKey(value)]; // if the farm already exist we want to read its state to add it to the LUT try { const farmState = await dist_1.FarmState.fetch(this.getConnection(), keysToAddToLUT[0]); keysToAddToLUT.push(farmState.farmVault, farmState.farmVaultsAuthority, farmState.token.mint, farmState.scopePrices, farmState.globalConfig); const insertIntoLutIxs = await this.insertIntoLookupTableIxs(vaultState.vaultAdminAuthority, vaultState.vaultLookupTable, keysToAddToLUT); updateLUTIxs.push(...insertIntoLutIxs); } catch (error) { console.log(`Error fetching farm ${keysToAddToLUT[0].toString()} state`, error); } } const updateVaultConfigIxs = { updateVaultConfigIx, updateLUTIxs, }; return updateVaultConfigIxs; } /** 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) { const vaultHasFarm = await vault.hasFarm(this.getConnection()); if (vaultHasFarm && errorOnOverride) { throw new Error('Vault already has a farm, if you want to override it set errorOnOverride to false'); } return this.updateVaultConfigIxs(vault, new types_1.VaultConfigField.Farm(), farm.toBase58()); } /** * This method updates the vault config for a vault that * @param vault - address of vault to be updated * @param mode - the field to be updated * @param value - the new value for the field to be updated (number or pubkey) * @returns - an instruction to update the vault config */ updateUninitialisedVaultConfigIx(admin, vault, mode, value) { const updateVaultConfigAccs = { vaultAdminAuthority: admin, vaultState: vault, klendProgram: this._kaminoLendProgramId, }; const updateVaultConfigArgs = { entry: mode, data: Buffer.from([0]), }; if (isNaN(+value)) { if (mode.kind === new types_1.VaultConfigField.Name().kind) { const data = Array.from(this.encodeVaultName(value)); updateVaultConfigArgs.data = Buffer.from(data); } else { const data = new web3_js_1.PublicKey(value); updateVaultConfigArgs.data = data.toBuffer(); } } else { const buffer = Buffer.alloc(8); buffer.writeBigUInt64LE(BigInt(value.toString())); updateVaultConfigArgs.data = buffer; } const updateVaultConfigIx = (0, instructions_1.updateVaultConfig)(updateVaultConfigArgs, updateVaultConfigAccs, this._kaminoVaultProgramId); return updateVaultConfigIx; } /** * 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) { const vaultState = await vault.getState(this.getConnection()); const acceptOwneshipAccounts = { pendingAdmin: vaultState.pendingAdmin, vaultState: vault.address, }; const acceptVaultOwnershipIx = (0, instructions_1.updateAdmin)(acceptOwneshipAccounts, this._kaminoVaultProgramId); // read the current LUT and create a new one for the new admin and backfill it const accountsInExistentLUT = (await (0, lookupTable_1.getAccountsInLUT)(this.getConnection(), vaultState.vaultLookupTable)).filter((account) => !account.equals(vaultState.vaultAdminAuthority)); const LUTIxs = []; const [initNewLUTIx, newLUT] = (0, lookupTable_1.initLookupTableIx)(vaultState.pendingAdmin, await this.getConnection().getSlot()); const insertIntoLUTIxs = await this.insertIntoLookupTableIxs(vaultState.pendingAdmin, newLUT, accountsInExistentLUT, []); LUTIxs.push(...insertIntoLUTIxs); const updateVaultConfigIxs = await this.updateVaultConfigIxs(vault, new types_1.VaultConfigField.LookupTable(), newLUT.toString(), vaultState.pendingAdmin); LUTIxs.push(updateVaultConfigIxs.updateVaultConfigIx); LUTIxs.push(...updateVaultConfigIxs.updateLUTIxs); const acceptVaultOwnershipIxs = { acceptVaultOwnershipIx, initNewLUTIx, updateLUTIxs: LUTIxs, }; return acceptVaultOwnershipIxs; } /** * 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) { const vaultState = await vault.getState(this.getConnection()); const giveUpPendingFeesAccounts = { vaultAdminAuthority: vaultState.vaultAdminAuthority, vaultState: vault.address, klendProgram: this._kaminoLendProgramId, }; const maxAmountToGiveUpLamports = (0, utils_1.numberToLamportsDecimal)(maxAmountToGiveUp, vaultState.tokenMintDecimals.toNumber()); const giveUpPendingFeesArgs = { maxAmountToGiveUp: new anchor_1.BN(maxAmountToGiveUpLamports.toString()), }; return (0, instructions_1.giveUpPendingFees)(giveUpPendingFeesArgs, giveUpPendingFeesAccounts, this._kaminoVaultProgramId); } /** * 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, vaultReservesMap) { const vaultState = await vault.getState(this.getConnection()); const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState); const [{ ata: adminTokenAta, createAtaIx }] = (0, utils_2.createAtasIdempotent)(vaultState.vaultAdminAuthority, [ { mint: vaultState.tokenMint, tokenProgram: spl_token_1.TOKEN_PROGRAM_ID, }, ]); const tokensToWithdraw = new fraction_1.Fraction(vaultState.pendingFeesSf).toDecimal(); let tokenLeftToWithdraw = tokensToWithdraw; tokenLeftToWithdraw = tokenLeftToWithdraw.sub(new decimal_js_1.default(vaultState.tokenAvailable.toString())); const reservesToWithdraw = []; if (tokenLeftToWithdraw.lte(0)) { // Availabe enough to withdraw all - using first reserve as it does not matter reservesToWithdraw.push(vaultState.vaultAllocationStrategy[0].reserve); } else { // Get decreasing order sorted available liquidity to withdraw from each reserve allocated to const reserveAllocationAvailableLiquidityToWithdraw = await this.getReserveAllocationAvailableLiquidityToWithdraw(vault, slot, vaultReservesState); // sort const reserveAllocationAvailableLiquidityToWithdrawSorted = new lib_1.PubkeyHashMap([...reserveAllocationAvailableLiquidityToWithdraw.entries()].sort((a, b) => b[1].sub(a[1]).toNumber())); reserveAllocationAvailableLiquidityToWithdrawSorted.forEach((availableLiquidityToWithdraw, key) => { if (tokenLeftToWithdraw.gt(0)) { reservesToWithdraw.push(key); tokenLeftToWithdraw = tokenLeftToWithdraw.sub(availableLiquidityToWithdraw); } }); } const reserveStates = await lib_1.Reserve.fetchMultiple(this.getConnection(), reservesToWithdraw, this._kaminoLendProgramId); const withdrawIxs = await Promise.all(reservesToWithdraw.map(async (reserve, index) => { if (reserveStates[index] === null) { throw new Error(`Reserve ${reserve.toBase58()} not found`); } const reserveState = reserveStates[index]; const marketAddress = reserveState.lendingMarket; return this.withdrawPendingFeesIx(vault, vaultState, marketAddress, { address: reserve, state: reserveState }, adminTokenAta); })); return [createAtaIx, ...withdrawIxs]; } // async closeVaultIx(vault: KaminoVault): Promise<TransactionInstruction> { // const vaultState: VaultState = await vault.getState(this.getConnection()); // const closeVaultAccounts: CloseVaultAccounts = { // adminAuthority: vaultState.adminAuthority, // vaultState: vault.address, // }; // return closeVault(closeVaultAccounts, this._kaminoVaultProgramId); // } /** * 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 depositIxs(user, vault, tokenAmount, vaultReservesMap, farmState) { const vaultState = await vault.getState(this.getConnection()); const tokenProgramID = vaultState.tokenProgram; const userTokenAta = (0, lib_1.getAssociatedTokenAddress)(vaultState.tokenMint, user, true, tokenProgramID); const createAtasIxs = []; const closeAtasIxs = []; if (vaultState.tokenMint.equals(spl_token_1.NATIVE_MINT)) { const [{ ata: wsolAta, createAtaIx: createWsolAtaIxn }] = (0, utils_2.createAtasIdempotent)(user, [ { mint: spl_token_1.NATIVE_MINT, tokenProgram: spl_token_1.TOKEN_PROGRAM_ID, }, ]); createAtasIxs.push(createWsolAtaIxn); const transferWsolIxs = (0, lib_1.getTransferWsolIxs)(user, wsolAta, (0, utils_1.numberToLamportsDecimal)(tokenAmount, vaultState.tokenMintDecimals.toNumber()).ceil()); createAtasIxs.push(...transferWsolIxs); } const [{ ata: userSharesAta, createAtaIx: createSharesAtaIxs }] = (0, utils_2.createAtasIdempotent)(user, [ { mint: vaultState.sharesMint, tokenProgram: spl_token_1.TOKEN_PROGRAM_ID, }, ]); createAtasIxs.push(createSharesAtaIxs); const eventAuthority = getEventAuthorityPda(this._kaminoVaultProgramId); const depoistAccounts = { user: user, vaultState: vault.address, tokenVault: vaultState.tokenVault, tokenMint: vaultState.tokenMint, baseVaultAuthority: vaultState.baseVaultAuthority, sharesMint: vaultState.sharesMint, userTokenAta: userTokenAta, userSharesAta: userSharesAta, tokenProgram: tokenProgramID, klendProgram: this._kaminoLendProgramId, sharesTokenProgram: spl_token_1.TOKEN_PROGRAM_ID, eventAuthority: eventAuthority, program: this._kaminoVaultProgramId, }; const depositArgs = { maxAmount: new anchor_1.BN((0, utils_1.numberToLamportsDecimal)(tokenAmount, vaultState.tokenMintDecimals.toNumber()).floor().toString()), }; const depositIx = (0, instructions_2.deposit)(depositArgs, depoistAccounts, this._kaminoVaultProgramId); const vaultReserves = this.getVaultReserves(vaultState); const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState); let vaultReservesAccountMetas = []; let vaultReservesLendingMarkets = []; vaultReserves.forEach((reserve) => { const reserveState = vaultReservesState.get(reserve); if (reserveState === undefined) { throw new Error(`Reserve ${reserve.toBase58()} not found`); } vaultReservesAccountMetas = vaultReservesAccountMetas.concat([ { pubkey: reserve, isSigner: false, isWritable: true }, ]); vaultReservesLendingMarkets = vaultReservesLendingMarkets.concat([ { pubkey: reserveState.state.lendingMarket, isSigner: false, isWritable: false }, ]); }); depositIx.keys = depositIx.keys.concat(vaultReservesAccountMetas); depositIx.keys = depositIx.keys.concat(vaultReservesLendingMarkets); const depositIxs = { depositIxs: [...createAtasIxs, depositIx, ...closeAtasIxs], stakeInFarmIfNeededIxs: [], }; // if there is no farm, we can return the deposit instructions, otherwise include the stake ix in the response if (!(await vault.hasFarm(this.getConnection()))) { return depositIxs; } // if there is a farm, stake the shares const stakeSharesIxs = await this.stakeSharesIxs(user, vault, undefined, farmState); depositIxs.stakeInFarmIfNeededIxs = stakeSharesIxs; return depositIxs; } /** * 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) { const vaultState = await vault.getState(this.getConnection()); let sharesToStakeLamports = new decimal_js_1.default(utils_2.U64_MAX); if (sharesAmount) { sharesToStakeLamports = (0, utils_1.numberToLamportsDecimal)(sharesAmount, vaultState.sharesMintDecimals.toNumber()); } // if tokens to be staked are 0 or vault has no farm there is no stake needed if (sharesToStakeLamports.lte(0) || !vault.hasFarm(this.getConnection())) { return []; } // returns the ix to create the farm state account if needed and the ix to stake the shares return (0, farm_utils_1.getFarmStakeIxs)(this.getConnection(), user, sharesToStakeLamports, vaultState.vaultFarm, farmState); } /** * This function will return a struct with the instructions to unstake from the farm if necessary and the instructions for 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 withdrawIxs(user, vault, shareAmount, slot, vaultReservesMap, farmState) { const vaultState = await vault.getState(this.getConnection()); const kaminoVault = new KaminoVault(vault.address, vaultState, vault.programId); const withdrawIxs = { unstakeFromFarmIfNeededIxs: [], withdrawIxs: [], postWithdrawIxs: [], }; const shareLamportsToWithdraw = (0, kliquidity_sdk_1.collToLamportsDecimal)(shareAmount, vaultState.sharesMintDecimals.toNumber()); const hasFarm = await vault.hasFarm(this.getConnection()); if (hasFarm) { const unstakeAndWithdrawFromFarmIxs = await (0, farm_utils_1.getFarmUnstakeAndWithdrawIxs)(this.getConnection(), user, shareLamportsToWithdraw, vaultState.vaultFarm, farmState); withdrawIxs.unstakeFromFarmIfNeededIxs.push(unstakeAndWithdrawFromFarmIxs.unstakeIx); withdrawIxs.unstakeFromFarmIfNeededIxs.push(unstakeAndWithdrawFromFarmIxs.withdrawIx); } // if the vault has allocations withdraw otherwise wtihdraw from available ix const vaultAllocation = vaultState.vaultAllocationStrategy.find((allocation) => !allocation.reserve.equals(web3_js_1.PublicKey.default)); if (vaultAllocation) { const withdrawFromVaultIxs = await this.withdrawWithReserveIxs(user, kaminoVault, shareAmount, slot, vaultReservesMap); withdrawIxs.withdrawIxs = withdrawFromVaultIxs; } else { const withdrawFromVaultIxs = await this.withdrawFromAvailableIxs(user, kaminoVault, shareAmount); withdrawIxs.withdrawIxs = withdrawFromVaultIxs; } // if the vault is for SOL return the ix to unwrap the SOL if (vaultState.tokenMint.equals(spl_token_1.NATIVE_MINT)) { const userWsolAta = (0, lib_1.getAssociatedTokenAddress)(spl_token_1.NATIVE_MINT, user); const unwrapIx = (0, spl_token_1.createCloseAccountInstruction)(userWsolAta, user, user, [], spl_token_1.TOKEN_PROGRAM_ID); withdrawIxs.postWithdrawIxs.push(unwrapIx); } return withdrawIxs; } async withdrawFromAvailableIxs(user, vault, shareAmount) { const vaultState = await vault.getState(this.getConnection()); const kaminoVault = new KaminoVault(vault.address, vaultState, vault.programId); const userSharesAta = (0, lib_1.getAssociatedTokenAddress)(vaultState.sharesMint, user); const [{ ata: userTokenAta, createAtaIx }] = (0, utils_2.createAtasIdempotent)(user, [ { mint: vaultState.tokenMint, tokenProgram: vaultState.tokenProgram, }, ]); const shareLamportsToWithdraw = (0, kliquidity_sdk_1.collToLamportsDecimal)(shareAmount, vaultState.sharesMintDecimals.toNumber()); const withdrawFromAvailableIxn = await this.withdrawFromAvailableIx(user, kaminoVault, vaultState, userSharesAta, userTokenAta, shareLamportsToWithdraw); return [createAtaIx, withdrawFromAvailableIxn]; } async withdrawWithReserveIxs(user, vault, shareAmount, slot, vaultReservesMap) { const vaultState = await vault.getState(this.getConnection()); const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState); const userSharesAta = (0, lib_1.getAssociatedTokenAddress)(vaultState.sharesMint, user); const [{ ata: userTokenAta, createAtaIx }] = (0, utils_2.createAtasIdempotent)(user, [ { mint: vaultState.tokenMint, tokenProgram: vaultState.tokenProgram, }, ]); const shareLamportsToWithdraw = (0, kliquidity_sdk_1.collToLamportsDecimal)(shareAmount, vaultState.sharesMintDecimals.toNumber()); const tokensPerShare = await this.getTokensPerShareSingleVault(vault, slot); const sharesPerToken = new decimal_js_1.default(1).div(tokensPerShare); const tokensToWithdraw = shareLamportsToWithdraw.mul(tokensPerShare); let tokenLeftToWithdraw = tokensToWithdraw; const availableTokens = new decimal_js_1.default(vaultState.tokenAvailable.toString()); tokenLeftToWithdraw = tokenLeftToWithdraw.sub(availableTokens); const reserveWithSharesAmountToWithdraw = []; let isFirstWithdraw = true; if (tokenLeftToWithdraw.lte(0)) { // Availabe enough to withdraw all - using the first existent reserve const firstReserve = vaultState.vaultAllocationStrategy.find((reserve) => !reserve.reserve.equals(web3_js_1.PublicKey.default)); reserveWithSharesAmountToWithdraw.push({ reserve: firstReserve.reserve, shares: shareLamportsToWithdraw, }); } else { // Get decreasing order sorted available liquidity to withdraw from each reserve allocated to const reserveAllocationAvailableLiquidityToWithdraw = await this.getReserveAllocationAvailableLiquidityToWithdraw(vault, slot, vaultReservesState); // sort const reserveAllocationAvailableLiquidityToWithdrawSorted = [ ...reserveAllocationAvailableLiquidityToWithdraw.entries(), ].sort((a, b) => b[1].sub(a[1]).toNumber()); reserveAllocationAvailableLiquidityToWithdrawSorted.forEach(([key, availableLiquidityToWithdraw], _) => { if (tokenLeftToWithdraw.gt(0)) { let tokensToWithdrawFromReserve = decimal_js_1.default.min(tokenLeftToWithdraw, availableLiquidityToWithdraw); if (isFirstWithdraw) { tokensToWithdrawFromReserve = tokensToWithdrawFromReserve.add(availableTokens); isFirstWithdraw = false; } // round up to the nearest integer the shares to withdraw const sharesToWithdrawFromReserve = tokensToWithdrawFromReserve.mul(sharesPerToken).ceil(); reserveWithSharesAmountToWithdraw.push({ reserve: key, shares: sharesToWithdrawFromReserve }); tokenLeftToWithdraw = tokenLeftToWithdraw.sub(tokensToWithdrawFromReserve); } }); } const withdrawIxs = []; withdrawIxs.push(createAtaIx); for (let reserveIndex = 0; reserveIndex < reserveWithSharesAmountToWithdraw.length; reserveIndex++) { const reserveWithTokens = reserveWithSharesAmountToWithdraw[reserveIndex]; const reserveState = vaultReservesState.get(reserveWithTokens.reserve); if (reserveState === undefined) { throw new Error(`Reserve ${reserveWithTokens.reserve.toBase58()} not found in vault reserves map`); } const marketAddress = reserveState.state.lendingMarket; const isLastWithdraw = reserveIndex === reserveWithSharesAmountToWithdraw.length - 1; // if it is not last withdraw it means that we can pass all shares as we are withdrawing everything from that reserve let sharesToWithdraw = shareAmount; if (isLastWithdraw) { sharesToWithdraw = reserveWithTokens.shares; } const withdrawFromReserveIx = this.withdrawIx(user, vault, vaultState, marketAddress, { address: reserveWithTokens.reserve, state: reserveState.state }, userSharesAta, userTokenAta, sharesToWithdraw, vaultReservesState); withdrawIxs.push(withdrawFromReserveIx); } return withdrawIxs; } /** * 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 wallet that pays the tx * @param vault - vault to invest from * @returns - an array of invest instructions for each invest action required for the vault reserves */ async investAllReservesIxs(payer, vault) { const vaultState = await vault.getState(this.getConnection()); const minInvestAmount = vaultState.minInvestAmount; const allReserves = this.getVaultReserves(vaultState); if (allReserves.length === 0) { throw new Error('No reserves found for the vault, please select at least one reserve for the vault'); } const [allReservesStateMap, computedReservesAllocation] = await Promise.all([ this.loadVaultReserves(vaultState), this.getVaultComputedReservesAllocation(vaultState), ]); const tokenProgram = await (0, rpc_1.getAccountOwner)(this.getConnection(), vaultState.tokenMint); const [{ ata: _payerTokenAta, createAtaIx }] = (0, utils_2.createAtasIdempotent)(payer, [ { mint: vaultState.tokenMint, tokenProgram }, ]); // compute total vault holdings and expected distribution based on weights const curentVaultAllocations = this.getVaultAllocations(vaultState); const reservesToDisinvestFrom = []; const reservesToInvestInto = []; for (let index = 0; index < allReserves.length; index++) { const reservePubkey = allReserves[index]; const reserveState = allReservesStateMap.get(reservePubkey); const computedAllocation = computedReservesAllocation.get(reservePubkey); const currentCTokenAllocation = curentVaultAllocations.get(reservePubkey).ctokenAllocation; const currentAllocationCap = curentVaultAllocations.get(reservePubkey).tokenAllocationCap; const reserveCollExchangeRate = reserveState.getCollateralExchangeRate(); const reserveAllocationLiquidityAmount = (0, lib_1.lamportsToDecimal)(currentCTokenAllocation.div(reserveCollExchangeRate), vaultState.tokenMintDecimals.toNumber()); const diffInReserveTokens = computedAllocation.sub(reserveAllocation