Kamino 백서

Kamino

원문

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

EST API | HTTPS endpoints for data, analytics, and unsigned transactions. Language-agnostic. | | TypeScript SDK | On-chain state reads and transaction building. TS/JS only. | | Rust Interface Crate | Lightweight instruction builder for Rust clients, bots, and on-chain CPI. | ## Core Differences Comparison of API, SDK, and Rust crate capabilities. | Capability | REST API | TypeScript SDK | Rust Interface Crate | | - | - | - | - | | Data queries (vaults, reserves) | Ready-made endpoints | On-chain reads | On-chain reads (raw account parsing) | | User position tracking | Rich endpoints | Real-time account lookup | Real-time account lookup | | Historical metrics & charts | Built-in history endpoints | Not available | Not available | | Transaction building (deposit, borrow) | Unsigned transaction endpoints | Instruction builders | Instruction builders | | Vault creation | Not supported | Admin-level creation tools | Not supported | | On-chain CPI | Not applicable | Not applicable | Direct CPI from Solana programs | | Language/runtime | Any (via HTTP) | TypeScript/JavaScript only | Rust (client-side or on-chain) | ## Data & Analytics Retrieve vault, market, and historical performance data. <AccordionGroup> <Accordion title="Historical Performance"> **REST API** Fetch historical APY data for lending market reserves. ```typescript theme={null} const options = {method: 'GET'}; fetch('https://api.kamino.finance/kamino-market/{market-id}/rates/history', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err)); ``` **TypeScript SDK** No history tracking. Developers must persist snapshots manually if needed. </Accordion> </AccordionGroup> ## On-Chain Transactions Build and execute deposit, borrow, repay, and withdraw operations. <AccordionGroup> <Accordion title="Deposit Liquidity"> **REST API**<br /> Get unsigned Solana transactions to deposit liquidity into a Kamino Lend market reserve. Returns transaction that must be signed client-side. ```typescript theme={null} const depositRequest = { wallet: 'YOUR_WALLET_ADDRESS', market: 'DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek', reserve: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', amount: '1.0', // 1 USDC (decimal format, not lamports) }; const res = await fetch('https://api.kamino.finance/ktx/klend/deposit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(depositRequest), }); const { transaction } = await res.json(); // Sign and send transaction client-side ``` **TypeScript SDK**<br /> Build and execute deposit transactions directly on-chain. ```typescript theme={null} import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import { createSolanaRpc, address } from '@solana/kit'; import BN from 'bn.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const market = await KaminoMarket.load( rpc, address('DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek'), 100 ); const depositAction = await KaminoAction.buildDepositTxns( market, new BN(1_000_000), // 1 USDC address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), signer, new VanillaObligation(PROGRAM_ID), true ); // Build, sign, and send transaction ``` **Rust Interface Crate**<br /> Build deposit instructions from a Rust client. Ideal for bots and backend services. ```rust theme={null} use klend_interface::{helpers, pda, ReserveInfo, KLEND_PROGRAM_ID}; use spl_associated_token_account::get_associated_token_address; let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; 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); let instructions = helpers::deposit::deposit( owner, &reserve, user_source_liquidity, user_destination_collateral, 1_000_000, // 1 USDC (6 decimals) ); // Build and send transaction ``` </Accordion> <Accordion title="Deposit into an Earn Vault"> **TypeScript SDK**<br /> Build a vault deposit with the SDK. ```typescript theme={null} import { KaminoVault } from '@kamino-finance/klend-sdk'; import { createSolanaRpc, address } from '@solana/kit'; import { Decimal } from 'decimal.js'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E') // USDC vault ); const bundle = await vault.depositIxs(signer, new Decimal(1.0)); ``` **Rust Interface Crate**<br /> Build a vault deposit with the [`kvault-interface`](https://crates.io/crates/kvault-interface) crate. The helper derives the PDAs and per-reserve remaining accounts from the on-chain vault state. ```rust theme={null} use kvault_interface::{helpers, pda, VaultInfo, KVAULT_PROGRAM_ID}; use spl_associated_token_account::get_associated_token_address; let vault = VaultInfo::from_account_data(vault_pubkey, &vault_data.data, &reserve_infos)?; let user_token_ata = get_associated_token_address(&owner, &vault.token_mint); let (shares_mint, _) = pda::shares_mint(&KVAULT_PROGRAM_ID, &vault_pubkey); let user_shares_ata = get_associated_token_address(&owner, &shares_mint); let instruction = helpers::deposit::deposit( &vault, owner, user_token_ata, user_shares_ata, 1_000_000, // 1 USDC (6 decimals) ); // Build and send transaction ``` </Accordion> <Accordion title="Borrow & Repay"> **REST API**<br /> Get unsigned transactions for borrow and repay operations. ```typescript theme={null} // Borrow const borrowRequest = { wallet: 'YOUR_WALLET_ADDRESS', market: '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF', reserve: 'D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59', amount: '1.0', }; const borrowRes = await fetch('https://api.kamino.finance/ktx/klend/borrow', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(borrowRequest), }); // Repay const repayRequest = { wallet: 'YOUR_WALLET_ADDRESS', market: '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF', reserve: 'D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59', amount: '1.0', }; const repayRes = await fetch('https://api.kamino.finance/ktx/klend/repay', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(repayRequest), }); ``` **TypeScript SDK** <br /> Build borrow and repay transactions directly. ```typescript theme={null} import { KaminoAction, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import BN from 'bn.js'; const borrowAction = await KaminoAction.buildBorrowTxns( market, new BN(1_000_000), tokenMint, signer, new VanillaObligation(PROGRAM_ID), true, undefined, 1_000_000, true, false ); ``` **Rust Interface Crate**<br /> Build borrow instructions using `ObligationContext` which handles reserve refresh automatically. ```rust theme={null} use klend_interface::{ObligationContext, pda, KLEND_PROGRAM_ID}; use spl_associated_token_account::get_associated_token_address; // Build context from on-chain obligation + its reserves let ctx = ObligationContext::from_account_data( obligation_pubkey, &obligation_data.data, &reserves )?; let user_dest_liquidity = get_associated_token_address(&owner, &borrow_mint); let instructions = ctx.borrow( owner, &reserve_pubkey, user_dest_liquidity, 1_000_000, // 1 USDC (6 decimals) )?; // Build and send transaction ``` </Accordion> <Accordion title="Vault Creation"> **TypeScript SDK**<br /> ```typescript theme={null} const { vault: vaultSigner, initVaultIxs: instructions } = await kaminoManager.createVaultIxs(kaminoVaultConfig); ``` <br /> </Accordion> </AccordionGroup> ## Recommended Usage Patterns Choose the right tool for your use case. | Use Case | Best Tool | | - | - | | Display vault list with APR & TVL | API | | Chart vault APY over 30 days | API | | Fetch a user's historical rewards | API | | Build transactions for client signing | API | | Execute transactions with full customization | SDK | | Create a new liquidity vault | SDK | | Build in non-JS backend (e.g. Python) | API | | Require zero rate limits | SDK with private RPC | | Build a Rust bot | Rust Crate | | CPI from an on-chain Solana program | Rust Crate | ## Summary Use the Kamino REST API for fast data integration, history tracking, and building unsigned transactions across any backend. Use the TypeScript SDK for advanced transaction composition, simulation, and vault creation with full on-chain control. Use the Rust interface crate for Rust-native clients, high-performance bots, and CPI from on-chain Solana programs. ## Relevant links <CardGroup> <Card title="API Documentation" icon="globe" href="https://api-docs.kamino.com/"> Explore REST API endpoints and response schemas </Card> <Card title="SDK Documentation" icon="code" href="https://github.com/Kamino-Finance/klend-sdk"> Learn how to integrate the TypeScript SDK </Card> <Card title="Lending Rust Crate" icon="rust" href="https://crates.io/crates/klend-interface"> Lightweight Rust instruction builder for Kamino Lending clients and CPI </Card> <Card title="Vaults Rust Crate" icon="rust" href="https://crates.io/crates/kvault-interface"> Lightweight Rust instruction builder for Kamino Vaults clients and CPI </Card> <Card title="Borrow Operations" icon="book" href="/docs/build/developers/borrow/operations/deposit"> Step-by-step guides for deposit, withdraw, borrow, and repay </Card> <Card title="Earn Operations" icon="book" href="/docs/build/developers/earn/operations/deposit"> Step-by-step guides for vault deposit and withdraw </Card> <Card title="SDK Examples" icon="github" href="https://github.com/Kamino-Finance/klend-sdk/tree/master/examples"> View code examples in the GitHub repository </Card> </CardGroup> # Market Source: https://kamino.com/docs/build/developers/borrow/data/market-data ## Reading Market Data Retrieve market metrics, reserve information, and TVL data using the Kamino SDK and API. <Note>Historical market data is only available via the API.</Note> <Steps> <Step> ### Get Market Info Retrieves real-time market-wide metrics including total deposits and borrows TVL across all reserves. <Note> Using the SDK requires a private RPC connection or the public rate-limited [RPC endpoint](https://api.mainnet-beta.solana.com). </Note> <Tabs> <Tab title="TypeScript"> ```typescript icon="typescript" getMarketInfo 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> </Step> <Step> ### Get Reserve Info Queries detailed information for all reserves in the market including deposit/borrow TVL, APY rates, and utilization ratios. <Tabs> <Tab title="TypeScript"> ```typescript icon="typescript" getReserveInfo 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> <Tab title="Rust"> ```rust expandable title="get_market_and_reserves.rs" theme={null} // Additional deps: klend-interface = "0.1.0", solana-client = "~2.3", // solana-pubkey = "2.1", solana-account = "2.1", fixed = "1" use klend_interface::accounts::from_account_data; use klend_interface::state::{LendingMarket, Reserve}; use klend_interface::KLEND_PROGRAM_ID; use solana_client::rpc_client::RpcClient; use solana_client::rpc_config::RpcProgramAccountsConfig; use solana_client::rpc_filter::{Memcmp, RpcFilterType}; use solana_account::ReadableAccount; use solana_pubkey::Pubkey; use fixed::types::U68F60; use std::str::FromStr; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let market_pubkey = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); // Fetch and parse the lending market let market_account = rpc_client.get_account(&market_pubkey)?; let market = from_account_data::<LendingMarket>(&market_account.data)?; println!("Market authority: {}", market.lending_market_owner); // Fetch all reserves for this market using memcmp filter let filters = vec![ RpcFilterType::Memcmp(Memcmp::new_raw_bytes(32, market_pubkey.to_bytes().to_vec())), RpcFilterType::DataSize(8616), ]; let accounts = rpc_client.get_program_accounts_with_config( &KLEND_PROGRAM_ID, RpcProgramAccountsConfig { filters: Some(filters), ..Default::default() }, )?; // Parse each reserve and print key metrics // Fields suffixed with `_sf` are scaled fractions — use the `fixed` crate for precise conversion for (pubkey, account) in &accounts { let reserve = from_account_data::<Reserve>(account.data())?; let borrowed = U68F60::from_bits(reserve.liquidity.borrowed_amount_sf as u128); let price = U68F60::from_bits(reserve.liquidity.market_price_sf as u128); println!("Reserve: {pubkey}"); println!(" Available liquidity: {}", reserve.liquidity.available_amount); println!(" Borrowed amount: {borrowed}"); println!(" Market price: {price}"); println!(" Mint decimals: {}", reserve.liquidity.mint_decimals); println!(" LTV: {}%", reserve.config.loan_to_value_pct); println!(" Deposit limit: {}", reserve.config.deposit_limit); println!(" Borrow limit: {}", reserve.config.borrow_limit); } ``` <a href="https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/market_data.rs"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> </Step> <Step> ### Get Historical Reserve APY Fetch historical supply APY and borrow APY data for a specific reserve over time. ```typescript icon="typescript" getHistoricalReserveAPY theme={null} const API_BASE_URL = "https://api.kamino.finance"; const marketPubkey = "7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF"; const reservePubkey = "d4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q"; 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 { history } = await res.json(); for (const item of history) { console.log({ timestamp: item.timestamp, symbol: item.metrics.symbol, 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> </Step> </Steps> ## 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> # User Obligation Source: https://kamino.com/docs/build/developers/borrow/data/user-position-data ## Manage User Obligations Manage and retrieve user obligations, positions, and transaction history using the Kamino SDK and API. <Note>Historical obligation data is only available via the API.</Note> ### Get User Obligation Info Retrieve detailed obligation information including deposits, borrows, and health metrics. <Tabs> <Tab title="TypeScript"> ```typescript expandable title="getUserObligation.ts" 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> <Tab title="Rust"> ```rust expandable title="get_user_obligation.rs" theme={null} // Additional deps: klend-interface = "0.1.0", solana-client = "~2.3", // solana-pubkey = "2.1", fixed = "1" use klend_interface::accounts::from_account_data; use klend_interface::state::Obligation; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_client::rpc_client::RpcClient; use solana_pubkey::Pubkey; use fixed::types::U68F60; use std::str::FromStr; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let market_pubkey = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let user_pubkey = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY").unwrap(); // Derive the obligation PDA (tag 0 = Vanilla obligation) let (obligation_pubkey, _bump) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &user_pubkey, &market_pubkey, &Pubkey::default(), &Pubkey::default(), ); // Fetch and parse the obligation account let obligation_account = rpc_client.get_account(&obligation_pubkey)?; let obligation = from_account_data::<Obligation>(&obligation_account.data)?; println!("Obligation owner: {}", obligation.owner); // Active deposits println!("\nDeposits (Collateral):"); for deposit in &obligation.deposits { if deposit.deposit_reserve == Pubkey::default() { continue; } println!(" Reserve: {}", deposit.deposit_reserve); println!(" Deposited amount (cTokens): {}", deposit.deposited_amount); } // Active borrows println!("\nBorrows:"); for borrow in &obligation.borrows { if borrow.borrow_reserve == Pubkey::default() { continue; } println!(" Reserve: {}",
프로젝트로 돌아가기