Kamino 백서

Kamino

원문

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

borrow.borrow_reserve); println!(" Borrowed amount (sf): {}", borrow.borrowed_amount_sf); } // Health metrics — `_sf` fields use the `fixed` crate for precise conversion let deposited_value = U68F60::from_bits(obligation.deposited_value_sf as u128); let allowed_borrow = U68F60::from_bits(obligation.allowed_borrow_value_sf as u128); let unhealthy_borrow = U68F60::from_bits(obligation.unhealthy_borrow_value_sf as u128); let borrowed_value = U68F60::from_bits(obligation.borrow_factor_adjusted_debt_value_sf as u128); println!("\nMetrics:"); println!(" Deposited value: ${deposited_value}"); println!(" Allowed borrow value: ${allowed_borrow}"); println!(" Unhealthy borrow value: ${unhealthy_borrow}"); println!(" Current borrow value: ${borrowed_value}"); println!(" Liquidatable: {}", borrowed_value > unhealthy_borrow); println!(" Borrowing disabled: {}", obligation.borrowing_disabled > 0); ``` <a href="https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/user_position.rs"> <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 title="getAllUserObligations.ts" 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 title="getAllObligationsByReserve.ts" 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 title="getTransactionHistory.ts" 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> ## Additional Resources <CardGroup> <Card title="API Examples" icon="book" href="https://api-docs.kamino.com/" /> <Card title="SDK Examples" icon="github" href="https://github.com/Kamino-Finance/klend-sdk/tree/master/examples" /> </CardGroup> # Borrow & Lend Source: https://kamino.com/docs/build/developers/borrow/index Learn how to build with Borrow ## Overview Build lending applications on Solana using the Kamino TypeScript SDK, the Rust interface crate, or the REST API. This guide covers everything from basic setup to advanced transaction building for deposit, borrow, repay, and withdraw operations. ## Key Components of Borrow Integration <CardGroup> <Card title="Lending Operations" icon="coins"> Deposit collateral, borrow assets, repay debt, and withdraw - complete lending lifecycle management. </Card> <Card title="Loan Management" icon="shield-check"> LTV ratios, health factors, obligation status and position monitoring for safe lending. </Card> <Card title="Market Analytics" icon="chart-line"> APY tracking, utilization rates, reserve metrics from API and on-chain data. </Card> </CardGroup> ## Integration Options <CardGroup> <Card title="Public API" icon="globe"> Access market data, borrow rates, reserve liquidity, and obligation status via REST endpoints. Language-agnostic. </Card> <Card title="TypeScript SDK" icon="code"> On-chain reads and transaction building for deposit, borrow, repay, and withdraw. TS/JS only. </Card> <Card title="Rust Interface Crate" icon="rust"> Lightweight instruction builder for Rust bots and on-chain CPI. </Card> </CardGroup> ### Deposit <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address, createNoopSigner } from '@solana/kit'; import { KaminoMarket, KaminoAction, LendingObligation } from '@kamino-finance/klend-sdk'; import { simulateTx } from '../../utils/tx'; import BN from 'bn.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const marketPubkey = address('DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek'); const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const market = await KaminoMarket.load(rpc, marketPubkey, 400); const user = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); // user // Create a LendingObligation for depositing to earn interest const obligation = new LendingObligation(usdcMint, market!.programId, 0); const action = await KaminoAction.buildDepositReserveLiquidityTxns( market!, new BN(1_000_000), // Deposit 1 USDC * 10^6 decimals usdcMint, createNoopSigner(user), obligation, undefined ); const res = await simulateTx(rpc, user, [ ...action.computeBudgetIxs, ...action.setupIxs, ...action.lendingIxs, ...action.cleanupIxs, ], []); console.log('Simulation Result:', res); ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-04-user-deposit-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> <Tab title="Rust"> ```rust theme={null} use klend_interface::helpers; use klend_interface::ReserveInfo; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_client::rpc_client::RpcClient; use solana_pubkey::Pubkey; use solana_sdk::signer::keypair::read_keypair_file; use solana_sdk::signer::Signer; use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; use spl_associated_token_account::get_associated_token_address; use std::str::FromStr; 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(); // Fetch reserve data from the chain 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)?; // Derive user token accounts let user_source_liquidity = get_associated_token_address(&owner, &reserve.liquidity_mint); let (collateral_mint, _) = pda::reserve_collateral_mint(&KLEND_PROGRAM_ID, &reserve_pubkey); let user_destination_collateral = get_associated_token_address(&owner, &collateral_mint); // Build deposit instructions (includes refresh_reserve automatically) let instructions = helpers::deposit::deposit( owner, &reserve, user_source_liquidity, user_destination_collateral, 1_000_000, // 1 USDC (6 decimals) ); // Build and send let message = Message::new(&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!("Deposit successful! Signature: {signature}"); ``` </Tab> </Tabs> <Note> For the full deposit example, including transaction sending and confirmation, check out [Deposit Operations](/docs/build/developers/borrow/operations/deposit). </Note> ### Withdraw <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address, createNoopSigner } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import { simulateTx } from '../../utils/tx'; import BN from 'bn.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const marketPubkey = address('DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek'); const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const market = await KaminoMarket.load(rpc, marketPubkey, 400); const user = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); // Fetch the existing obligation from the blockchain const obligation = await market!.getObligationByWallet( user, new VanillaObligation(PROGRAM_ID) ); if (!obligation) { throw new Error('No obligation found for this wallet. You must deposit first.'); } const action = await KaminoAction.buildWithdrawTxns( market!, new BN(1_000_000), // Withdraw 1 USDC * 10^6 decimals usdcMint, createNoopSigner(user), obligation, true, // useV2Ixs undefined // scopeRefreshConfig ); const res = await simulateTx(rpc, user, [ ...action.computeBudgetIxs, ...action.setupIxs, ...action.lendingIxs, ...action.cleanupIxs, ], []); console.log('Simulation Result:', res); ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-05-user-withdraw-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> <Tab title="Rust"> ```rust theme={null} use klend_interface::ObligationContext; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_client::rpc_client::RpcClient; use solana_pubkey::Pubkey; use solana_sdk::signer::keypair::read_keypair_file; use solana_sdk::signer::Signer; use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; use spl_associated_token_account::get_associated_token_address; use std::str::FromStr; 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(); let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); // Derive and fetch the obligation let (obligation_pubkey, _) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, &Pubkey::default(), &Pubkey::default(), ); let obligation_data = rpc_client.get_account(&obligation_pubkey)?; // Fetch all reserves referenced by the obligation let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; 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 )?; // Derive user token account for the withdrawal token (e.g. USDC) let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); let user_dest_liquidity = get_associated_token_address(&owner, &liquidity_mint); // Build withdraw instructions (includes refresh_reserves + refresh_obligation) let instructions = ctx.withdraw( owner, &reserve_pubkey, user_dest_liquidity, 1_000_000, // 1 USDC (6 decimals) )?; // Build and send let message = Message::new(&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!("Withdrawal successful! Signature: {signature}"); ``` </Tab> </Tabs> <Note> For the full withdraw example, including transaction sending and confirmation, check out [Withdraw Operations](/docs/build/developers/borrow/operations/withdraw). </Note> ## Key Data Structures <div> <Tabs> <Tab title="TypeScript"> ##### Obligation ```typescript theme={null} class Obligation { tag: BN; lastUpdate: types.LastUpdate; lendingMarket: Address; owner: Address; deposits: Array<types.ObligationCollateral>; lowestReserveDepositLiquidationLtv: BN; depositedValueSf: BN; borrows: Array<types.ObligationLiquidity>; borrowFactorAdjustedDebtValueSf: BN; borrowedAssetsMarketValueSf: BN; allowedBorrowValueSf: BN; unhealthyBorrowValueSf: BN; depositsAssetTiers: Array<number>; borrowsAssetTiers: Array<number>; elevationGroup: number; numOfObsoleteDepositReserves: number; hasDebt: number; referrer: Address; borrowingDisabled: number; autodeleverageTargetLtvPct: number; lowestReserveDepositMaxLtvPct: number; numOfObsoleteBorrowReserves: number; reserved: Array<number>; highestBorrowFactorPct: BN; autodeleverageMarginCallStartedTimestamp: BN; orders: Array<types.ObligationOrder>; } ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/80f29fcda3ac954b400ceb3000999def487cff5c/src/%40codegen/klend/accounts/Obligation.ts#L145"> <Icon icon="github" /> <span>View Full TypeScript Obligation</span> </a> <Expandable title="Fields"> | Field | Type | Description | | - | - | - | | `tag` | `BN` | Version of the struct | | `lastUpdate` | `types.LastUpdate` | Last update to collateral, liquidity, or their market values | | `lendingMarket` | `Address` | Lending market address | | `owner` | `Address` | Owner authority which can borrow liquidity | | `deposits` | `Array<types.ObligationCollateral>` | Deposited collateral for the obligation, unique by deposit reserve address | | `lowestReserveDepositLiquidationLtv` | `BN` | Worst LTV for the collaterals backing the loan, represented as a percentage | | `depositedValueSf` | `BN` | Market value of deposits (scaled fraction) | | `borrows` | `Array<types.ObligationLiquidity>` | Borrowed liquidity for the obligation, unique by borrow reserve address | | `borrowFactorAdjustedDebtValueSf` | `BN` | Risk adjusted market value of borrows/debt (scaled fraction) | | `borrowedAssetsMarketValueSf` | `BN` | Market value of borrows - used for max\_liquidatable\_borrowed\_amount (scaled fraction) | | `allowedBorrowValueSf` | `BN` | The maximum borrow value at the weighted average loan to value ratio (scaled fraction) | | `unhealthyBorrowValueSf` | `BN` | The dangerous borrow value at the weighted average liquidation threshold (scaled fraction) | | `depositsAssetTiers` | `Array<number>` | The asset tier of the deposits | | `borrowsAssetTiers` | `Array<number>` | The asset tier of the borrows | | `elevationGroup` | `number` | The elevation group id the obligation opted into | | `numOfObsoleteDepositReserves` | `number` | The number of obsolete reserves the obligation has a deposit in | | `hasDebt` | `number` | Marked = 1 if borrows array is not empty, 0 = borrows empty | | `referrer` | `Address` | Wallet address of the referrer | | `borrowingDisabled` | `number` | Marked = 1 if borrowing disabled, 0 = borrowing enabled | | `autodeleverageTargetLtvPct` | `number` | A target LTV set by the risk council when marking this obligation for deleveraging | | `lowestReserveDepositMaxLtvPct` | `number` | The lowest max LTV found amongst the collateral deposits | | `numOfObsoleteBorrowReserves` | `number` | The number of obsolete reserves the obligation has a borrow in | | `reserved` | `Array<number>` | Reserved space for future use | | `highestBorrowFactorPct` | `BN` | The highest borrow factor percentage across all borrows | | `autodeleverageMarginCallStartedTimestamp` | `BN` | Timestamp when risk council marked this obligation for deleveraging (zero if not applicable) | | `orders` | `Array<types.ObligationOrder>` | Owner-defined, liquidator-executed orders (e.g., stop-loss, take-profit) | </Expandable> </Tab> <Tab title="JSON"> ##### Obligation ```json theme={null} { "tag": "0", "lastUpdate": {}, "lendingMarket": "...", "owner": "...", "deposits": [], "low
프로젝트로 돌아가기