Kamino 백서

Kamino

원문

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

('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> # Flash Loans Source: https://kamino.com/docs/build/borrow/multiply/flash-loans Execute atomic flash loan transactions on Kamino ## 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 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> # Monitor Position Health Source: https://kamino.com/docs/build/borrow/multiply/monitor-position-health Monitor LTV, leverage, and liquidation risk for your multiply positions When a Multiply position is opened, Kamino's on-chain program immediately begins tracking and updating position health metrics. These metrics update with every transaction that affects the position and recalculate based on current collateral prices and debt accrual. The protocol stores six core metrics that describe position size, leverage level, borrowing capacity, and liquidation risk. ### Position Health Metrics | Metric | Description | | - | - | | **Total Deposit** | The total USD value of all collateral deposited into the position | | **Total Borrow** | The total USD value of debt owed on the position | | **Net Value** | Equity in the position. Calculated as Total Deposit - Total Borrow. Represents the value that would be received if all debt were repaid and collateral withdrawn | | **Leverage** | Capital amplification multiplier. 1x = no leverage (collateral only), 2x = borrowed amount equals deposit, 3x = borrowed twice the deposit amount | | **Borrow Limit** | Maximum borrowing capacity before approaching liquidation threshold. Total Borrow must remain below this value | | **Liquidation LTV** | The loan-to-value percentage at which the position becomes eligible for liquidation. Varies by asset pair and eMode settings | Leverage amplifies both gains and losses. When Current LTV approaches Liquidation LTV, the position risks partial liquidation. When borrow rates exceed collateral yield, Net APY turns negative and debt grows faster than earnings. Regular monitoring enables integrations to alert users when conditions warrant position adjustment—whether through debt repayment, leverage reduction, or position closure. *** ## Get Position Health Metrics <Tabs> <Tab title="SDK"> <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication and Kamino SDK operations. ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, parseKeypairFile, ObligationTypeTag, DEFAULT_RECENT_SLOT_DURATION_MS } from '@kamino-finance/klend-sdk'; ``` </Step> <Step> ### Load Market and Initialize RPC Load the keypair, initialize RPC connection, and load the xStocks 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 marketPubkey = address('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const market = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS); ``` </Step> <Step>
프로젝트로 돌아가기