@kamino-finance/klend-sdk
Version:
Typescript SDK for interacting with the Kamino Lending (klend) protocol
1,272 lines (1,132 loc) • 174 kB
text/typescript
import BN from 'bn.js';
import {
Account,
AccountRole,
Address,
address,
Base58EncodedBytes,
fetchEncodedAccount,
generateKeyPairSigner,
getAddressEncoder,
getBase58Decoder,
GetProgramAccountsDatasizeFilter,
GetProgramAccountsMemcmpFilter,
getProgramDerivedAddress,
AccountMeta,
Instruction,
lamports,
ProgramDerivedAddress,
Rpc,
Slot,
SolanaRpcApi,
TransactionSigner,
AccountInfoWithPubkey,
AccountInfoBase,
AccountInfoWithJsonData,
} from '@solana/kit';
import {
AllOracleAccounts,
DEFAULT_PUBLIC_KEY,
DEFAULT_RECENT_SLOT_DURATION_MS,
getAssociatedTokenAddress,
getTokenBalanceFromAccountInfoLamports,
getTokenOracleData,
getTransferWsolIxs,
KaminoMarket,
KaminoReserve,
lamportsToDecimal,
Reserve,
UserState,
WRAPPED_SOL_MINT,
} from '../lib';
import {
deposit,
DepositAccounts,
DepositArgs,
giveUpPendingFees,
GiveUpPendingFeesAccounts,
GiveUpPendingFeesArgs,
initVault,
InitVaultAccounts,
invest,
InvestAccounts,
removeAllocation,
RemoveAllocationAccounts,
updateAdmin,
UpdateAdminAccounts,
updateReserveAllocation,
UpdateReserveAllocationAccounts,
UpdateReserveAllocationArgs,
updateVaultConfig,
UpdateVaultConfigAccounts,
UpdateVaultConfigArgs,
withdraw,
WithdrawAccounts,
WithdrawArgs,
withdrawFromAvailable,
WithdrawFromAvailableAccounts,
WithdrawFromAvailableArgs,
withdrawPendingFees,
WithdrawPendingFeesAccounts,
} from '../@codegen/kvault/instructions';
import { VaultConfigField, VaultConfigFieldKind } from '../@codegen/kvault/types';
import { VaultState } from '../@codegen/kvault/accounts';
import Decimal from 'decimal.js';
import { bpsToPct, decodeVaultName, numberToLamportsDecimal, parseTokenSymbol, pubkeyHashMapToJson } from './utils';
import { PROGRAM_ID } from '../@codegen/klend/programId';
import { ReserveWithAddress } from './reserve';
import { Fraction } from './fraction';
import {
CDN_ENDPOINT,
createAtasIdempotent,
createWsolAtaIfMissing,
getAllStandardTokenProgramTokenAccounts,
getKVaultSharesMetadataPda,
getTokenAccountAmount,
getTokenAccountMint,
lendingMarketAuthPda,
SECONDS_PER_YEAR,
U64_MAX,
VAULT_INITIAL_DEPOSIT,
} from '../utils';
import { getAccountOwner, getProgramAccounts } from '../utils/rpc';
import {
AcceptVaultOwnershipIxs,
APYs,
CreateVaultFarm,
DepositIxs,
DisinvestAllReservesIxs,
InitVaultIxs,
ReserveAllocationOverview,
SyncVaultLUTIxs,
UpdateReserveAllocationIxs,
UpdateVaultConfigIxs,
UserSharesForVault,
VaultComputedAllocation,
WithdrawAndBlockReserveIxs,
WithdrawIxs,
} from './vault_types';
import { batchFetch, collToLamportsDecimal, ZERO } from '@kamino-finance/kliquidity-sdk';
import { FullBPSDecimal } from '@kamino-finance/kliquidity-sdk/dist/utils/CreationParameters';
import { FarmConfigOption, FarmIncentives, FarmState, getUserStatePDA } from '@kamino-finance/farms-sdk/dist';
import { getAccountsInLut, initLookupTableIx, insertIntoLookupTableIxs } from '../utils/lookupTable';
import {
FARMS_ADMIN_MAINNET,
FARMS_GLOBAL_CONFIG_MAINNET,
getFarmStakeIxs,
getFarmUnstakeAndWithdrawIxs,
getSharesInFarmUserPosition,
getUserPendingRewardsInFarm,
getUserSharesInTokensStakedInFarm,
} from './farm_utils';
import { getCreateAccountInstruction, SYSTEM_PROGRAM_ADDRESS } from '@solana-program/system';
import { getInitializeKVaultSharesMetadataIx, getUpdateSharesMetadataIx, resolveMetadata } from '../utils/metadata';
import { decodeVaultState } from '../utils/vault';
import { fetchMaybeToken, findAssociatedTokenPda, getCloseAccountInstruction } from '@solana-program/token-2022';
import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token';
import { SYSVAR_INSTRUCTIONS_ADDRESS, SYSVAR_RENT_ADDRESS } from '@solana/sysvars';
import { noopSigner } from '../utils/signer';
import { Farms } from '@kamino-finance/farms-sdk';
import { getFarmIncentives } from '@kamino-finance/farms-sdk/dist/utils/apy';
import { computeReservesAllocation } from '../utils/vaultAllocation';
import { getReserveFarmRewardsAPY } from '../utils/farmUtils';
export const kaminoVaultId = address('KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd');
export const kaminoVaultStagingId = address('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';
export const METADATA_SEED = 'metadata';
export const METADATA_PROGRAM_ID: Address = address('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s');
export const INITIAL_DEPOSIT_LAMPORTS = 1000;
const addressEncoder = getAddressEncoder();
const base58Decoder = getBase58Decoder();
/**
* KaminoVaultClient is a class that provides a high-level interface to interact with the Kamino Vault program.
*/
export class KaminoVaultClient {
private readonly _rpc: Rpc<SolanaRpcApi>;
private readonly _kaminoVaultProgramId: Address;
private readonly _kaminoLendProgramId: Address;
recentSlotDurationMs: number;
constructor(
rpc: Rpc<SolanaRpcApi>,
recentSlotDurationMs: number,
kaminoVaultprogramId?: Address,
kaminoLendProgramId?: Address
) {
this._rpc = rpc;
this.recentSlotDurationMs = recentSlotDurationMs;
this._kaminoVaultProgramId = kaminoVaultprogramId ? kaminoVaultprogramId : kaminoVaultId;
this._kaminoLendProgramId = kaminoLendProgramId ? kaminoLendProgramId : PROGRAM_ID;
}
getConnection() {
return this._rpc;
}
getProgramID() {
return this._kaminoVaultProgramId;
}
getRpc() {
return this._rpc;
}
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: Address, vaultState?: VaultState) {
const vault = vaultState ? vaultState : await VaultState.fetch(this.getConnection(), vaultPubkey);
if (!vault) {
console.log(`Vault ${vaultPubkey.toString()} not found`);
return;
}
const kaminoVault = KaminoVault.loadWithClientAndState(this, vaultPubkey, vault);
const vaultName = this.decodeVaultName(vault.name);
const slot = await this.getConnection().getSlot({ commitment: 'confirmed' }).send();
const tokensPerShare = await this.getTokensPerShareSingleVault(kaminoVault, slot);
const holdings = await this.getVaultHoldings(vault, slot);
const sharesIssued = new Decimal(vault.sharesIssued.toString()!).div(
new Decimal(vault.sharesMintDecimals.toString())
);
console.log('Name: ', vaultName);
console.log('Shares issued: ', sharesIssued);
holdings.print();
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: KaminoVaultConfig
): Promise<{ vault: TransactionSigner; lut: Address; initVaultIxs: InitVaultIxs }> {
const vaultState = await generateKeyPairSigner();
const size = BigInt(VaultState.layout.span + 8);
const createVaultIx = getCreateAccountInstruction({
payer: vaultConfig.admin,
space: size,
lamports: await this.getConnection().getMinimumBalanceForRentExemption(size).send(),
programAddress: this._kaminoVaultProgramId,
newAccount: vaultState,
});
const [slot, [tokenVault], [baseVaultAuthority], [sharesMint]] = await Promise.all([
this.getConnection().getSlot({ commitment: 'finalized' }).send(),
getProgramDerivedAddress({
seeds: [Buffer.from(TOKEN_VAULT_SEED), addressEncoder.encode(vaultState.address)],
programAddress: this._kaminoVaultProgramId,
}),
getProgramDerivedAddress({
seeds: [Buffer.from(BASE_VAULT_AUTHORITY_SEED), addressEncoder.encode(vaultState.address)],
programAddress: this._kaminoVaultProgramId,
}),
getProgramDerivedAddress({
seeds: [Buffer.from(SHARES_SEED), addressEncoder.encode(vaultState.address)],
programAddress: this._kaminoVaultProgramId,
}),
]);
let adminTokenAccount: Address;
const prerequisiteIxs: Instruction[] = [];
const cleanupIxs: Instruction[] = [];
if (vaultConfig.tokenMint === WRAPPED_SOL_MINT) {
const { wsolAta, createAtaIxs, closeAtaIxs } = await createWsolAtaIfMissing(
this.getConnection(),
new Decimal(VAULT_INITIAL_DEPOSIT),
vaultConfig.admin
);
adminTokenAccount = wsolAta;
prerequisiteIxs.push(...createAtaIxs);
cleanupIxs.push(...closeAtaIxs);
} else {
adminTokenAccount = (
await findAssociatedTokenPda({
mint: vaultConfig.tokenMint,
tokenProgram: vaultConfig.tokenMintProgramId,
owner: vaultConfig.admin.address,
})
)[0];
}
const initVaultAccounts: InitVaultAccounts = {
adminAuthority: vaultConfig.admin,
vaultState: vaultState.address,
baseTokenMint: vaultConfig.tokenMint,
tokenVault,
baseVaultAuthority,
sharesMint,
systemProgram: SYSTEM_PROGRAM_ADDRESS,
rent: SYSVAR_RENT_ADDRESS,
tokenProgram: vaultConfig.tokenMintProgramId,
sharesTokenProgram: TOKEN_PROGRAM_ADDRESS,
adminTokenAccount,
};
const initVaultIx = initVault(initVaultAccounts, undefined, this._kaminoVaultProgramId);
const createVaultFarm = await this.createVaultFarm(vaultConfig.admin, vaultState.address, sharesMint);
// create and set up the vault lookup table
const [createLUTIx, lut] = await initLookupTableIx(vaultConfig.admin, slot);
const accountsToBeInserted: Address[] = [
vaultConfig.admin.address,
vaultState.address,
vaultConfig.tokenMint,
vaultConfig.tokenMintProgramId,
baseVaultAuthority,
sharesMint,
SYSTEM_PROGRAM_ADDRESS,
SYSVAR_RENT_ADDRESS,
TOKEN_PROGRAM_ADDRESS,
this._kaminoLendProgramId,
SYSVAR_INSTRUCTIONS_ADDRESS,
createVaultFarm.farm.address,
FARMS_GLOBAL_CONFIG_MAINNET,
];
const insertIntoLUTIxs = await insertIntoLookupTableIxs(
this.getConnection(),
vaultConfig.admin,
lut,
accountsToBeInserted,
[]
);
const setLUTIx = this.updateUninitialisedVaultConfigIx(
vaultConfig.admin,
vaultState.address,
new VaultConfigField.LookupTable(),
lut.toString()
);
const ixs = [createVaultIx, initVaultIx, setLUTIx];
if (vaultConfig.getPerformanceFeeBps() > 0) {
const setPerformanceFeeIx = this.updateUninitialisedVaultConfigIx(
vaultConfig.admin,
vaultState.address,
new VaultConfigField.PerformanceFeeBps(),
vaultConfig.getPerformanceFeeBps().toString()
);
ixs.push(setPerformanceFeeIx);
}
if (vaultConfig.getManagementFeeBps() > 0) {
const setManagementFeeIx = this.updateUninitialisedVaultConfigIx(
vaultConfig.admin,
vaultState.address,
new VaultConfigField.ManagementFeeBps(),
vaultConfig.getManagementFeeBps().toString()
);
ixs.push(setManagementFeeIx);
}
if (vaultConfig.name && vaultConfig.name.length > 0) {
const setNameIx = this.updateUninitialisedVaultConfigIx(
vaultConfig.admin,
vaultState.address,
new VaultConfigField.Name(),
vaultConfig.name
);
ixs.push(setNameIx);
}
const setFarmIx = this.updateUninitialisedVaultConfigIx(
vaultConfig.admin,
vaultState.address,
new VaultConfigField.Farm(),
createVaultFarm.farm.address
);
const metadataIx = await this.getSetSharesMetadataIx(
this.getConnection(),
vaultConfig.admin,
vaultState.address,
sharesMint,
baseVaultAuthority,
vaultConfig.vaultTokenSymbol,
vaultConfig.vaultTokenName
);
return {
vault: vaultState,
lut,
initVaultIxs: {
createAtaIfNeededIxs: prerequisiteIxs,
initVaultIxs: ixs,
createLUTIx,
populateLUTIxs: insertIntoLUTIxs,
cleanupIxs,
initSharesMetadataIx: metadataIx,
createVaultFarm,
setFarmToVaultIx: setFarmIx,
},
};
}
/**
* This method creates a farm for a vault
* @param signer - the signer of the transaction
* @param vaultSharesMint - the mint of the vault shares
* @param vaultAddress - the address of the vault (it doesn't need to be already initialized)
* @returns a struct with the farm, the setup farm ixs and the update farm ixs
*/
async createVaultFarm(
signer: TransactionSigner,
vaultAddress: Address,
vaultSharesMint: Address
): Promise<CreateVaultFarm> {
const farmsSDK = new Farms(this._rpc);
const farm = await generateKeyPairSigner();
const ixs = await farmsSDK.createFarmIxs(signer, farm, FARMS_GLOBAL_CONFIG_MAINNET, vaultSharesMint);
const updatePendingFarmAdminIx = await farmsSDK.updateFarmConfigIx(
signer,
farm.address,
DEFAULT_PUBLIC_KEY,
new FarmConfigOption.UpdatePendingFarmAdmin(),
FARMS_ADMIN_MAINNET,
undefined,
undefined,
true
);
const updateFarmVaultIdIx = await farmsSDK.updateFarmConfigIx(
signer,
farm.address,
DEFAULT_PUBLIC_KEY,
new FarmConfigOption.UpdateVaultId(),
vaultAddress,
undefined,
undefined,
true
);
return {
farm,
setupFarmIxs: ixs,
updateFarmIxs: [updatePendingFarmAdminIx, updateFarmVaultIdIx],
};
}
/**
* This method creates an instruction to set the shares metadata for a vault
* @param rpc
* @param vaultAdmin
* @param vault - the vault to set the shares metadata for
* @param sharesMint
* @param baseVaultAuthority
* @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(
rpc: Rpc<SolanaRpcApi>,
vaultAdmin: TransactionSigner,
vault: Address,
sharesMint: Address,
baseVaultAuthority: Address,
tokenName: string,
extraName: string
) {
const [sharesMintMetadata] = await getKVaultSharesMetadataPda(sharesMint);
const { name, symbol, uri } = resolveMetadata(sharesMint, extraName, tokenName);
const ix = !(await fetchEncodedAccount(rpc, sharesMintMetadata, { commitment: 'processed' })).exists
? await getInitializeKVaultSharesMetadataIx(vaultAdmin, vault, sharesMint, baseVaultAuthority, name, symbol, uri)
: await getUpdateSharesMetadataIx(vaultAdmin, vault, sharesMint, baseVaultAuthority, name, symbol, uri);
return ix;
}
/**
* This method updates the vault reserve allocation config 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 [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 updateReserveAllocationIxs(
vault: KaminoVault,
reserveAllocationConfig: ReserveAllocationConfig,
vaultAdminAuthority?: TransactionSigner
): Promise<UpdateReserveAllocationIxs> {
const vaultState: VaultState = await vault.getState();
const reserveState: Reserve = reserveAllocationConfig.getReserveState();
const cTokenVault = await getCTokenVaultPda(
vault.address,
reserveAllocationConfig.getReserveAddress(),
this._kaminoVaultProgramId
);
const vaultAdmin = parseVaultAdmin(vaultState, vaultAdminAuthority);
const updateReserveAllocationAccounts: UpdateReserveAllocationAccounts = {
signer: vaultAdmin,
vaultState: vault.address,
baseVaultAuthority: vaultState.baseVaultAuthority,
reserveCollateralMint: reserveState.collateral.mintPubkey,
reserve: reserveAllocationConfig.getReserveAddress(),
ctokenVault: cTokenVault,
systemProgram: SYSTEM_PROGRAM_ADDRESS,
rent: SYSVAR_RENT_ADDRESS,
reserveCollateralTokenProgram: TOKEN_PROGRAM_ADDRESS,
};
const updateReserveAllocationArgs: UpdateReserveAllocationArgs = {
weight: new BN(reserveAllocationConfig.targetAllocationWeight),
cap: new BN(reserveAllocationConfig.getAllocationCapLamports().floor().toString()),
};
const updateReserveAllocationIx = updateReserveAllocation(
updateReserveAllocationArgs,
updateReserveAllocationAccounts,
undefined,
this._kaminoVaultProgramId
);
const accountsToAddToLut = [
reserveAllocationConfig.getReserveAddress(),
cTokenVault,
...this.getReserveAccountsToInsertInLut(reserveState),
];
const [lendingMarketAuth] = await lendingMarketAuthPda(reserveState.lendingMarket, this._kaminoLendProgramId);
accountsToAddToLut.push(lendingMarketAuth);
const insertIntoLutIxs = await insertIntoLookupTableIxs(
this.getConnection(),
vaultAdmin,
vaultState.vaultLookupTable,
accountsToAddToLut
);
const updateReserveAllocationIxs: UpdateReserveAllocationIxs = {
updateReserveAllocationIx,
updateLUTIxs: insertIntoLutIxs,
};
return updateReserveAllocationIxs;
}
/**
* 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: KaminoVault,
vaultAdminAuthority?: TransactionSigner,
unallocatedWeight?: BN,
unallocatedCap?: BN
) {
const vaultState = await vault.getState();
const unallocatedWeightToUse = unallocatedWeight ? unallocatedWeight : vaultState.unallocatedWeight;
const unallocatedCapToUse = unallocatedCap ? unallocatedCap : vaultState.unallocatedTokensCap;
const ixs: Instruction[] = [];
if (!unallocatedWeightToUse.eq(vaultState.unallocatedWeight)) {
const updateVaultUnallocatedWeightIx = await this.updateVaultConfigIxs(
vault,
new VaultConfigField.UnallocatedWeight(),
unallocatedWeightToUse.toString(),
vaultAdminAuthority
);
ixs.push(updateVaultUnallocatedWeightIx.updateVaultConfigIx);
}
if (!unallocatedCapToUse.eq(vaultState.unallocatedTokensCap)) {
const updateVaultUnallocatedCapIx = await this.updateVaultConfigIxs(
vault,
new VaultConfigField.UnallocatedTokensCap(),
unallocatedCapToUse.toString(),
vaultAdminAuthority
);
ixs.push(updateVaultUnallocatedCapIx.updateVaultConfigIx);
}
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: KaminoVault,
reserve: Address,
vaultAdminAuthority?: TransactionSigner
): Promise<WithdrawAndBlockReserveIxs> {
const vaultState = await vault.getState();
const reserveIsPartOfAllocation = vaultState.vaultAllocationStrategy.some(
(allocation) => allocation.reserve === reserve
);
const withdrawAndBlockReserveIxs: WithdrawAndBlockReserveIxs = {
updateReserveAllocationIxs: [],
investIxs: [],
};
if (!reserveIsPartOfAllocation) {
return withdrawAndBlockReserveIxs;
}
const reserveState = await Reserve.fetch(this.getConnection(), reserve);
if (reserveState === null) {
return withdrawAndBlockReserveIxs;
}
const reserveWithAddress: ReserveWithAddress = {
address: reserve,
state: reserveState,
};
const reserveAllocationConfig = new ReserveAllocationConfig(reserveWithAddress, 0, new Decimal(0));
const admin = vaultAdminAuthority ? vaultAdminAuthority : noopSigner(vaultState.vaultAdminAuthority);
// update allocation to have 0 weight and 0 cap
const updateAllocIxs = await this.updateReserveAllocationIxs(vault, reserveAllocationConfig, admin);
const investIx = await this.investSingleReserveIxs(admin, 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 allocations (set weight and ctoken allocation to 0) and an a list of instructions to disinvest the funds in the reserves
*/
async withdrawEverythingFromAllReservesAndBlockInvest(
vault: KaminoVault,
vaultReservesMap?: Map<Address, KaminoReserve>,
payer?: TransactionSigner
): Promise<WithdrawAndBlockReserveIxs> {
const vaultState = await vault.getState();
const reserves = this.getVaultReserves(vaultState);
const withdrawAndBlockReserveIxs: WithdrawAndBlockReserveIxs = {
updateReserveAllocationIxs: [],
investIxs: [],
};
if (!vaultReservesMap) {
vaultReservesMap = await this.loadVaultReserves(vaultState);
}
for (const reserve of reserves) {
const reserveWithAddress: ReserveWithAddress = {
address: reserve,
state: vaultReservesMap.get(reserve)!.state,
};
const reserveAllocationConfig = new ReserveAllocationConfig(reserveWithAddress, 0, new Decimal(0));
// update allocation to have 0 weight and 0 cap
const updateAllocIxs = await this.updateReserveAllocationIxs(vault, reserveAllocationConfig, payer);
withdrawAndBlockReserveIxs.updateReserveAllocationIxs.push(updateAllocIxs.updateReserveAllocationIx);
}
const investPayer = payer ? payer : noopSigner(vaultState.vaultAdminAuthority);
const investIxs = await this.investAllReservesIxs(investPayer, vault, true);
withdrawAndBlockReserveIxs.investIxs = investIxs;
return withdrawAndBlockReserveIxs;
}
/**
* 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 [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: KaminoVault,
vaultReservesMap?: Map<Address, KaminoReserve>,
payer?: TransactionSigner
): Promise<DisinvestAllReservesIxs> {
const vaultState = await vault.getState();
const reserves = this.getVaultReserves(vaultState);
const disinvestAllReservesIxs: DisinvestAllReservesIxs = {
updateReserveAllocationIxs: [],
investIxs: [],
};
if (!vaultReservesMap) {
vaultReservesMap = await this.loadVaultReserves(vaultState);
}
for (const reserve of reserves) {
const reserveWithAddress: ReserveWithAddress = {
address: reserve,
state: vaultReservesMap.get(reserve)!.state,
};
const existingReserveAllocation = vaultState.vaultAllocationStrategy.find(
(allocation) => allocation.reserve === reserve
);
if (!existingReserveAllocation) {
continue;
}
const reserveAllocationConfig = new ReserveAllocationConfig(
reserveWithAddress,
0,
new Decimal(existingReserveAllocation.tokenAllocationCap.toString())
);
// update allocation to have 0 weight and 0 cap
const updateAllocIxs = await this.updateReserveAllocationIxs(vault, reserveAllocationConfig, payer);
disinvestAllReservesIxs.updateReserveAllocationIxs.push(updateAllocIxs.updateReserveAllocationIx);
}
const investPayer = payer ? payer : noopSigner(vaultState.vaultAdminAuthority);
const investIxs = await this.investAllReservesIxs(investPayer, vault, true);
disinvestAllReservesIxs.investIxs = investIxs;
return disinvestAllReservesIxs;
}
/**
* 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: KaminoVault,
reserve: Address,
vaultAdminAuthority?: TransactionSigner
): Promise<Instruction | undefined> {
const vaultState = await vault.getState();
const vaultAdmin = parseVaultAdmin(vaultState, vaultAdminAuthority);
const reserveIsPartOfAllocation = vaultState.vaultAllocationStrategy.some(
(allocation) => allocation.reserve === reserve
);
if (!reserveIsPartOfAllocation) {
return undefined;
}
const accounts: RemoveAllocationAccounts = {
vaultAdminAuthority: vaultAdmin,
vaultState: vault.address,
reserve,
};
return 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 [vaultAdminAuthority] 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
* @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: KaminoVault,
mode: VaultConfigFieldKind,
value: string,
vaultAdminAuthority?: TransactionSigner,
lutIxsSigner?: TransactionSigner,
skipLutUpdate: boolean = false
): Promise<UpdateVaultConfigIxs> {
const vaultState: VaultState = await vault.getState();
const admin = parseVaultAdmin(vaultState, vaultAdminAuthority);
const updateVaultConfigAccs: UpdateVaultConfigAccounts = {
vaultAdminAuthority: admin,
vaultState: vault.address,
klendProgram: this._kaminoLendProgramId,
};
if (vaultAdminAuthority) {
updateVaultConfigAccs.vaultAdminAuthority = vaultAdminAuthority;
}
const updateVaultConfigArgs: UpdateVaultConfigArgs = {
entry: mode,
data: Buffer.from([0]),
};
if (isNaN(+value) || value === DEFAULT_PUBLIC_KEY) {
if (mode.kind === new VaultConfigField.Name().kind) {
const data = Array.from(this.encodeVaultName(value));
updateVaultConfigArgs.data = Buffer.from(data);
} else {
const data = address(value);
updateVaultConfigArgs.data = Buffer.from(addressEncoder.encode(data));
}
} 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 updateVaultConfigIx = updateVaultConfig(
updateVaultConfigArgs,
updateVaultConfigAccs,
undefined,
this._kaminoVaultProgramId
);
updateVaultConfigIx = this.appendRemainingAccountsForVaultReserves(
updateVaultConfigIx,
vaultReserves,
vaultReservesState
);
const updateLUTIxs: Instruction[] = [];
if (!skipLutUpdate) {
const lutIxsSignerAccount = lutIxsSigner ? lutIxsSigner : admin;
if (mode.kind === new VaultConfigField.PendingVaultAdmin().kind) {
const newPubkey = address(value);
const insertIntoLutIxs = await insertIntoLookupTableIxs(
this.getConnection(),
lutIxsSignerAccount,
vaultState.vaultLookupTable,
[newPubkey]
);
updateLUTIxs.push(...insertIntoLutIxs);
} else if (mode.kind === new VaultConfigField.Farm().kind) {
const keysToAddToLUT = [address(value)];
// if the farm already exist we want to read its state to add it to the LUT
try {
const farmState = await FarmState.fetch(this.getConnection(), keysToAddToLUT[0]);
keysToAddToLUT.push(
farmState!.farmVault,
farmState!.farmVaultsAuthority,
farmState!.token.mint,
farmState!.scopePrices,
farmState!.globalConfig
);
const insertIntoLutIxs = await insertIntoLookupTableIxs(
this.getConnection(),
lutIxsSignerAccount,
vaultState.vaultLookupTable,
keysToAddToLUT
);
updateLUTIxs.push(...insertIntoLutIxs);
} catch (error) {
console.log(`Error fetching farm ${keysToAddToLUT[0].toString()} state`, error);
}
}
}
const updateVaultConfigIxs: 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
* @param [vaultAdminAuthority] - vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
* @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
* @returns - a struct that contains the instruction to update the farm and an optional list of instructions to update the lookup table
*/
async setVaultFarmIxs(
vault: KaminoVault,
farm: Address,
errorOnOverride: boolean = true,
vaultAdminAuthority?: TransactionSigner,
lutIxsSigner?: TransactionSigner,
skipLutUpdate: boolean = false
): Promise<UpdateVaultConfigIxs> {
const vaultHasFarm = await vault.hasFarm();
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 VaultConfigField.Farm(),
farm,
vaultAdminAuthority,
lutIxsSigner,
skipLutUpdate
);
}
/**
* This method updates the vault config for a vault that
* @param admin - address of vault to be updated
* @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
*/
private updateUninitialisedVaultConfigIx(
admin: TransactionSigner,
vault: Address,
mode: VaultConfigFieldKind,
value: string
): Instruction {
const updateVaultConfigAccs: UpdateVaultConfigAccounts = {
vaultAdminAuthority: admin,
vaultState: vault,
klendProgram: this._kaminoLendProgramId,
};
const updateVaultConfigArgs: UpdateVaultConfigArgs = {
entry: mode,
data: Buffer.from([0]),
};
if (isNaN(+value)) {
if (mode.kind === new VaultConfigField.Name().kind) {
const data = Array.from(this.encodeVaultName(value));
updateVaultConfigArgs.data = Buffer.from(data);
} else {
const data = address(value);
updateVaultConfigArgs.data = Buffer.from(addressEncoder.encode(data));
}
} else {
const buffer = Buffer.alloc(8);
buffer.writeBigUInt64LE(BigInt(value.toString()));
updateVaultConfigArgs.data = buffer;
}
const updateVaultConfigIx = updateVaultConfig(
updateVaultConfigArgs,
updateVaultConfigAccs,
undefined,
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
* @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: KaminoVault,
pendingAdmin?: TransactionSigner
): Promise<AcceptVaultOwnershipIxs> {
const vaultState: VaultState = await vault.getState();
const signer = parseVaultPendingAdmin(vaultState, pendingAdmin);
const acceptOwneshipAccounts: UpdateAdminAccounts = {
pendingAdmin: signer,
vaultState: vault.address,
};
const acceptVaultOwnershipIx = updateAdmin(acceptOwneshipAccounts, undefined, this._kaminoVaultProgramId);
// read the current LUT and create a new one for the new admin and backfill it
const accountsInExistentLUT = (await getAccountsInLut(this.getConnection(), vaultState.vaultLookupTable)).filter(
(account) => account !== vaultState.vaultAdminAuthority
);
const lutIxs: Instruction[] = [];
const [initNewLutIx, newLut] = await initLookupTableIx(
signer,
await this.getConnection().getSlot({ commitment: 'finalized' }).send()
);
const insertIntoLUTIxs = await insertIntoLookupTableIxs(
this.getConnection(),
signer,
newLut,
accountsInExistentLUT,
[]
);
lutIxs.push(...insertIntoLUTIxs);
const updateVaultConfigIxs = await this.updateVaultConfigIxs(
vault,
new VaultConfigField.LookupTable(),
newLut.toString(),
signer
);
lutIxs.push(updateVaultConfigIxs.updateVaultConfigIx);
lutIxs.push(...updateVaultConfigIxs.updateLUTIxs);
const acceptVaultOwnershipIxs: AcceptVaultOwnershipIxs = {
acceptVaultOwnershipIx,
initNewLUTIx: 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
* @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: KaminoVault,
maxAmountToGiveUp: Decimal,
vaultAdminAuthority?: TransactionSigner
): Promise<Instruction> {
const vaultState: VaultState = await vault.getState();
const vaultAdmin = parseVaultAdmin(vaultState, vaultAdminAuthority);
const giveUpPendingFeesAccounts: GiveUpPendingFeesAccounts = {
vaultAdminAuthority: vaultAdmin,
vaultState: vault.address,
klendProgram: this._kaminoLendProgramId,
};
const maxAmountToGiveUpLamports = numberToLamportsDecimal(
maxAmountToGiveUp,
vaultState.tokenMintDecimals.toNumber()
);
const giveUpPendingFeesArgs: GiveUpPendingFeesArgs = {
maxAmountToGiveUp: new BN(maxAmountToGiveUpLamports.toString()),
};
return giveUpPendingFees(giveUpPendingFeesArgs, giveUpPendingFeesAccounts, undefined, this._kaminoVaultProgramId);
}
/**
* This method withdraws all the pending fees from the vault to the owner's token ATA
* @param authority - vault admin
* @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
* @param [vaultAdminAuthority] - vault admin - a noop vaultAdminAuthority is provided when absent for multisigs
* @returns - list of instructions to withdraw all pending fees, including the ATA creation instructions if needed
*/
async withdrawPendingFeesIxs(
vault: KaminoVault,
slot: Slot,
vaultReservesMap?: Map<Address, KaminoReserve>,
vaultAdminAuthority?: TransactionSigner
): Promise<Instruction[]> {
const vaultState: VaultState = await vault.getState();
const vaultAdmin = parseVaultAdmin(vaultState, vaultAdminAuthority);
const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState);
const [{ ata: adminTokenAta, createAtaIx }] = await createAtasIdempotent(vaultAdmin, [
{
mint: vaultState.tokenMint,
tokenProgram: vaultState.tokenProgram,
},
]);
const tokensToWithdraw = new Fraction(vaultState.pendingFeesSf).toDecimal();
let tokenLeftToWithdraw = tokensToWithdraw;
tokenLeftToWithdraw = tokenLeftToWithdraw.sub(new Decimal(vaultState.tokenAvailable.toString()));
const reservesToWithdraw: Address[] = [];
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 Map(
[...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 Reserve.fetchMultiple(
this.getConnection(),
reservesToWithdraw,
this._kaminoLendProgramId
);
const withdrawIxs: Instruction[] = await Promise.all(
reservesToWithdraw.map(async (reserve, index) => {
if (reserveStates[index] === null) {
throw new Error(`Reserve ${reserve} not found`);
}
const reserveState = reserveStates[index]!;
const marketAddress = reserveState.lendingMarket;
return this.withdrawPendingFeesIx(
vaultAdmin,
vault,
vaultState,
marketAddress,
{ address: reserve, state: reserveState },
adminTokenAta
);
})
);
return [createAtaIx, ...withdrawIxs];
}
// async closeVaultIx(vault: KaminoVault): Promise<Instruction> {
// 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: TransactionSigner,
vault: KaminoVault,
tokenAmount: Decimal,
vaultReservesMap?: Map<Address, KaminoReserve>,
farmState?: FarmState
): Promise<DepositIxs> {
const vaultState = await vault.getState();
const tokenProgramID = vaultState.tokenProgram;
const userTokenAta = await getAssociatedTokenAddress(vaultState.tokenMint, user.address, tokenProgramID);
const createAtasIxs: Instruction[] = [];
const closeAtasIxs: Instruction[] = [];
if (vaultState.tokenMint === WRAPPED_SOL_MINT) {
const [{ ata: wsolAta, createAtaIx: createWsolAtaIxn }] = await createAtasIdempotent(user, [
{
mint: WRAPPED_SOL_MINT,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
},
]);
createAtasIxs.push(createWsolAtaIxn);
const transferWsolIxs = getTransferWsolIxs(
user,
wsolAta,
lamports(
BigInt(numberToLamportsDecimal(tokenAmount, vaultState.tokenMintDecimals.toNumber()).ceil().toString())
)
);
createAtasIxs.push(...transferWsolIxs);
}
const [{ ata: userSharesAta, createAtaIx: createSharesAtaIxs }] = await createAtasIdempotent(user, [
{
mint: vaultState.sharesMint,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
},
]);
createAtasIxs.push(createSharesAtaIxs);
const eventAuthority = await getEventAuthorityPda(this._kaminoVaultProgramId);
const depositAccounts: DepositAccounts = {
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: TOKEN_PROGRAM_ADDRESS,
eventAuthority: eventAuthority,
program: this._kaminoVaultProgramId,
};
const depositArgs: DepositArgs = {
maxAmount: new BN(
numberToLamportsDecimal(tokenAmount, vaultState.tokenMintDecimals.toNumber()).floor().toString()
),
};
let depositIx = deposit(depositArgs, depositAccounts, undefined, this._kaminoVaultProgramId);
const vaultReserves = this.getVaultReserves(vaultState);
const vaultReservesState = vaultReservesMap ? vaultReservesMap : await this.loadVaultReserves(vaultState);
depositIx = this.appendRemainingAccountsForVaultReserves(depositIx, vaultReserves, vaultReservesState);
const depositIxs: 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())) {
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: TransactionSigner,
vault: KaminoVault,
sharesAmount?: Decimal,
farmState?: FarmState
): Promise<Instruction[]> {
const vaultState = await vault.getState();
let sharesToStakeLamports = new Decimal(U64_MAX);
if (sharesAmount) {
sharesToStakeLamports = 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) || !(await vault.hasFarm())) {
return [];
}
// returns the ix to create the farm state account if needed and the ix to stake the shares
return 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: TransactionSigner,
vault: KaminoVault,
shareAmountToWithdraw: Decimal,
slot: Slot,
vaultReservesMap?: Map<Address, KaminoReserve>,
farmState?: FarmState
): Promise<WithdrawIxs> {
const vaultState = await vault.getState();
const hasFarm = await v