nsactionFactory,
getSignatureFromTransaction,
some,
} from '@solana/kit';
import {
KaminoMarket,
KaminoAction,
VanillaObligation,
PROGRAM_ID,
parseKeypairFile,
DEFAULT_RECENT_SLOT_DURATION_MS,
} from '@kamino-finance/klend-sdk';
import BN from 'bn.js';
```
</Step>
<Step>
### Setup Market and Check Existing Referrer
Load the keypair, initialize the market, and check whether a referrer is already associated with the account.
```typescript theme={null}
const KEYPAIR_FILE = '/path/to/your/keypair.json';
const signer = await parseKeypairFile(KEYPAIR_FILE);
const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com');
const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com');
const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); // SOL/BTC Market
const market = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS);
const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC
const depositAmount = new BN(1_000_000); // 1 USDC
```
Check if a referrer is already associated with the account and set the referrer address.
```typescript theme={null}
// Referrer address - UPDATE THIS with the referrer's wallet address
const referrer = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCfqY');
// Check if user already has UserMetadata with a different referrer
const [, currentUserMetadata] = await market!.getUserMetadata(signer.address);
const actualReferrer =
currentUserMetadata && currentUserMetadata.referrer.toString() !== referrer.toString()
? currentUserMetadata.referrer
: referrer;
```
<Warning>
Once a UserMetadata account has a referrer, it cannot be changed. If a referrer is already set, any new referrer value is ignored, and the original referrer continues to receive commission from the user's borrowing activity.
</Warning>
</Step>
<Step>
### Build Deposit Instructions with Referrer
Generate deposit instructions that include the referrer information.
```typescript theme={null}
let depositAction = await KaminoAction.buildDepositTxns(
market!,
depositAmount,
usdcMint,
signer,
new VanillaObligation(PROGRAM_ID),
true,
undefined,
1_000_000,
true,
false,
{ skipInitialization: false, skipLutCreation: false },
some(actualReferrer)
);
const hasSetup = (depositAction.setupIxs || []).length > 0;
// Combine all instructions
let instructions = [
...(depositAction.setupIxs || []),
...(depositAction.lendingIxs || []),
...(depositAction.cleanupIxs || []),
];
```
<Tip>
The referrer earns commission from the user's future borrowing activity. This creates a permanent, non-revocable link between the user and the referrer.
</Tip>
</Step>
<Step>
### Send Initial Transaction
Fetch the latest blockhash and build the transaction message.
```typescript theme={null}
const signatures: string[] = [];
try {
const { value: depositBlockhash } = await rpc
.getLatestBlockhash({ commitment: 'finalized' })
.send();
const depositTx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(depositBlockhash, tx),
(tx) => appendTransactionMessageInstructions(instructions, tx)
);
```
Sign and send the transaction.
```typescript theme={null}
const depositSigned = await signTransactionMessageWithSigners(depositTx);
const depositSignature = getSignatureFromTransaction(depositSigned);
signatures.push(depositSignature);
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(depositSigned, {
commitment: 'confirmed',
skipPreflight: true,
});
console.log(`Deposit successful! Signature: ${depositSignature}`);
```
</Step>
<Step>
### Handle Retry Logic
Detect and handle setup-related errors that may occur.
```typescript theme={null}
} catch (error: unknown) {
const errorMsg = error instanceof Error ? error.message : String(error);
const is0x17a3 =
errorMsg.includes('0x17a3') ||
errorMsg.includes('6051') ||
errorMsg.includes('IncorrectInstructionInPosition');
if (hasSetup && is0x17a3) {
```
<Warning>
When setup instructions are included, the first transaction may fail with error 0x17a3. The retry logic handles this by waiting for blockchain state to settle, reloading the market, and rebuilding instructions.
</Warning>
Wait for blockchain state to settle and reload the market.
```typescript theme={null}
await new Promise((resolve) => setTimeout(resolve, 2000));
const reloadedMarket = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS);
```
Rebuild the deposit instructions with the reloaded market state.
```typescript theme={null}
depositAction = await KaminoAction.buildDepositTxns(
reloadedMarket!,
depositAmount,
usdcMint,
signer,
new VanillaObligation(PROGRAM_ID),
true,
undefined,
1_000_000,
true,
false,
{ skipInitialization: false, skipLutCreation: false },
some(actualReferrer)
);
instructions = [
...(depositAction.setupIxs || []),
...(depositAction.lendingIxs || []),
...(depositAction.cleanupIxs || []),
];
```
Fetch a fresh blockhash and build the retry transaction.
```typescript theme={null}
const { value: retryBlockhash } = await rpc
.getLatestBlockhash({ commitment: 'finalized' })
.send();
const retryTx = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(signer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(retryBlockhash, tx),
(tx) => appendTransactionMessageInstructions(instructions, tx)
);
```
Sign and send the retry transaction.
```typescript theme={null}
const retrySigned = await signTransactionMessageWithSigners(retryTx);
const retrySignature = getSignatureFromTransaction(retrySigned);
signatures.push(retrySignature);
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(retrySigned, {
commitment: 'confirmed',
skipPreflight: true,
});
console.log(
`Deposit successful! Signature: ${retrySignature}\nSetup transaction: https://solscan.io/tx/${signatures[0]}`
);
} else {
console.error('Deposit failed:', error);
}
}
```
<Check>
The deposit with referral is complete. The referrer is now permanently linked to the account and will earn commission from the user's future borrowing activity.
</Check>
</Step>
</Steps>
</Tab>
<Tab title="Rust">
<Steps>
<Step>
### Add Dependencies
```toml theme={null}
[dependencies]
klend-interface = "0.1.0"
solana-pubkey = "2.1"
solana-instruction = "2.1"
solana-sdk = "~2.3"
solana-client = "~2.3"
spl-token = "7"
spl-associated-token-account = "6"
```
<Note>
`klend-interface` is a lightweight Rust instruction builder that creates `Vec<Instruction>` with required refresh instructions prepended automatically.
</Note>
</Step>
<Step>
### Set Up RPC Client
```rust theme={null}
use solana_client::rpc_client::RpcClient;
use solana_sdk::signer::keypair::read_keypair_file;
use solana_sdk::signer::Signer;
let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com");
let signer = read_keypair_file("/path/to/your/keypair.json")
.expect("Failed to read keypair file");
let owner = signer.pubkey();
```
</Step>
<Step>
### Initialize User with Referrer
Create the user metadata account linked to a referrer before depositing.
```rust theme={null}
use klend_interface::helpers;
use klend_interface::pda;
use klend_interface::KLEND_PROGRAM_ID;
use solana_pubkey::Pubkey;
use std::str::FromStr;
let referrer = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCfqY").unwrap();
// Derive the referrer's user_metadata PDA
let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer);
// Your user's address lookup table (created during onboarding)
let user_lookup_table = Pubkey::from_str("YOUR_USER_LOOKUP_TABLE_PUBKEY").unwrap();
let init_ixs = helpers::lifecycle::init_user(
owner,
owner, // fee payer
user_lookup_table,
Some(referrer_user_metadata), // links to this referrer
);
```
<Warning>
Once a UserMetadata account has a referrer, it cannot be changed. The original referrer permanently earns commission from the user's borrowing activity.
</Warning>
</Step>
<Step>
### Build Obligation Context
Derive the obligation PDA and build the context for depositing.
```rust theme={null}
use klend_interface::ObligationContext;
let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap();
let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap();
// Derive the obligation PDA
let (obligation_pubkey, _) = pda::obligation(
&KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market,
&Pubkey::default(), &Pubkey::default(),
);
// Fetch the obligation account
let obligation_data = rpc_client.get_account(&obligation_pubkey)?;
// Discover which reserves the obligation references
let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?;
// Fetch all reserve accounts in one RPC call
let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?;
// Build the context
let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter()
.zip(reserve_accounts.iter())
.filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice())))
.collect();
let ctx = ObligationContext::from_account_data(
obligation_pubkey, &obligation_data.data, &reserves
)?;
```
<Note>
`ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods.
</Note>
</Step>
<Step>
### Build Deposit Instructions
```rust theme={null}
use spl_associated_token_account::get_associated_token_address;
let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap();
let user_source_liquidity = get_associated_token_address(&owner, &liquidity_mint);
let deposit_ixs = ctx.deposit(
owner,
&reserve_pubkey,
user_source_liquidity,
1_000_000, // 1 USDC
)?;
```
</Step>
<Step>
### Send Transactions
```rust theme={null}
use solana_sdk::transaction::Transaction;
use solana_sdk::message::Message;
// Transaction 1: Initialize user metadata with referrer
let message = Message::new(&init_ixs, Some(&owner));
let recent_blockhash = rpc_client.get_latest_blockhash()?;
let tx = Transaction::new(&[&signer], message, recent_blockhash);
rpc_client.send_and_confirm_transaction(&tx)?;
// Transaction 2: Deposit with referral
let message = Message::new(&deposit_ixs, Some(&owner));
let recent_blockhash = rpc_client.get_latest_blockhash()?;
let tx = Transaction::new(&[&signer], message, recent_blockhash);
let signature = rpc_client.send_and_confirm_transaction(&tx)?;
println!("Deposit with referral successful! Signature: {signature}");
```
</Step>
</Steps>
</Tab>
</Tabs>
# Calculate Extra Farm Reward APY
Source: https://kamino.com/docs/build/tutorials/borrow/extra-farm-reward-apy
Calculate APY for extra farm stablecoin rewards
This tutorial shows you how to calculate APY for extra farm rewards that are earned when using specific collateral and debt combinations.
<Note>
Extra farms provide additional rewards to users who deposit specific collateral and borrow specific assets.
</Note>
## Calculate Extra Farm Reward APY
Calculate APY for extra farm rewards paid in stablecoins like CASH that are pegged to USD.
<Steps>
<Step>
### Import Dependencies
Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations.
```typescript theme={null}
import { createSolanaRpc, address } from '@solana/kit';
import { FarmState, calculateCurrentRewardPerToken } from '@kamino-finance/farms-sdk';
import { KaminoMarket, PROGRAM_ID, lamportsToNumberDecimal } from '@kamino-finance/klend-sdk';
import Decimal from 'decimal.js';
type ExtraFarm = { market: string; farm: string; collMint: string; debtMint: string };
type Resources = { 'mainnet-beta': { extraFarms: ExtraFarm[] } };
```
</Step>
<Step>
### Initialize RPC and Load Market
Set up the Solana RPC connection and load the Kamino market.
```typescript theme={null}
const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com');
const mainMarketAddress = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF');
// Load market and get CASH and SOL mints from reserves
const market = await KaminoMarket.load(rpc, mainMarketAddress, 400, PROGRAM_ID);
let cashReserve, solReserve;
for (const reserve of market!.reserves.values()) {
if (reserve.stats.symbol === 'CASH') cashReserve = reserve;
if (reserve.stats.symbol === 'SOL') solReserve = reserve;
}
if (!cashReserve || !solReserve) {
throw new Error('CASH or SOL reserve not found');
}
const cashMint = cashReserve.getLiquidityMint().toString();
const solMint = solReserve.getLiquidityMint().toString();
```
<Info>
This example targets the SOL/CASH extra farm pair where users deposit SOL collateral and borrow CASH to earn rewards.
</Info>
</Step>
<Step>
### Get and Filter Extra Farms
Fetch the list of extra farms from the CDN and filter by SOL collateral and CASH debt.
```typescript theme={null}
// Get extraFarms from CDN API and filter by SOL/CASH pair
const cdnRes = await fetch('https://cdn.kamino.finance/resources.json');
const allResources = (await cdnRes.json()) as Resources;
const kaminoResources = allResources['mainnet-beta'];
const extraFarmsForMarket = kaminoResources.extraFarms.filter((f) => f.market === mainMarketAddress.toString());
// Filter by collateral (SOL) and debt (CASH) mints
const solCashFarms = extraFarmsForMarket.filter((f) => f.collMint === solMint && f.debtMint === cashMint);
```
<Info>
The CDN resources endpoint provides a list of all extra farms. We filter for farms that specifically reward SOL collateral deposits paired with CASH borrows.
</Info>
</Step>
<Step>
### Fetch All Farm States in Batch
Fetch all farm states in a single batch request for better performance.
```typescript theme={null}
// Fetch all farm states in batch
const farmAddresses = solCashFarms.map((f) => address(f.farm));
const farmStates = await FarmState.fetchMultiple(rpc, farmAddresses);
const farms = solCashFarms.flatMap((extraFarm, index) => {
const farmState = farmStates[index];
return farmState ? [{ farm: extraFarm.farm, farmState }] : [];
});
```
<Info>
Using `FarmState.fetchMultiple` fetches all farm states in a single batch request.
</Info>
</Step>
<Step>
### Calculate APY for SOL/CASH Farms
Loop through the fetched farms and calculate APY for CASH rewards.
```typescript theme={null}
for (const { farm, farmState } of farms) {
const totalStaked = lamportsToNumberDecimal(
farmState.totalStakedAmount.toString(),
farmState.token.decimals.toNumber() || 6
);
const cashReward = farmState.rewardInfos.find(
(r) => r.token.mint.toString() === cashMint && r.rewardsAvailable.gtn(0)
);
if (cashReward && !totalStaked.isZero()) {
const currentTime = new Decimal(Date.now() / 1000);
// Calculate APY from farm rewards
const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(cashReward, currentTime); // returns the raw value
const divisor = new Decimal(10)
.pow(cashReward.rewardsPerSecondDecimals.toString())
.mul(new Decimal(10).pow(cashReward.token.decimals.toString()));
const adjustedRewardPerToken = new Decimal(rewardPerTokenPerSecond).div(divisor);
const dailyRewards = adjustedRewardPerToken.mul(86400);
const apy = Decimal.pow(dailyRewards.div(totalStaked).plus(1), 365).minus(1);
console.log(`ExtraFarm: ${farm}`);
console.log(` CASH APY: ${(apy.toNumber() * 100).toFixed(2)}%\n`);
}
}
```
<Check>
The script outputs the APY for SOL/CASH extra farms paying CASH rewards. The `calculateCurrentRewardPerToken` helper from farms-sdk handles the reward schedule logic. Since CASH is pegged to USD, no price lookup is required.
</Check>
</Step>
</Steps>
# Flash Loans
Source: https://kamino.com/docs/build/tutorials/borrow/flash-loans
Execute a flash loan to borrow assets and repay within a single atomic transaction
## Flash Loans
<Tabs>
<Tab title="TypeScript">
<Steps>
<Step>
### Import Dependencies
Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building.
```typescript theme={null}
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
address,
pipe,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
signTransactionMessageWithSigners,
sendAndConfirmTransactionFactory,
getSignatureFromTransaction,
none,
getProgramDerivedAddress,
getAddressEncoder,
} from '@solana/kit';
import {
KaminoMarket,
PROGRAM_ID,
getFlashLoanInstructions
} from '@kamino-finance/klend-sdk';
import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js';
import { getAddMemoInstruction } from '@solana-program/memo';
import Decimal from 'decimal.js';
```
</Step>
<Step>
### Setup Market and Signer
Load your keypair, initialize RPC connections, and load the Kamino market.
```typescript theme={null}
const KEYPAIR_FILE = '/path/to/your/keypair.json';
const signer = await parseKeypairFile(KEYPAIR_FILE);
const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com');
const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com');
const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); // SOL/BTC Market
const market = await KaminoMarket.load(rpc, marketPubkey, 400);
```
</Step>
<Step>
### Configure Flash Loan Parameters
Set the token mint, flash loan amount, and derive the user's token account address.
```typescript theme={null}
const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC
const usdcReserve = market!.getReserveByMint(usdcMint)!;
// Flash loan amount: 1 USDC
const flashLoanAmount = new Decimal(1_000_000);
// Derive user's USDC token account (ATA)
const ASSOCIATED_TOKEN_PROGRAM = address('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
const TOKEN_PROGRAM = usdcReserve.getLiquidityTokenProgram();
const addressEncoder = getAddressEncoder();
const [usdcAta] = await getProgramDerivedAddress({
programAddress: ASSOCIATED_TOKEN_PROGRAM,
seeds: [
addressEncoder.encode(signer.address),
addressEncoder.encode(TOKEN_PROGRAM),
addressEncoder.encode(usdcMint)
],
});
```
</Step>
<Step>
### Build Flash Loan Instructions
Generate the flash borrow and flash repay instructions using the Kamino SDK.
```typescript theme={null}
// Build flash loan instructions
const lendingMarketAuthority = await market!.getLendingMarketAuthority();
const { flashBorrowIx, flashRepayIx } = getFlashLoanInstructions({
borrowIxIndex: 0,
userTransferAuthority: signer,
lendingMarketAuthority,
lendingMarketAddress: market!.getAddress(),
reserve: usdcReserve,
amountLamports: flashLoanAmount,
destinationAta: usdcAta,
referrerAccount: none(),
referrerTokenState: none(),
programId: PROGRAM_ID,
});
```
<Info>
The `borrowIxIndex:0 ` parameter specifies that the flash borrow instruction is at index 0 in the transaction. The SDK uses this to validate that repayment occurs in the same transaction.
</Info>
</Step>
<Step>
### Add Your Custom Instructions
Create your custom instructions to execute with the borrowed funds. In this example, we use a simple memo instruction.
```typescript theme={null}
// Create memo instruction
const memoIx = getAddMemoInstruction({ memo: 'Hello Kamino' });
// Arrange instructions: flash borrow → your instructions → flash repay
const allInstructions = [flashBorrowIx, memoIx, flashRepayIx];
```
<Note>
Replace the memo instruction with your actual프로젝트로 돌아가기