UNPKG

@kamino-finance/klend-sdk

Version:

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

1,569 lines (1,440 loc) 133 kB
import { Connection, PublicKey, RpcResponseAndContext, SimulatedTransactionResponse, SystemProgram, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_RENT_PUBKEY, Transaction, TransactionInstruction, TransactionSignature, } from '@solana/web3.js'; import { ASSOCIATED_TOKEN_PROGRAM_ID, NATIVE_MINT, TOKEN_PROGRAM_ID, createCloseAccountInstruction, createSyncNativeInstruction, } from '@solana/spl-token'; import BN from 'bn.js'; import Decimal from 'decimal.js'; import { borrowObligationLiquidity, depositAndWithdraw, borrowObligationLiquidityV2, depositObligationCollateral, depositObligationCollateralV2, depositReserveLiquidity, depositReserveLiquidityAndObligationCollateral, depositReserveLiquidityAndObligationCollateralV2, initObligation, initObligationFarmsForReserve, InitObligationFarmsForReserveAccounts, InitObligationFarmsForReserveArgs, initReferrerTokenState, initUserMetadata, liquidateObligationAndRedeemReserveCollateral, liquidateObligationAndRedeemReserveCollateralV2, redeemReserveCollateral, refreshObligation, refreshObligationFarmsForReserve, RefreshObligationFarmsForReserveAccounts, RefreshObligationFarmsForReserveArgs, refreshReserve, repayAndWithdrawAndRedeem, repayObligationLiquidity, repayObligationLiquidityV2, requestElevationGroup, RequestElevationGroupAccounts, RequestElevationGroupArgs, setObligationOrder, withdrawObligationCollateralAndRedeemReserveCollateral, withdrawObligationCollateralAndRedeemReserveCollateralV2, withdrawReferrerFees, } from '../idl_codegen/instructions'; import { buildComputeBudgetIx, createAssociatedTokenAccountIdempotentInstruction, ObligationType, U64_MAX, referrerTokenStatePda, userMetadataPda, createLookupTableIx, isNotNullPubkey, PublicKeySet, getAssociatedTokenAddress, ScopePriceRefreshConfig, createAtasIdempotent, SOL_PADDING_FOR_INTEREST, obligationFarmStatePda, } from '../utils'; import { getTokenIdsForScopeRefresh, KaminoMarket } from './market'; import { isKaminoObligation, KaminoObligation } from './obligation'; import { KaminoReserve } from './reserve'; import { ReserveFarmKind } from '../idl_codegen/types'; import { farmsId } from '@kamino-finance/farms-sdk'; import { Reserve } from '../idl_codegen/accounts'; import { VanillaObligation } from '../utils/ObligationType'; import { PROGRAM_ID } from '../lib'; import { Scope } from '@kamino-finance/scope-sdk'; import { ObligationOrderAtIndex } from './obligationOrder'; export type ActionType = | 'deposit' | 'borrow' | 'withdraw' | 'repay' | 'mint' | 'redeem' | 'depositCollateral' | 'liquidate' | 'depositAndBorrow' | 'repayAndWithdraw' | 'refreshObligation' | 'requestElevationGroup' | 'withdrawReferrerFees' | 'repayAndWithdrawV2' | 'depositAndWithdraw'; export type AuxiliaryIx = 'setup' | 'inBetween' | 'cleanup'; export class KaminoAction { kaminoMarket: KaminoMarket; reserve: KaminoReserve; outflowReserve: KaminoReserve | undefined; owner: PublicKey; payer: PublicKey; obligation: KaminoObligation | ObligationType; referrer: PublicKey; /** * Null unless the obligation is not passed */ obligationType: ObligationType | null = null; mint: PublicKey; secondaryMint?: PublicKey; positions?: number; amount: BN; outflowAmount?: BN; computeBudgetIxs: Array<TransactionInstruction>; computeBudgetIxsLabels: Array<string>; setupIxs: Array<TransactionInstruction>; setupIxsLabels: Array<string>; inBetweenIxs: Array<TransactionInstruction>; inBetweenIxsLabels: Array<string>; lendingIxs: Array<TransactionInstruction>; lendingIxsLabels: Array<string>; cleanupIxs: Array<TransactionInstruction>; cleanupIxsLabels: Array<string>; refreshFarmsCleanupTxnIxs: Array<TransactionInstruction>; refreshFarmsCleanupTxnIxsLabels: Array<string>; depositReserves: Array<PublicKey>; borrowReserves: Array<PublicKey>; preLoadedDepositReservesSameTx: Array<PublicKey>; currentSlot: number; private constructor( kaminoMarket: KaminoMarket, owner: PublicKey, obligation: KaminoObligation | ObligationType, mint: PublicKey, positions: number, amount: string | BN, depositReserves: Array<PublicKey>, borrowReserves: Array<PublicKey>, reserveState: KaminoReserve, currentSlot: number, secondaryMint?: PublicKey, outflowReserveState?: KaminoReserve, outflowAmount?: string | BN, referrer?: PublicKey, payer?: PublicKey ) { this.kaminoMarket = kaminoMarket; this.obligation = obligation; this.owner = owner; this.payer = payer ?? owner; this.amount = new BN(amount); this.mint = mint; this.positions = positions; this.computeBudgetIxs = []; this.computeBudgetIxsLabels = []; this.setupIxs = []; this.setupIxsLabels = []; this.inBetweenIxs = []; this.inBetweenIxsLabels = []; this.lendingIxs = []; this.lendingIxsLabels = []; this.cleanupIxs = []; this.cleanupIxsLabels = []; this.refreshFarmsCleanupTxnIxs = []; this.refreshFarmsCleanupTxnIxsLabels = []; this.depositReserves = depositReserves; this.borrowReserves = borrowReserves; this.secondaryMint = secondaryMint; this.reserve = reserveState; this.outflowReserve = outflowReserveState; this.outflowAmount = outflowAmount ? new BN(outflowAmount) : undefined; this.preLoadedDepositReservesSameTx = []; this.referrer = referrer ? referrer : PublicKey.default; this.currentSlot = currentSlot; } static async initialize( action: ActionType, amount: string | BN, mint: PublicKey, owner: PublicKey, kaminoMarket: KaminoMarket, obligation: KaminoObligation | ObligationType, referrer: PublicKey = PublicKey.default, currentSlot: number = 0, payer?: PublicKey ) { const reserve = kaminoMarket.getReserveByMint(mint); if (reserve === undefined) { throw new Error(`Reserve ${mint} not found in market ${kaminoMarket.getAddress().toBase58()}`); } const { kaminoObligation, depositReserves, borrowReserves, distinctReserveCount } = await KaminoAction.loadObligation(action, kaminoMarket, owner, reserve.address, obligation); const referrerKey = await this.getReferrerKey(kaminoMarket, owner, kaminoObligation, referrer); return new KaminoAction( kaminoMarket, owner, kaminoObligation || obligation, mint, distinctReserveCount, amount, depositReserves, borrowReserves, reserve, currentSlot, undefined, undefined, undefined, referrerKey, payer ); } private static getUserAccountAddresses(owner: PublicKey, reserve: Reserve) { const userTokenAccountAddress = getAssociatedTokenAddress( reserve.liquidity.mintPubkey, owner, true, reserve.liquidity.tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID ); const userCollateralAccountAddress = getAssociatedTokenAddress( reserve.collateral.mintPubkey, owner, true, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID ); return { userTokenAccountAddress, userCollateralAccountAddress }; } private static async loadObligation( action: ActionType, kaminoMarket: KaminoMarket, owner: PublicKey, reserve: PublicKey, obligation: KaminoObligation | ObligationType, outflowReserve?: PublicKey ) { let kaminoObligation: KaminoObligation | null; const depositReserves: Array<PublicKey> = []; const borrowReserves: Array<PublicKey> = []; if (obligation instanceof KaminoObligation) { kaminoObligation = obligation; } else { const obligationAddress = obligation.toPda(kaminoMarket.getAddress(), owner); kaminoObligation = await KaminoObligation.load(kaminoMarket, obligationAddress); } if (kaminoObligation !== null) { depositReserves.push(...[...kaminoObligation.deposits.keys()]); borrowReserves.push(...[...kaminoObligation.borrows.keys()]); } if (!outflowReserve && action === 'depositAndBorrow') { throw new Error(`Outflow reserve has not been set for depositAndBorrow`); } // Union of addresses const distinctReserveCount = new PublicKeySet<PublicKey>([ ...borrowReserves.map((e) => e), ...(action === 'borrow' ? [reserve] : []), ...(action === 'depositAndBorrow' ? [reserve] : []), ]).toArray().length + new PublicKeySet<PublicKey>([ ...depositReserves.map((e) => e), ...(action === 'deposit' ? [reserve] : []), ...(action === 'depositAndBorrow' ? [outflowReserve!] : []), ]).toArray().length; return { kaminoObligation, depositReserves, borrowReserves, distinctReserveCount, }; } static async buildRefreshObligationTxns( kaminoMarket: KaminoMarket, payer: PublicKey, obligation: KaminoObligation, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix currentSlot: number = 0 ) { // placeholder for action initialization const firstReserve = obligation.getDeposits()[0].reserveAddress; const firstKaminoReserve = kaminoMarket.getReserveByAddress(firstReserve); if (!firstKaminoReserve) { throw new Error(`Reserve ${firstReserve.toBase58()} not found`); } const axn = await KaminoAction.initialize( 'refreshObligation', '0', firstKaminoReserve?.getLiquidityMint(), obligation.state.owner, kaminoMarket, obligation, undefined, currentSlot ); if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } axn.addRefreshObligation(payer); return axn; } static async buildRequestElevationGroupTxns( kaminoMarket: KaminoMarket, payer: PublicKey, obligation: KaminoObligation, elevationGroup: number, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix currentSlot: number = 0 ) { const firstReserve = obligation.state.deposits.find( (x) => !x.depositReserve.equals(PublicKey.default) )!.depositReserve; const firstKaminoReserve = kaminoMarket.getReserveByAddress(firstReserve); if (!firstKaminoReserve) { throw new Error(`Reserve ${firstReserve.toBase58()} not found`); } const axn = await KaminoAction.initialize( 'requestElevationGroup', '0', firstKaminoReserve?.getLiquidityMint(), obligation.state.owner, kaminoMarket, obligation, undefined, currentSlot ); if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } axn.addRefreshObligation(payer); axn.addRequestElevationIx(elevationGroup, 'setup'); return axn; } static async buildDepositTxns( kaminoMarket: KaminoMarket, amount: string | BN, mint: PublicKey, owner: PublicKey, obligation: KaminoObligation | ObligationType, useV2Ixs: boolean, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas, requestElevationGroup: boolean = false, // to be requested *before* the deposit initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default, currentSlot: number = 0, overrideElevationGroupRequest: number | undefined = undefined // if set, when an elevationgroup request is made, it will use this value ) { const axn = await KaminoAction.initialize( 'deposit', amount, mint, owner, kaminoMarket, obligation, referrer, currentSlot ); const addInitObligationForFarm = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'deposit', includeAtaIxs, requestElevationGroup, addInitObligationForFarm, useV2Ixs, scopeRefreshConfig, initUserMetadata, undefined, overrideElevationGroupRequest ); if (useV2Ixs) { axn.addDepositIxV2(); } else { axn.addDepositIx(); } axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); return axn; } async addScopeRefreshIxs(scope: Scope, tokens: number[], feed: string = 'hubble') { this.setupIxsLabels.unshift(`refreshScopePrices`); this.setupIxs.unshift( await scope.refreshPriceListIx( { feed: feed, }, tokens ) ); } static async buildBorrowTxns( kaminoMarket: KaminoMarket, amount: string | BN, mint: PublicKey, owner: PublicKey, obligation: KaminoObligation | ObligationType, useV2Ixs: boolean, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas, requestElevationGroup: boolean = false, initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default, currentSlot: number = 0, overrideElevationGroupRequest: number | undefined = undefined // if set, when an elevationgroup request is made, it will use this value ) { const axn = await KaminoAction.initialize( 'borrow', amount, mint, owner, kaminoMarket, obligation, referrer, currentSlot ); const addInitObligationForFarm = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } if (!axn.referrer.equals(PublicKey.default)) { const referrerTokenState = referrerTokenStatePda( axn.referrer, axn.reserve.address, axn.kaminoMarket.programId )[0]; const account = await axn.kaminoMarket.getConnection().getAccountInfo(referrerTokenState); if (!account) { axn.addInitReferrerTokenStateIx(axn.reserve, referrerTokenState); } } await axn.addSupportIxs( 'borrow', includeAtaIxs, requestElevationGroup, addInitObligationForFarm, useV2Ixs, scopeRefreshConfig, initUserMetadata, undefined, overrideElevationGroupRequest ); if (useV2Ixs) { axn.addBorrowIxV2(); } else { axn.addBorrowIx(); } axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); return axn; } static async buildDepositReserveLiquidityTxns( kaminoMarket: KaminoMarket, amount: string | BN, mint: PublicKey, owner: PublicKey, obligation: KaminoObligation | ObligationType, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas requestElevationGroup: boolean = false, referrer: PublicKey = PublicKey.default, currentSlot: number = 0 ) { const axn = await KaminoAction.initialize( 'mint', amount, mint, owner, kaminoMarket, obligation, referrer, currentSlot ); const addInitObligationForFarm = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'mint', includeAtaIxs, requestElevationGroup, false, addInitObligationForFarm, scopeRefreshConfig, { skipInitialization: true, skipLutCreation: true } ); axn.addDepositReserveLiquidityIx(); axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); return axn; } static async buildRedeemReserveCollateralTxns( kaminoMarket: KaminoMarket, amount: string | BN, mint: PublicKey, owner: PublicKey, obligation: KaminoObligation | ObligationType, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas requestElevationGroup: boolean = false, referrer: PublicKey = PublicKey.default, currentSlot: number = 0 ) { const axn = await KaminoAction.initialize( 'redeem', amount, mint, owner, kaminoMarket, obligation, referrer, currentSlot ); const addInitObligationForFarm = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'redeem', includeAtaIxs, requestElevationGroup, false, addInitObligationForFarm, scopeRefreshConfig, { skipInitialization: true, skipLutCreation: true } ); axn.addRedeemReserveCollateralIx(); axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); return axn; } static async buildDepositObligationCollateralTxns( kaminoMarket: KaminoMarket, amount: string | BN, mint: PublicKey, owner: PublicKey, obligation: KaminoObligation | ObligationType, useV2Ixs: boolean, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas requestElevationGroup: boolean = false, initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default, currentSlot: number = 0 ) { const axn = await KaminoAction.initialize( 'depositCollateral', amount, mint, owner, kaminoMarket, obligation, referrer, currentSlot ); const addInitObligationForFarm = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'depositCollateral', includeAtaIxs, requestElevationGroup, addInitObligationForFarm, useV2Ixs, scopeRefreshConfig, initUserMetadata ); if (useV2Ixs) { axn.addDepositObligationCollateralIxV2(); } else { axn.addDepositObligationCollateralIx(); } axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); return axn; } static async buildDepositAndBorrowTxns( kaminoMarket: KaminoMarket, depositAmount: string | BN, depositMint: PublicKey, borrowAmount: string | BN, borrowMint: PublicKey, payer: PublicKey, obligation: KaminoObligation | ObligationType, useV2Ixs: boolean, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas, requestElevationGroup: boolean = false, initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default, currentSlot: number = 0 ) { const axn = await KaminoAction.initializeMultiTokenAction( kaminoMarket, 'depositAndBorrow', depositAmount, depositMint, borrowMint, payer, payer, obligation, borrowAmount, referrer, currentSlot ); const addInitObligationForFarmForDeposit = true; const addInitObligationForFarmForBorrow = false; const twoTokenAction = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } if (!axn.referrer.equals(PublicKey.default)) { const referrerTokenState = referrerTokenStatePda( axn.referrer, axn.outflowReserve!.address, axn.kaminoMarket.programId )[0]; const account = await axn.kaminoMarket.getConnection().getAccountInfo(referrerTokenState); if (!account) { axn.addInitReferrerTokenStateIx(axn.outflowReserve!, referrerTokenState); } } await axn.addSupportIxs( 'deposit', includeAtaIxs, requestElevationGroup, addInitObligationForFarmForDeposit, useV2Ixs, undefined, initUserMetadata, twoTokenAction ); if (useV2Ixs) { await axn.addDepositAndBorrowIxV2(); } else { await axn.addDepositAndBorrowIx(); } await axn.addInBetweenIxs( 'depositAndBorrow', includeAtaIxs, requestElevationGroup, addInitObligationForFarmForBorrow, useV2Ixs ); axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); // Create the scope refresh ix in here to ensure it's the first ix in the txn const allReserves = new PublicKeySet<PublicKey>([ ...axn.depositReserves, ...axn.borrowReserves, axn.reserve.address, ...(axn.outflowReserve ? [axn.outflowReserve.address] : []), ...(axn.preLoadedDepositReservesSameTx ? axn.preLoadedDepositReservesSameTx : []), ]).toArray(); const tokenIds = getTokenIdsForScopeRefresh(axn.kaminoMarket, allReserves); if (tokenIds.length > 0 && scopeRefreshConfig) { await axn.addScopeRefreshIxs(scopeRefreshConfig.scope, tokenIds, scopeRefreshConfig.scopeFeed); } return axn; } static async buildDepositAndWithdrawV2Txns( kaminoMarket: KaminoMarket, depositAmount: string | BN, depositMint: PublicKey, withdrawAmount: string | BN, withdrawMint: PublicKey, payer: PublicKey, currentSlot: number, obligation: KaminoObligation | ObligationType, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas, requestElevationGroup: boolean = false, initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default ) { const axn = await KaminoAction.initializeMultiTokenAction( kaminoMarket, 'depositAndWithdraw', depositAmount, depositMint, withdrawMint, payer, payer, obligation, withdrawAmount, referrer, currentSlot ); const addInitObligationForFarm = true; const twoTokenAction = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'depositAndWithdraw', includeAtaIxs, requestElevationGroup, addInitObligationForFarm, true, scopeRefreshConfig, initUserMetadata, twoTokenAction ); const withdrawCollateralAmount = axn.getWithdrawCollateralAmount(axn.outflowReserve!, axn.outflowAmount!); axn.addDepositAndWithdrawV2Ixs(withdrawCollateralAmount); return axn; } static async buildRepayAndWithdrawV2Txns( kaminoMarket: KaminoMarket, repayAmount: string | BN, repayMint: PublicKey, withdrawAmount: string | BN, withdrawMint: PublicKey, payer: PublicKey, currentSlot: number, obligation: KaminoObligation | ObligationType, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas, requestElevationGroup: boolean = false, initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default ) { const axn = await KaminoAction.initializeMultiTokenAction( kaminoMarket, 'repayAndWithdrawV2', repayAmount, repayMint, withdrawMint, payer, payer, obligation, withdrawAmount, referrer, currentSlot ); const addInitObligationForFarm = true; const twoTokenAction = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'repayAndWithdrawV2', includeAtaIxs, requestElevationGroup, addInitObligationForFarm, true, scopeRefreshConfig, initUserMetadata, twoTokenAction ); const withdrawCollateralAmount = axn.getWithdrawCollateralAmount(axn.outflowReserve!, axn.outflowAmount!); axn.addRepayAndWithdrawV2Ixs(withdrawCollateralAmount); return axn; } static async buildRepayAndWithdrawTxns( kaminoMarket: KaminoMarket, repayAmount: string | BN, repayMint: PublicKey, withdrawAmount: string | BN, withdrawMint: PublicKey, payer: PublicKey, currentSlot: number, obligation: KaminoObligation | ObligationType, useV2Ixs: boolean, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas, requestElevationGroup: boolean = false, initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default ) { const axn = await KaminoAction.initializeMultiTokenAction( kaminoMarket, 'repayAndWithdraw', repayAmount, repayMint, withdrawMint, payer, payer, obligation, withdrawAmount, referrer, currentSlot ); const addInitObligationForFarmForRepay = true; const addInitObligationForFarmForWithdraw = false; const twoTokenAction = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'repay', includeAtaIxs, requestElevationGroup, addInitObligationForFarmForRepay, useV2Ixs, undefined, initUserMetadata, twoTokenAction ); const withdrawCollateralAmount = axn.getWithdrawCollateralAmount(axn.outflowReserve!, axn.outflowAmount!); if (useV2Ixs) { await axn.addRepayAndWithdrawIxsV2(withdrawCollateralAmount); } else { await axn.addRepayAndWithdrawIxs(withdrawCollateralAmount); } await axn.addInBetweenIxs( 'repayAndWithdraw', includeAtaIxs, requestElevationGroup, addInitObligationForFarmForWithdraw, useV2Ixs ); axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); // Create the scope refresh ix in here to ensure it's the first ix in the txn const allReserves = new PublicKeySet<PublicKey>([ ...axn.depositReserves, ...axn.borrowReserves, axn.reserve.address, ...(axn.outflowReserve ? [axn.outflowReserve.address] : []), ...(axn.preLoadedDepositReservesSameTx ? axn.preLoadedDepositReservesSameTx : []), ]).toArray(); const tokenIds = getTokenIdsForScopeRefresh(axn.kaminoMarket, allReserves); if (tokenIds.length > 0 && scopeRefreshConfig) { await axn.addScopeRefreshIxs(scopeRefreshConfig.scope, tokenIds, scopeRefreshConfig.scopeFeed); } return axn; } static async buildWithdrawTxns( kaminoMarket: KaminoMarket, amount: string | BN, mint: PublicKey, owner: PublicKey, obligation: KaminoObligation | ObligationType, useV2Ixs: boolean, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas, requestElevationGroup: boolean = false, // to be requested *after* the withdraw initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default, currentSlot: number = 0, overrideElevationGroupRequest?: number, // Optional customizations which may be needed if the obligation was mutated by some previous ix. obligationCustomizations?: { // Any newly-added deposit reserves. addedDepositReserves?: PublicKey[]; } ) { const axn = await KaminoAction.initialize( 'withdraw', amount, mint, owner, kaminoMarket, obligation, referrer, currentSlot ); const addInitObligationForFarm = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } axn.depositReserves.push(...(obligationCustomizations?.addedDepositReserves || [])); await axn.addSupportIxs( 'withdraw', includeAtaIxs, requestElevationGroup, addInitObligationForFarm, useV2Ixs, scopeRefreshConfig, initUserMetadata, false, overrideElevationGroupRequest ); const collateralAmount = axn.getWithdrawCollateralAmount(axn.reserve, axn.amount); if (useV2Ixs) { await axn.addWithdrawIxV2(collateralAmount); } else { await axn.addWithdrawIx(collateralAmount); } axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); return axn; } /** * * @param kaminoMarket * @param amount * @param mint * @param owner * @param obligation - obligation to repay or the PDA seeds * @param currentSlot * @param payer - if not set then owner is used * @param extraComputeBudget - if > 0 then adds the ix * @param includeAtaIxs - if true it includes create and close wsol and token atas * @param requestElevationGroup * @param includeUserMetadata - if true it includes user metadata * @param referrer */ static async buildRepayTxns( kaminoMarket: KaminoMarket, amount: string | BN, mint: PublicKey, owner: PublicKey, obligation: KaminoObligation | ObligationType, useV2Ixs: boolean, scopeRefreshConfig: ScopePriceRefreshConfig | undefined, currentSlot: number, payer: PublicKey | undefined = undefined, extraComputeBudget: number = 1_000_000, includeAtaIxs: boolean = true, requestElevationGroup: boolean = false, initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default ) { const axn = await KaminoAction.initialize( 'repay', amount, mint, owner, kaminoMarket, obligation, referrer, currentSlot, payer ); const addInitObligationForFarm = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'repay', includeAtaIxs, requestElevationGroup, addInitObligationForFarm, useV2Ixs, scopeRefreshConfig, initUserMetadata ); if (useV2Ixs) { await axn.addRepayIxV2(); } else { await axn.addRepayIx(); } axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); return axn; } static async buildLiquidateTxns( kaminoMarket: KaminoMarket, amount: string | BN, minCollateralReceiveAmount: string | BN, repayTokenMint: PublicKey, withdrawTokenMint: PublicKey, liquidator: PublicKey, obligationOwner: PublicKey, obligation: KaminoObligation | ObligationType, useV2Ixs: boolean, scopeRefreshConfig: ScopePriceRefreshConfig | undefined = undefined, extraComputeBudget: number = 1_000_000, // if > 0 then adds the ix includeAtaIxs: boolean = true, // if true it includes create and close wsol and token atas, and creates all other token atas if they don't exist requestElevationGroup: boolean = false, initUserMetadata: { skipInitialization: boolean; skipLutCreation: boolean } = { skipInitialization: false, skipLutCreation: false, }, referrer: PublicKey = PublicKey.default, maxAllowedLtvOverridePercent: number = 0, currentSlot: number = 0 ) { const axn = await KaminoAction.initializeMultiTokenAction( kaminoMarket, 'liquidate', amount, repayTokenMint, withdrawTokenMint, liquidator, obligationOwner, obligation, minCollateralReceiveAmount, referrer, currentSlot ); const addInitObligationForFarm = true; if (extraComputeBudget > 0) { axn.addComputeBudgetIxn(extraComputeBudget); } await axn.addSupportIxs( 'liquidate', includeAtaIxs, requestElevationGroup, addInitObligationForFarm, useV2Ixs, scopeRefreshConfig, initUserMetadata ); if (useV2Ixs) { await axn.addLiquidateIxV2(maxAllowedLtvOverridePercent); } else { await axn.addLiquidateIx(maxAllowedLtvOverridePercent); } axn.addRefreshFarmsCleanupTxnIxsToCleanupIxs(); return axn; } static async buildWithdrawReferrerFeeTxns( owner: PublicKey, tokenMint: PublicKey, kaminoMarket: KaminoMarket, currentSlot: number = 0 ) { const { axn, createAtaIxs } = await KaminoAction.initializeWithdrawReferrerFees( tokenMint, owner, kaminoMarket, currentSlot ); axn.setupIxs.push(...createAtaIxs); axn.setupIxsLabels.push(`createAtasIxs[${axn.owner.toString()}]`); if (!axn.referrer.equals(PublicKey.default)) { const referrerTokenState = referrerTokenStatePda( axn.referrer, axn.reserve.address, axn.kaminoMarket.programId )[0]; const account = await axn.kaminoMarket.getConnection().getAccountInfo(referrerTokenState); if (!account) { axn.addInitReferrerTokenStateIx(axn.reserve, referrerTokenState); } } axn.addRefreshReserveIxs([axn.reserve.address]); axn.addWithdrawReferrerFeesIxs(); return axn; } /** * Builds an instruction for setting the new state of one of the given obligation's orders. * * In other words: it will overwrite the given slot in the {@link Obligation.orders} array. This possibly includes * setting the `null` state (i.e. cancelling the order). */ static buildSetObligationOrderIxn( kaminoMarket: KaminoMarket, obligation: KaminoObligation, orderAtIndex: ObligationOrderAtIndex ): TransactionInstruction { return setObligationOrder( { index: orderAtIndex.index, order: orderAtIndex.orderState(), }, { lendingMarket: kaminoMarket.getAddress(), obligation: obligation.obligationAddress, owner: obligation.state.owner, }, kaminoMarket.programId ); } async getTransactions() { let txns: Transaction; if (this.lendingIxs.length === 2) { txns = new Transaction({ feePayer: this.owner, recentBlockhash: (await this.kaminoMarket.getConnection().getLatestBlockhash()).blockhash, }).add( ...this.setupIxs, ...[this.lendingIxs[0]], ...this.inBetweenIxs, ...[this.lendingIxs[1]], ...this.cleanupIxs ); } else { txns = new Transaction({ feePayer: this.owner, recentBlockhash: (await this.kaminoMarket.getConnection().getLatestBlockhash()).blockhash, }).add(...this.setupIxs, ...this.lendingIxs, ...this.cleanupIxs); } return txns; } async sendTransactions(sendTransaction: (txn: Transaction, connection: Connection) => Promise<TransactionSignature>) { const txns = await this.getTransactions(); const signature = await this.sendSingleTransaction(txns, sendTransaction); return signature; } private async sendSingleTransaction( txn: Transaction | null, sendTransaction: (txn: Transaction, connection: Connection) => Promise<TransactionSignature> ) { if (!txn) return ''; const signature = await sendTransaction(txn, this.kaminoMarket.getConnection()); await this.kaminoMarket.getConnection().confirmTransaction(signature); return signature; } async simulateTransactions( sendTransaction: ( txn: Transaction, connection: Connection ) => Promise<RpcResponseAndContext<SimulatedTransactionResponse>> ) { const txns = await this.getTransactions(); const signature = await this.simulateSingleTransaction(txns, sendTransaction); return signature; } private async simulateSingleTransaction( txn: Transaction | null, sendTransaction: ( txn: Transaction, connection: Connection ) => Promise<RpcResponseAndContext<SimulatedTransactionResponse>> ) { if (!txn) return ''; return await sendTransaction(txn, this.kaminoMarket.getConnection()); } addDepositReserveLiquidityIx() { this.lendingIxsLabels.push(`depositReserveLiquidity`); this.lendingIxs.push( depositReserveLiquidity( { liquidityAmount: this.amount, }, { owner: this.owner, lendingMarket: this.kaminoMarket.getAddress(), lendingMarketAuthority: this.kaminoMarket.getLendingMarketAuthority(), reserve: this.reserve.address, reserveLiquidityMint: this.reserve.getLiquidityMint(), reserveLiquiditySupply: this.reserve.state.liquidity.supplyVault, reserveCollateralMint: this.reserve.getCTokenMint(), userSourceLiquidity: this.getUserTokenAccountAddress(this.reserve), userDestinationCollateral: this.getUserCollateralAccountAddress(this.reserve), collateralTokenProgram: TOKEN_PROGRAM_ID, liquidityTokenProgram: this.reserve.getLiquidityTokenProgram(), instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, this.kaminoMarket.programId ) ); } addRedeemReserveCollateralIx() { this.lendingIxsLabels.push(`redeemReserveCollateral`); this.lendingIxs.push( redeemReserveCollateral( { collateralAmount: this.amount, }, { owner: this.owner, lendingMarket: this.kaminoMarket.getAddress(), lendingMarketAuthority: this.kaminoMarket.getLendingMarketAuthority(), reserve: this.reserve.address, reserveLiquidityMint: this.reserve.getLiquidityMint(), reserveLiquiditySupply: this.reserve.state.liquidity.supplyVault, reserveCollateralMint: this.reserve.getCTokenMint(), userSourceCollateral: this.getUserCollateralAccountAddress(this.reserve), userDestinationLiquidity: this.getUserTokenAccountAddress(this.reserve), collateralTokenProgram: TOKEN_PROGRAM_ID, liquidityTokenProgram: this.reserve.getLiquidityTokenProgram(), instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, this.kaminoMarket.programId ) ); } // @deprecated -- use addDepositIxV2 instead addDepositIx() { this.lendingIxsLabels.push(`depositReserveLiquidityAndObligationCollateral`); this.lendingIxs.push( depositReserveLiquidityAndObligationCollateral( { liquidityAmount: this.amount, }, { owner: this.owner, obligation: this.getObligationPda(), lendingMarket: this.kaminoMarket.getAddress(), lendingMarketAuthority: this.kaminoMarket.getLendingMarketAuthority(), reserve: this.reserve.address, reserveLiquidityMint: this.reserve.getLiquidityMint(), reserveLiquiditySupply: this.reserve.state.liquidity.supplyVault, reserveCollateralMint: this.reserve.getCTokenMint(), reserveDestinationDepositCollateral: this.reserve.state.collateral.supplyVault, // destinationCollateral userSourceLiquidity: this.getUserTokenAccountAddress(this.reserve), placeholderUserDestinationCollateral: this.kaminoMarket.programId, collateralTokenProgram: TOKEN_PROGRAM_ID, liquidityTokenProgram: this.reserve.getLiquidityTokenProgram(), instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, this.kaminoMarket.programId ) ); } addDepositIxV2() { const farmsAccounts = this.reserve.state.farmCollateral.equals(PublicKey.default) ? { obligationFarmUserState: this.kaminoMarket.programId, reserveFarmState: this.kaminoMarket.programId, } : { obligationFarmUserState: obligationFarmStatePda(this.reserve.state.farmCollateral, this.getObligationPda()), reserveFarmState: this.reserve.state.farmCollateral, }; this.lendingIxsLabels.push(`depositReserveLiquidityAndObligationCollateralV2`); this.lendingIxs.push( depositReserveLiquidityAndObligationCollateralV2( { liquidityAmount: this.amount, }, { depositAccounts: { owner: this.owner, obligation: this.getObligationPda(), lendingMarket: this.kaminoMarket.getAddress(), lendingMarketAuthority: this.kaminoMarket.getLendingMarketAuthority(), reserve: this.reserve.address, reserveLiquidityMint: this.reserve.getLiquidityMint(), reserveLiquiditySupply: this.reserve.state.liquidity.supplyVault, reserveCollateralMint: this.reserve.getCTokenMint(), reserveDestinationDepositCollateral: this.reserve.state.collateral.supplyVault, // destinationCollateral userSourceLiquidity: this.getUserTokenAccountAddress(this.reserve), placeholderUserDestinationCollateral: this.kaminoMarket.programId, collateralTokenProgram: TOKEN_PROGRAM_ID, liquidityTokenProgram: this.reserve.getLiquidityTokenProgram(), instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, farmsAccounts, farmsProgram: farmsId, }, this.kaminoMarket.programId ) ); } /// @deprecated -- use addDepositObligationCollateralIxV2 instead addDepositObligationCollateralIx() { this.lendingIxsLabels.push(`depositObligationCollateral`); this.lendingIxs.push( depositObligationCollateral( { collateralAmount: this.amount, }, { owner: this.owner, obligation: this.getObligationPda(), lendingMarket: this.kaminoMarket.getAddress(), depositReserve: this.reserve.address, reserveDestinationCollateral: this.reserve.state.collateral.supplyVault, userSourceCollateral: this.getUserCollateralAccountAddress(this.reserve), tokenProgram: TOKEN_PROGRAM_ID, instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, this.kaminoMarket.programId ) ); } addDepositObligationCollateralIxV2() { const farmsAccounts = this.reserve.state.farmCollateral.equals(PublicKey.default) ? { obligationFarmUserState: this.kaminoMarket.programId, reserveFarmState: this.kaminoMarket.programId, } : { obligationFarmUserState: obligationFarmStatePda(this.reserve.state.farmCollateral, this.getObligationPda()), reserveFarmState: this.reserve.state.farmCollateral, }; this.lendingIxsLabels.push(`depositObligationCollateralV2`); this.lendingIxs.push( depositObligationCollateralV2( { collateralAmount: this.amount, }, { depositAccounts: { owner: this.owner, obligation: this.getObligationPda(), lendingMarket: this.kaminoMarket.getAddress(), depositReserve: this.reserve.address, reserveDestinationCollateral: this.reserve.state.collateral.supplyVault, userSourceCollateral: this.getUserCollateralAccountAddress(this.reserve), tokenProgram: TOKEN_PROGRAM_ID, instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, lendingMarketAuthority: this.kaminoMarket.getLendingMarketAuthority(), farmsAccounts, farmsProgram: farmsId, }, this.kaminoMarket.programId ) ); } /// @deprecated -- use addDepositObligationCollateralIxV2 instead addBorrowIx() { this.lendingIxsLabels.push(`borrowObligationLiquidity`); const depositReservesList = this.getAdditionalDepositReservesList(); const depositReserveAccountMetas = depositReservesList.map((reserve) => { return { pubkey: reserve, isSigner: false, isWritable: true }; }); const borrowIx = borrowObligationLiquidity( { liquidityAmount: this.amount, }, { owner: this.owner, obligation: this.getObligationPda(), lendingMarket: this.kaminoMarket.getAddress(), lendingMarketAuthority: this.kaminoMarket.getLendingMarketAuthority(), borrowReserve: this.reserve.address, borrowReserveLiquidityMint: this.reserve.getLiquidityMint(), reserveSourceLiquidity: this.reserve.state.liquidity.supplyVault, userDestinationLiquidity: this.getUserTokenAccountAddress(this.reserve), borrowReserveLiquidityFeeReceiver: this.reserve.state.liquidity.feeVault, referrerTokenState: referrerTokenStatePda(this.referrer, this.reserve.address, this.kaminoMarket.programId)[0], tokenProgram: this.reserve.getLiquidityTokenProgram(), instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, this.kaminoMarket.programId ); borrowIx.keys = isKaminoObligation(this.obligation) && (this.obligation.state.elevationGroup > 0 || this.obligation.refreshedStats.potentialElevationGroupUpdate > 0) ? borrowIx.keys.concat([...depositReserveAccountMetas]) : borrowIx.keys; this.lendingIxs.push(borrowIx); } addBorrowIxV2() { this.lendingIxsLabels.push(`borrowObligationLiquidityV2`); const depositReservesList = this.getAdditionalDepositReservesList(); const depositReserveAccountMetas = depositReservesList.map((reserve) => { return { pubkey: reserve, isSigner: false, isWritable: true }; }); const farmsAccounts = this.reserve.state.farmDebt.equals(PublicKey.default) ? { obligationFarmUserState: this.kaminoMarket.programId, reserveFarmState: this.kaminoMarket.programId, } : { obligationFarmUserState: obligationFarmStatePda(this.reserve.state.farmDebt, this.getObligationPda()), reserveFarmState: this.reserve.state.farmDebt, }; const borrowIx = borrowObligationLiquidityV2( { liquidityAmount: this.amount, }, { borrowAccounts: { owner: this.owner, obligation: this.getObligationPda(), lendingMarket: this.kaminoMarket.getAddress(), lendingMarketAuthority: this.kaminoMarket.getLendingMarketAuthority(), borrowReserve: this.reserve.address, borrowReserveLiquidityMint: this.reserve.getLiquidityMint(), reserveSourceLiquidity: this.reserve.state.liquidity.supplyVault, userDestinationLiquidity: this.getUserTokenAccountAddress(this.reserve), borrowReserveLiquidityFeeReceiver: this.reserve.state.liquidity.feeVault, referrerTokenState: referrerTokenStatePda( this.referrer, this.reserve.address, this.kaminoMarket.programId )[0], tokenProgram: this.reserve.getLiquidityTokenProgram(), instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, farmsAccounts, farmsProgram: farmsId, }, this.kaminoMarket.programId ); borrowIx.keys = isKaminoObligation(this.obligation) && (this.obligation.state.elevationGroup > 0 || this.obligation.refreshedStats.potentialElevationGroupUpdate > 0) ? borrowIx.keys.concat([...depositReserveAccountMetas]) : borrowIx.keys; this.lendingIxs.push(borrowIx); } /// @deprecated -- use addWithdrawIxV2 instead async addWithdrawIx(collateralAmount: BN) { this.lendingIxsLabels.push(`withdrawObligationCollateralAndRedeemReserveCollateral`); this.lendingIxs.push( withdrawObligationCollateralAndRedeemReserveCollateral( { collateralAmount, }, { owner: this.owner, obligation: this.getObligationPda(), lendingMarket: this.kaminoMarket.getAddress(), lendingMarketAuthority: this.kaminoMarket.getLendingMarketAuthority(), withdrawReserve: this.reserve.address, reserveLiquidityMint: this.reserve.getLiquidityMint(), reserveCollateralMint: this.reserve.getCTokenMint(), reserveLiquiditySupply: this.reserve.state.liquidity.supplyVault, reserveSourceCollateral: this.reserve.state.collateral.supplyVault, userDestinationLiquidity: this.getUserTokenAccountAddress(this.reserve), placeholderUserDestinationCollateral: this.kaminoMarket.programId, collateralTokenProgram: TOKEN_PROGRAM_ID, liquidityTokenProgram: this.reserve.getLiquidityTokenProgram(), instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY, }, this.kaminoMarket.programId ) ); } async addWithdrawIxV2(collateralAmount: BN) { const farmsAccounts = this.reserve.state.farmCollateral.equals(PublicKey.default) ? { obligationFarmUserState: this.kaminoMarket.programId, reserveFarmState: this.kaminoMarket.programId, } : { obligationFarmUserState: obligationFarmStatePda(this.reserve.state.farmCollateral, this.getObligationPda()), reserveFarmState: this.reserve.state.farmCollateral,