Kamino 백서

Kamino

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 54쪽

business logic. </Note> </Step> <Step> ### Build and Send Transaction Build the transaction with a fresh blockhash and send it to the network. ```typescript theme={null} // Get fresh blockhash const { value: latestBlockhash } = await rpc .getLatestBlockhash({ commitment: 'finalized' }) .send(); // Build transaction const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => appendTransactionMessageInstructions(allInstructions, tx), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })( signedTransaction, { commitment: 'confirmed', skipPreflight: false, } ); console.log(`Flash loan successful! Signature: ${signature}`); ``` <Check> Your flash loan transaction is complete! The borrowed funds were used for your operations and automatically repaid within the same atomic transaction. </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> ### Fetch Reserve Data ```rust theme={null} use klend_interface::helpers; use klend_interface::ReserveInfo; use solana_pubkey::Pubkey; use std::str::FromStr; let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); let reserve_data = rpc_client.get_account(&reserve_pubkey)?; let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; ``` <Note> Use `ReserveInfo::from_account_data(pubkey, &data)` to construct reserve info from raw RPC account bytes. </Note> </Step> <Step> ### Derive Token Accounts ```rust theme={null} use spl_associated_token_account::get_associated_token_address; let user_token_account = get_associated_token_address(&owner, &reserve.liquidity_mint); ``` </Step> <Step> ### Build Flash Loan Instructions ```rust theme={null} let (borrow_ix, repay_ix) = helpers::flash::flash_loan( owner, &reserve, user_token_account, // source for repayment user_token_account, // destination for borrowed funds 1_000_000, // 1 USDC (6 decimals) 0, // borrow instruction index in the transaction None, // no referrer ); ``` <Info> The `borrow_instruction_index` parameter specifies the position of the flash borrow instruction in the final transaction. Set to `0` if it is the first instruction. </Info> </Step> <Step> ### Compose and Send Transaction ```rust theme={null} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; // Insert your custom instructions between borrow and repay let your_custom_instructions = vec![/* your logic here */]; let mut all_instructions = vec![borrow_ix]; all_instructions.extend(your_custom_instructions); all_instructions.push(repay_ix); let message = Message::new(&all_instructions, 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!("Flash loan successful! Signature: {signature}"); ``` <Note> The flash borrow and repay must be in the same transaction. You can insert any number of instructions between them. </Note> </Step> </Steps> </Tab> </Tabs> # Markets Source: https://kamino.com/docs/build/tutorials/borrow/index Learn how to access market data including supply APY, borrow APY, TVL, and utilization rates for lending reserves <CardGroup> <Card title="Borrow & Lend" icon="chart-line" href="/docs/build/borrow/index"> Borrow and lend assets </Card> </CardGroup> ## Get Market Information Retrieve market-wide TVL metrics for deposits and borrows. <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket } from '@kamino-finance/klend-sdk'; const slotDuration = 400; // ms const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const market = await KaminoMarket.load(rpc, marketPubkey, slotDuration); console.log({ deposits: market!.getTotalDepositTVL(), borrows: market!.getTotalBorrowTVL(), }); ``` <a> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> ## Get Reserve Supply and Borrow APY Fetch historical supply APY and borrow APY data for a specific reserve over time. <Tabs> <Tab title="TypeScript"> ```typescript theme={null} const API_BASE_URL = 'https://api.kamino.finance'; const marketPubkey = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; const reservePubkey = '37Jk2zkz23vkAYBT66HM2gaqJuNg2nYLsCreQAVt5MWK'; const url = `${API_BASE_URL}/kamino-market/${marketPubkey}/reserves/${reservePubkey}/metrics/history`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); for (const item of data.history) { console.log({ timestamp: item.timestamp, supplyInterestAPY: item.metrics.supplyInterestAPY, borrowInterestAPY: item.metrics.borrowInterestAPY, depositTvl: item.metrics.depositTvl, borrowTvl: item.metrics.borrowTvl, }); } ``` <a> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> ## Get Reserve Information Check detailed metrics for all reserves including supply APY, borrow APY, deposit TVL, borrow TVL, and utilization rates. <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket } from '@kamino-finance/klend-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const marketPubkey = address('DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek'); const slotDuration = 400; // ms const slot = await rpc.getSlot().send(); const market = await KaminoMarket.load(rpc, marketPubkey, slotDuration); for (const reserve of market!.getReserves()) { console.log(`Reserve ${reserve.symbol}:`); console.log(` Deposit TVL: ${reserve.getDepositTvl().toFixed(2)}`); console.log(` Borrow TVL: ${reserve.getBorrowTvl().toFixed(2)}`); console.log(` Borrow APY: ${reserve.totalBorrowAPY(slot)}%`); console.log(` Supply APY: ${reserve.totalSupplyAPY(slot)}%`); console.log(` Utilization: ${reserve.calculateUtilizationRatio()}%`); } ``` <a> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> ## Get Reserve Reward History Fetches historical KLend reward metrics for a specific deposit and borrow reserve pair. <Note> This endpoint returns KMNO reward incentives for specific deposit and borrow reserve combinations. </Note> <Tabs> <Tab title="TypeScript"> ```typescript theme={null} const depositReservePubkey = 'd4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q'; const borrowReservePubkey = 'D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59'; const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2025-11-07T00:00:00.000Z', end: '2025-11-14T23:59:59.999Z', frequency: 'day', }).toString(); const url = `${API_BASE_URL}/klend/${depositReservePubkey}/${borrowReservePubkey}/rewards/history?${params}`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log(data); ``` <a> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> ## Get User Obligation Info Retrieve detailed obligation information including deposits, borrows, and health metrics. <Tabs> <Tab title="TypeScript"> ```typescript expandable theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const userAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); const market = await KaminoMarket.load(rpc, marketPubkey, 400, PROGRAM_ID); const kaminoObligation = await market!.getObligationByWallet( userAddress, new VanillaObligation(PROGRAM_ID) ); if (!kaminoObligation) { console.log('No obligation found for user:', userAddress); } else { console.log('Obligation Info:'); console.log('Owner:', kaminoObligation.state.owner.toString()); console.log('\nDeposits (Collateral):'); const deposits = [...kaminoObligation.deposits.values()]; deposits.forEach((deposit) => { console.log(`Reserve:`, deposit.reserveAddress.toString()); console.log(` Amount:`, deposit.amount); console.log(` Market Value:`, deposit.marketValueRefreshed); }); console.log('\nBorrows:'); const borrows = [...kaminoObligation.borrows.values()]; borrows.forEach((borrow) => { console.log(`Reserve:`, borrow.reserveAddress.toString()); console.log(` Amount:`, borrow.amount); }); console.log('\nMetrics:'); console.log('Loan-to-Value:', kaminoObligation.loanToValue()); console.log('Borrow Utilization:', kaminoObligation.refreshedStats.borrowUtilization); console.log('Number of Positions:', kaminoObligation.getNumberOfPositions()); } ``` <a> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> ## Get All User Obligations Retrieve all obligations for a user wallet, including different obligation types across the market. <Tabs> <Tab title="TypeScript"> ```typescript expandable theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, PROGRAM_ID, ObligationTypeTag } from '@kamino-finance/klend-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const userWallet = address('Hs9ioQZ2pCUyvS18anwmBxjQJsZrMPShwTMLySD6Us3V'); const market = await KaminoMarket.load(rpc, marketPubkey, 400, PROGRAM_ID); const obligations = await market.getAllUserObligations(userWallet); if (obligations.length === 0) { console.log('No obligations found for wallet:', userWallet); } else { console.log(`Found ${obligations.length} obligation(s):\n`); obligations.forEach((obligation, i) => { console.log(`Obligation ${i + 1}:`); console.log('Address:', obligation.obligationAddress.toString()); console.log('Type:', ObligationTypeTag[obligation.obligationTag]); console.log('Owner:', obligation.state.owner.toString()); console.log('\nDeposits (Collateral):'); const deposits = [...obligation.deposits.values()]; deposits.forEach((deposit) => { console.log(` Reserve:`, deposit.reserveAddress.toString()); console.log(` Amount:`, deposit.amount); console.log(` Market Value:`, deposit.marketValueRefreshed); }); console.log('\nBorrows:'); const borrows = [...obligation.borrows.values()]; borrows.forEach((borrow) => { console.log(` Reserve:`, borrow.reserveAddress.toString()); console.log(` Amount:`, borrow.amount); console.log(` Market Value:`, borrow.marketValueRefreshed); }); console.log('\nMetrics:'); console.log('Loan-to-Value:', obligation.loanToValue()); console.log('Borrow Utilization:', obligation.refreshedStats.borrowUtilization); console.log('Number of Positions:', obligation.getNumberOfPositions()); }); } ``` <a> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> ## Get All Obligations by Reserve Retrieve all obligations that have deposits in a specific reserve. Useful for analyzing reserve utilization and user exposure. <Tabs> <Tab title="TypeScript"> ```typescript expandable theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, PROGRAM_ID, ObligationTypeTag } from '@kamino-finance/klend-sdk'; // Note: This example requires a paid/dedicated RPC node. Public RPCs will hit rate limits. const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const reserveAddress = address('37Jk2zkz23vkAYBT66HM2gaqJuNg2nYLsCreQAVt5MWK'); const market = await KaminoMarket.load(rpc, marketPubkey, 400, PROGRAM_ID); const obligations = await market.getAllObligationsByDepositedReserve(reserveAddress); if (obligations.length === 0) { console.log('No obligations found with deposits in reserve:', reserveAddress); } else { console.log(`Found ${obligations.length} obligation(s) with deposits in this reserve:\n`); obligations.forEach((obligation, i) => { console.log(`Obligation ${i + 1}:`); console.log('Address:', obligation.obligationAddress.toString()); console.log('Type:', ObligationTypeTag[obligation.obligationTag]); console.log('Owner:', obligation.state.owner.toString()); const reserveDeposit = [...obligation.deposits.values()].find( (deposit) => deposit.reserveAddress.toString() === reserveAddress.toString() ); if (reserveDeposit) { console.log('\nDeposit in this Reserve:'); console.log(' Amount:', reserveDeposit.amount); console.log(' Market Value:', reserveDeposit.marketValueRefreshed); } const otherDeposits = [...obligation.deposits.values()].filter( (deposit) => deposit.reserveAddress.toString() !== reserveAddress.toString() ); if (otherDeposits.length > 0) { console.log('\nOther Deposits:'); otherDeposits.forEach((deposit) => { console.log(' Reserve:', deposit.reserveAddress.toString()); console.log(' Market Value:', deposit.marketValueRefreshed); }); } const borrows = [...obligation.borrows.values()]; if (borrows.length > 0) { console.log('\nBorrows:'); borrows.forEach((borrow) => { console.log(' Reserve:', borrow.reserveAddress.toString()); console.log(' Market Value:', borrow.marketValueRefreshed); }); } console.log('\nMetrics:'); console.log('Loan-to-Value:', obligation.loanToValue()); console.log('Number of Positions:', obligation.getNumberOfPositions()); console.log(); }); } ``` <a> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> ## Get User Transaction History Access all transaction history for a user's wallet across deposits, borrows, repayments, and liquidations. <Tabs> <Tab title="TypeScript"> ```typescript theme={null} const marketPubkey = 'DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek'; const userPubkey = 'EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'; const API_BASE_URL = 'https://api.kamino.finance'; const url = `${API_BASE_URL}/v2/kamino-market/${marketPubkey}/users/${userPubkey}/transactions`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log(data); ``` <a> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> # Build a Liquidation Bot with KSwap Source: https://kamino.com/docs/build/tutorials/borrow/liquidation-bot Build a bot that monitors obligations, identifies profitable pairs, swaps into debt tokens via KSwap, and executes liquidations Liquidations on Kamino are permissionless. Any wallet can liquidate an unhealthy obligation and earn a bonus. Bots continuously monitor all obligations and execute when one crosses its health limit. ## Scanning for Unhealthy Positions The first step is loading every obligation in a market and checking which ones have breached their health limit. <Tabs> <Tab title="TypeScript"> <Steps> <Step> ### Import Dependencies ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, createKeyPairSignerFromBytes, sendAndConfirmTransactionFactory, address, } from '@solana/kit'; import { KaminoMarket, KaminoObligation, DEFAULT_RECENT_SLOT_DURATION_MS, } from '@kamino-finance/klend-sdk'; ``` </Step> <Step> ### Set Up RPC and Load Market ```typescript theme={null} const RPC_ENDPOINT = 'YOUR_RPC_URL'; const WS_ENDPOINT = RPC_ENDPOINT.replace('https://', 'wss://'); const SOL_BTC_MARKET = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); const keypairBytes = new Uint8Array(JSON.parse(process.env.LENDING_USER_SECRET_KEY!)); const liquidator = await createKeyPairSignerFromBytes(keypairBytes); const market = await KaminoMarket.load( rpc, address(SOL_BTC_MARKET), DEFAULT_RECENT_SLOT_DURATION_MS, ); ``` <Note> Kamino operates multiple markets (SOL/BTC, JLP, Altcoins, Prime). A production bot should scan all of them. See [Markets](/docs/products/borrow/markets) for the full list. </Note> </Step> <Step> ### Scan Obligations in Batches Scan obligations in batches of 100 to avoid out-of-memory on large markets. Use the on-chain LTV methods, not `refreshedStats.loanToValue`, to match the program's liquidation check. ```typescript theme={null} // Scanning 100k+ obligations in batches takes several minutes. const currentSlot = await rpc.getSlot().send(); const unhealthy: KaminoObligation[] = []; let totalScanned = 0; for await (const batch of market!.batchGetAllObligationsForMarket(currentSlot)) { totalScanned += batch.length; batch.forEach((ob) => { const ltv = ob.loanToValue(); const liqLtv = ob.liquidationLtv(); if (ltv.gte(liqLtv) && ob.refreshedStats.userTotalBorrow.gt(0)) { unhealthy.push(ob); } }); } console.log(`Found ${unhealthy.length} liquidatable out of ${totalScanned} total`); ``` </Step> </Steps> </Tab> <Tab title="Rust"> <Steps> <Step> ### Add Dependencies ```toml theme={null} [dependencies] klend-interface = { version = "0.6.0", features = ["solana-account"] } solana-pubkey = "2.1" solana-instruction = "2.1" solana-sdk = "~2.3" solana-client = "~2.3" solana-account = "2.1" solana-account-decoder-client-types = "~2.3" spl-token = "7" spl-associated-token-account = "6" reqwest = { version = "~0.12", features = ["blocking", "json"] } serde = { version = "1", features = ["derive"] } serde_json = "1" bincode = "1" base64 = "0.22" ``` <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_pubkey::Pubkey; use std::str::FromStr; let rpc_client = RpcClient::new("YOUR_RPC_URL"); let market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF")?; ``` <Warning> Scanning obligations requires `getProgramAccounts`, which returns thousands of accounts per market. The public Solana RPC will reject these calls. Use a private RPC provider (Helius, Triton, QuickNode, etc.). </Warning> </Step> <Step> ### Fetch All Obligations Fetch every obligation in the market using `get_program_accounts` with filters for the discriminator, lending market, and account size. ```rust theme={null} use klend_interface::{ state::{Obligation, S
프로젝트로 돌아가기