Kamino 백서

Kamino

원문

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

d: '2025-10-01T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/history?${params}`; 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) { console.log({ createdOn: item.createdOn, sharesAmount: item.sharesAmount, usdAmount: item.usdAmount, cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, }); } ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-08-get-user-vault-position-historical-info-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Get User Total Metrics History Queries cumulative performance metrics for a user across all vaults over a time range. Returns aggregated time-series data including total positions and earnings. ```typescript icon="typescript" getUserTotalMetricsHistory theme={null} const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2024-01-01T00:00:00.000Z', end: '2025-11-20T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/metrics/history?${params}`; 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) { console.log({ createdOn: item.createdOn, usdAmount: item.usdAmount, solAmount: item.solAmount, weightedApy: item.weightedApy, cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, }); } ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-09-get-user-all-vaults-positions-historical-info-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Get User Vault Metrics History Retrieves historical performance metrics for a specific user and vault. Returns time-series data including shares, APY, and cumulative interest earned. ```typescript icon="typescript" getUserVaultMetricsHistory theme={null} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/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) { console.log({ createdOn: item.createdOn, sharesAmount: item.sharesAmount, apy: item.apy, cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, }); } ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-10-get-vault-historical-info-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Get User Vault PnL Retrieves current profit and loss data for a user's position in a specific vault. Returns PnL metrics in USD, SOL, and token denominations. ```typescript icon="typescript" getUserVaultPnL theme={null} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const url = `${API_BASE_URL}/kvaults/${kvaultPubkey}/users/${ownerPubkey}/pnl`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log({ totalPnlUsd: data.totalPnl.usd, totalPnlSol: data.totalPnl.sol, totalPnlToken: data.totalPnl.token, totalCostBasisUsd: data.totalCostBasis.usd, }); ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-11-get-vault-user-pnl-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Get User Vault PnL History Queries historical profit and loss data for a user's vault position. Returns transaction-level PnL history with cost basis, realized gains, and position values. ```typescript icon="typescript" getUserVaultPnLHistory theme={null} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/pnl/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, pnlUsd: item.pnl?.usd, costBasisUsd: item.costBasis?.usd, positionValueUsd: item.positionValue?.usd, }); } ``` <a href="https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial"> <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/kvault-tutorial" /> </CardGroup> # Vault Source: https://kamino.com/docs/build/developers/earn/data/vault-data ## Reading Vault Data Retrieve vault TVL, APY, farm rewards, allocation weights, and user share balances using the Kamino SDK and API. <Note> Historical vault data is only available via the API. </Note> <Steps> <Step> ### Get All Vaults This fetches all available Kamino vaults from the API, and returns an array of vault objects containing address, state, and configuration data for each vault. ```typescript icon="typescript" getAllVaults theme={null} const url = 'https://api.kamino.finance/kvaults/vaults'; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const vaults = await res.json(); console.log({ address: vaults[0].address, name: vaults[0].state.name, tokenMint: vaults[0].state.tokenMint, sharesIssued: vaults[0].state.sharesIssued, tokenAvailable: vaults[0].state.tokenAvailable, }); ``` <a href="https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Get Vault Info Retrieves real-time vault metrics including holdings, APY rates, and exchange rate. And uses the SDK to query on-chain vault state and performance data. <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" getVaultInfo theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), // RPC address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E') // USDC vault ); console.log({ holdings: (await vault.getVaultHoldings()).asJSON(), apys: await vault.getAPYs(), exchangeRate: (await vault.getExchangeRate()).toString(), }); ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-01-get-vault-info-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> <Tab title="Rust"> <Info> Read and inspect a vault's on-chain state with the [`kvault-interface`](https://crates.io/crates/kvault-interface) crate — configuration, fees, AUM, and per-reserve allocations — using zero-copy deserialization, no SDK or RPC framework required beyond `solana-client`. </Info> <Steps> <Step> ### Add Dependencies ```toml theme={null} [dependencies] kvault-interface = "0.1.0" solana-client = "2.3" solana-pubkey = "2.1" ``` </Step> <Step> ### Fetch and Parse the Vault `from_account_data::<VaultState>` deserializes the raw account bytes into a zero-copy `VaultState` view. ```rust theme={null} use std::str::FromStr; use kvault_interface::{ from_account_data, state::{VaultAllocation, VaultState}, Fraction, }; use solana_client::rpc_client::RpcClient; use solana_pubkey::Pubkey; let rpc = RpcClient::new("https://api.mainnet-beta.solana.com".to_string()); let vault_pubkey = Pubkey::from_str("HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E").unwrap(); let vault_account = rpc.get_account(&vault_pubkey).unwrap(); let vault = from_account_data::<VaultState>(&vault_account.data).unwrap(); ``` </Step> <Step> ### Read Vault Configuration ```rust theme={null} println!("Vault: {vault_pubkey}"); println!(" Admin: {}", vault.vault_admin_authority); println!(" Token mint: {}", vault.token_mint); println!(" Available liquidity: {}", vault.token_available); println!(" Shares issued: {}", vault.shares_issued); println!(" Performance fee: {} bps", vault.performance_fee_bps); println!(" Management fee: {} bps", vault.management_fee_bps); let prev_aum = Fraction::from_bits(u128::from(vault.prev_aum_sf)); println!(" Previous AUM: {prev_aum:.6}"); ``` <Note> Fields suffixed with `_sf` are **scaled fractions** (fixed-point integers, 68 integer bits + 60 fractional bits). Convert them to a readable decimal with `Fraction::from_bits(u128::from(value))`. </Note> </Step> <Step> ### Inspect Per-Reserve Allocations The vault splits its assets across Klend reserves. Empty slots have a default `reserve` pubkey, so filter those out. ```rust theme={null} let active_allocations: Vec<&VaultAllocation> = vault .vault_allocation_strategy .iter() .filter(|a| a.reserve != Pubkey::default()) .collect(); println!("\n Active allocations: {}", active_allocations.len()); for alloc in &active_allocations { let target = Fraction::from_bits(u128::from(alloc.token_target_allocation_sf)); println!(" Reserve: {}", alloc.reserve); println!(" Weight: {}", alloc.target_allocation_weight); println!(" cToken balance: {}", alloc.ctoken_allocation); println!(" Token cap: {}", alloc.token_allocation_cap); println!(" Target allocation: {target:.6}"); } ``` </Step> </Steps> <a href="https://github.com/Kamino-Finance/kvault/blob/master/libs/kvault-interface/examples/vault_data.rs"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> </Step> <Step> ### Get User Vault Position Historical Info This queries historical performance metrics for a specific user's position in a vault over a time range, and returns time-series data including the user's balance, yield, and allocation changes. ```typescript icon="typescript" getUserVaultPositionHistory theme={null} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2024-01-01T00:00:00.000Z', end: '2025-01-01T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/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 href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-10-get-vault-historical-info-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Get Vault Metrics History Retrieves historical vault-level performance metrics including TVL, APY, and farm rewards APY. Returns time-series data showing the vault's total value locked, yield rates, and reward rates over time. ```typescript icon="typescript" getVaultMetricsHistory theme={null} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2024-06-01T00:00:00.000Z', end: '2025-01-01T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/kvaults/vaults/${kvaultPubkey}/metrics/history?${params}`; 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) { console.log({ tvl: item.tvl, apy: item.apy, apyFarmRewards: item.apyFarmRewards, }); } ``` <a href="https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Get Advanced Vault Allocation Info Queries the vault's allocation strategy showing how funds are distributed across different reserves with their target weights and current allocations. ```typescript icon="typescript" getVaultAllocations theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), // RPC address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E') // USDC vault ); const allocations = await vault.getVaultAllocations(); for (const [address, overview] of allocations) { console.log( `Reserve: ${address}: weight ${overview.targetWeight.toString()}, allocation: ${overview.ctokenAllocation.toString()}` ); } ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-07-get-vault-advanced-info-incentives-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Get Advanced Vault Incentives Info Retrieves detailed incentive information for the vault including delegated farm rewards, reserve farm incentives, and direct vault farm incentives along with comprehensive vault overview metrics. ```typescript icon="typescript" getVaultIncentives theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E') // USDC vault ); const kaminoManager = new KaminoManager(rpc); const vaultTokenPrice = new Decimal(1.0); // as it is an USDC vault the token price is 1 const vaultOverview = await kaminoManager.getVaultOverview(vault, vaultTokenPrice); console.log('vaultOverview', vaultOverview); console.log('delegated farm incentives', vaultOverview.delegatedFarmIncentives); console.log('reserves farm incentives', vaultOverview.reservesFarmsIncentives); console.log('vault farm incentives', vaultOverview.vaultFarmIncentives); ``` <a href="https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-07-get-vault-advanced-info-incentives-example/index.ts"> <Icon icon="github" /> <span>View Code</span> </a> </Step> <Step> ### Vault Revenue Share Earn revenue by deploying vaults with custom fee structures. Set performance fees on profits and management fees on assets under management. ```typescript icon="typescript" vaultRevenueShare theme={null} import { createSolanaRpc, address, generateKeyPairSigner } from '@solana/kit'; import { KaminoManager, KaminoVaultConfig } from '@kamino-finance/klend-sdk'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { Decimal } from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const adminSigner = await generateKeyPairSigner(); const tokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const kaminoManager = new KaminoManager(rpc); const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: tokenMint, tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(10.0), // 10% performance fee on profits managementFeeRatePercentage: new Decimal(1.0), // 1% annual management fee on AUM name: 'Revenue Share Vault', vaultTokenSymbol: 'kUSDC', vaultTokenName: 'kUSDC receipt', }); ``` <a href="https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial"> <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/kvault-tutorial" /> </CardGroup> # Earn Vaults Source: https://kamino.com/docs/build/developers/earn/index Learn how to build with Earn ## Overview Integrating Kamino's Earn vaults lets users supply tokens to curated lending strategies on Solana. Deposits are routed to lending markets according to the vault configuration, and interest from borrowers becomes yield for depositors. On deposit, users receive share tokens representing their position. If the vault has a farm attached, shares are automatically staked in the farm and are not visible in the user's wallet. If the vault has no farm, shares remain in the user's wallet. ## Key Components of Earn Integration <CardGroup> <Card title="Vault Operations" icon="box"> Deposit, withdraw, and track user positions in the Lend program. </Card> <Card title="Yield Tracking" icon="chart-line"> Read APY and performance from the public API or on-chain accounts, present recent and longer windows. </Card> </CardGroup> ## Ways to Fetch Data <CardGroup> <Card title="Public API" icon="globe"> Simplest source for vault lists, APY, TVL, status. </Card> <Card title="SDK" icon="code"> Helpers to deposit, withdraw, and read user positions. </Card> </CardGroup> ### Deposit <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E') ); // Deposit 100 USDC const depositIxs = await vault.depositIxs( user, // TransactionSigner (multisig cannot sign directly) new Decimal(100.0) // amount in tokens ); console.log('Deposit Instructions:', depositIxs); ``` <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 expandable theme={null} use kvault_interface::{ from_account_data, helpers, pda, state::VaultState, ReserveInfo, VaultInfo, KVAULT_PROGRAM_ID, }; use solana_client::rpc_client::RpcClient; use solana_pubkey::Pubkey; use spl_associated_token_account::get_associated_token_address; let rpc = RpcClient::new("https://api.mainnet-beta.solana.com".to_string()); let vault_pubkey: Pubkey = "HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E".parse().unwrap(); // Load the vault + its active reserves (their lending markets are needed to refresh klend on-chain) let vault_data = rpc.get_account(&vault_pubkey).unwrap(); let vault_state = from_account_data::<VaultState>(&vault_data.data).unwrap(); let mut reserve_infos = Vec::new(); for reserve in VaultInfo::active_reserve_addresses(vault_state) { let acc = rpc.get_account(&reserve).unwrap
프로젝트로 돌아가기