Kamino 백서

Kamino

원문

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

tions. </Card> <Card title="Scope SDK repository" icon="github" href="https://github.com/Kamino-Finance/scope-sdk"> TypeScript SDK source and example scripts. </Card> <Card title="Oracle Architecture" icon="book-open" href="/docs/security/oracles"> Scope, price protection, and manipulation resistance explained. </Card> <Card title="Scope Oracle Types" icon="sliders" href="/docs/curators/markets/scope-oracle-types"> Specialized Scope oracle entry types for fixed-income, multi-source, pegged, and LST assets. </Card> </CardGroup> # Overview Source: https://kamino.com/docs/build/developers/overview The Kamino SDK, API, and Rust crate provide access to Earn vaults and Borrow markets Users deposit assets into Earn vaults or supply them to Kamino's lending markets as collateral to borrow against. Developers can integrate the same flows using the SDK's composable methods for deposits, borrows, repayments, and withdrawals. <Tip> Using AI tools or building with LLMs? Use our [llms.txt](https://kamino.com/docs/llms.txt) for a structured index of the docs, and [skill.md](https://kamino.com/docs/skill.md) for Kamino's full API and SDK capability reference. </Tip> ## Integrate Kamino Developers can integrate Kamino using the REST API, the TypeScript SDK, or the Rust interface crate. <CardGroup> <Card title="REST API" icon="globe" href="https://api-docs.kamino.com/"> REST API for vault lists, performance metrics, user positions, and transaction history. </Card> <Card title="TypeScript SDK" icon="code" href="https://github.com/Kamino-Finance/klend-sdk"> Compose on-chain transactions for deposits, borrows, repayments, and withdrawals. </Card> <Card title="Rust Interface Crate" icon="rust" href="https://crates.io/crates/klend-interface"> Lightweight instruction builder for Rust bots and on-chain CPI. </Card> </CardGroup> ## Kamino Products <CardGroup> <Card title="Borrow Markets" icon="coins" href="/docs/build/borrow/index"> Earn by supplying assets </Card> <Card title="Earn Vaults" icon="chart-line" href="/docs/build/earn/index"> Earn interest on assets </Card> </CardGroup> ## Getting Started Set up your development environment: <Steps> <Step title="Install SDK"> Install the Klend TypeScript SDK and Solana Kit packages. ```bash theme={null} npm i @kamino-finance/klend-sdk @solana/kit ``` </Step> <Step title="Setup the RPC (optional)"> Use a private RPC for reliability. Public RPCs are often rate-limited and can cause transaction failures. <Note> Multiple RPC providers are available. [Helius](https://www.helius.dev) is one option. @solana/kit is used for standardized RPC interactions with improved type safety and better handling of Solana transactions. </Note> ```typescript theme={null} import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com"); ``` </Step> <Step title="Create or Import Wallet (optional)"> Choose a method to create or import a wallet for signing transactions. <Note> Alternatively, create a wallet using a browser wallet provider like [Phantom](https://phantom.app/). </Note> <Expandable title="Create with CLI"> Use the Solana CLI to generate a new keypair file. ```bash theme={null} solana-keygen new -o wallet.json ``` </Expandable> <Expandable title="Create with Solana Kit"> Generate a new keypair programmatically using the Solana Kit. ```typescript theme={null} import { generateKeyPairSigner } from "@solana/kit"; const signer = await generateKeyPairSigner(); console.log("address: ", signer.address); ``` </Expandable> <Expandable title="Import Keypair File"> Import a wallet from an existing keypair file. ```typescript theme={null} import { createKeyPairSignerFromBytes } from '@solana/kit'; import fs from 'fs'; import path from 'path'; import os from 'os'; const resolvedPath = path.resolve( filePath.startsWith("~") ? filePath.replace("~", os.homedir()) : filePath ); const loadedKeyBytes = Uint8Array.from( JSON.parse(fs.readFileSync(resolvedPath, "utf8")) ); const signer = await createKeyPairSignerFromBytes(loadedKeyBytes); console.log(signer.address); ``` </Expandable> <Expandable title="Import Private Key"> Import a private key from an existing browser wallet. ```typescript theme={null} import { createKeyPairSignerFromBytes } from '@solana/kit'; // Get your private key from browser wallet (as Uint8Array or number array) const privateKey = new Uint8Array([/* your private key bytes */]); const signer = await createKeyPairSignerFromBytes(privateKey); ``` </Expandable> </Step> </Steps> # Kamino Portfolio API Source: https://kamino.com/docs/build/developers/portfolio/index Fetch a wallet's entire Kamino footprint across lending, multiply, leverage, liquidity, earn, private credit, and staking The Portfolio API returns a wallet's positions across **every Kamino product in one call**: lending, multiply, leverage, liquidity, earn, private credit, and staking. It's the single request a dashboard makes to paint the whole picture, plus a companion endpoint for pending farm rewards. <Note> **Source data, composed by you.** Positions arrive already valued (each carries `value`/`price`), but portfolio-wide totals, net worth, and PnL are intentionally left to client composition, so you build exactly the rollups your app needs. See [Calculate portfolio totals](/docs/build/developers/portfolio/response#calculate-portfolio-totals). </Note> <Info> **No API key required.** All Portfolio endpoints are public on `https://api.kamino.finance`. </Info> ## Endpoints | Method | Endpoint | Returns | | - | - | - | | `GET` | `/portfolio/{pubkey}` | All positions across the seven product sections | | `GET` | `/portfolio/{pubkey}/rewards` | Pending farm rewards across all products | See the full field reference in [Portfolio response](/docs/build/developers/portfolio/response). ## What you can build * **Portfolio dashboards:** render every position a wallet holds across Kamino from one request. * **Liquidation and health monitors:** read `ltv` against `liquidationLtv` on lending, multiply, and leverage positions to alert before liquidation. * **Net-worth and PnL tools:** sum `netValue` across sections and convert to USD with the [Oracle prices](/docs/build/developers/oracle/data/prices) endpoint. * **Reward trackers:** surface pending farm rewards across lending, borrowing, and liquidity in one view. ## Quickstart Fetch a wallet's full portfolio and count positions per product. ```typescript theme={null} const WALLET = 'YOUR_WALLET_ADDRESS'; // replace with your wallet pubkey const API = 'https://api.kamino.finance'; const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); console.log('Timestamp:', portfolio.timestamp); const products = ['lending', 'multiply', 'leverage', 'liquidity', 'earn', 'privateCredit', 'staking'] as const; products.forEach((p) => console.log(` ${p}: ${(portfolio[p] || []).length} position(s)`)); ``` <Note> Numeric fields are returned as **strings** (for example `"0.38"`, `"100.05"`). Parse them with `parseFloat` before doing math. </Note> ## Next steps <CardGroup> <Card title="Portfolio response" icon="table-list" href="/docs/build/developers/portfolio/response"> Full field reference for every product section, plus runnable examples. </Card> <Card title="API reference" icon="code" href="/docs/build/api-reference/portfolio/portfolio-source-data"> The raw OpenAPI spec for both Portfolio endpoints. </Card> <Card title="Oracle prices" icon="satellite-dish" href="/docs/build/developers/oracle/data/prices"> Convert position amounts to USD when composing totals. </Card> <Card title="Rewards" icon="seedling" href="/docs/build/developers/portfolio/response#pending-rewards"> Read and aggregate pending farm rewards across products. </Card> </CardGroup> # Kamino Portfolio Data Source: https://kamino.com/docs/build/developers/portfolio/response Query Portfolio API response fields across all seven Kamino products The portfolio response returns a top level object with a timestamp, a `sections` object that reports indexing status and freshness for each product, and one array for each product section. Each position is returned already valued, with its own value and price included. <Tip> Run the endpoints live in the API playground: [portfolio](/docs/build/api-reference/portfolio/portfolio-source-data) and [pending rewards](/docs/build/api-reference/portfolio/portfolio-rewards). </Tip> ## Parameters | Parameter | In | Required | Description | | - | - | - | - | | `pubkey` | path | Yes | Wallet address (base58). | | `programId` | query | No | KLend program ID to scope results. | ## Response object | Field | Type | Description | | - | - | - | | `timestamp` | string | ISO timestamp of the response. | | `sections` | object | Indexing status and freshness per product. See [Section state](#shared-building-blocks). | | `lending` `multiply` `leverage` | array | Borrow-side obligations (see the **Position fields** tabs). | | `liquidity` `earn` `privateCredit` `staking` | array | The remaining product positions. | ## Position fields by product <Tabs> <Tab title="Lending, Multiply & Leverage"> One entry per obligation. The `tag` field distinguishes the kind (`Vanilla`, `Multiply`, and so on). Multiply and leverage entries add `depositMint` and `borrowMint`. | Field | Type | Description | | - | - | - | | `obligation` | string | Obligation pubkey. | | `market` | string | Lending market pubkey. | | `tag` | string | Obligation kind (`Vanilla`, `Multiply`, …). | | `netValue` | string | USD net value (deposits minus borrows). | | `totalDepositValue` | string | USD value of all deposits. | | `totalBorrowValue` | string | USD value of all borrows. | | `ltv` | string | Current loan-to-value (for example `"0.38"`). | | `maxLtv` | string | Maximum borrowing LTV. | | `liquidationLtv` | string | LTV at which liquidation triggers. | | `leverage` | string | Position leverage (for example `"1.56"`). | | `deposits` | array | Deposited assets ([Token object](#shared-building-blocks)). | | `borrows` | array | Borrowed assets ([Token object](#shared-building-blocks)). | | `depositMint` | string | Multiply and leverage only: collateral mint. | | `borrowMint` | string | Multiply and leverage only: debt mint. | </Tab> <Tab title="Liquidity"> | Field | Type | Description | | - | - | - | | `strategy` | string | Strategy pubkey. | | `shareMint` | string | Share token mint. | | `shares` | string | Share balance. | | `netValue` | string | USD value of the position. | | `tokenA` | object | First pool token ([Token object](#shared-building-blocks)). | | `tokenB` | object | Second pool token ([Token object](#shared-building-blocks)). | </Tab> <Tab title="Earn & Private Credit"> | Field | Type | Description | | - | - | - | | `vault` | string | Vault pubkey. | | `tokenMint` | string | Deposit token mint. | | `symbol` | string | Token symbol. | | `name` | string | Vault name (for example `Steakhouse USDC`). | | `netValue` | string | USD value of the position. | | `shares` | string | Vault shares held. | | `amount` | string | Underlying token amount. | </Tab> <Tab title="Staking"> | Field | Type | Description | | - | - | - | | `mint` | string | Staked token mint. | | `symbol` | string | Token symbol. | | `farm` | string | Farm pubkey. | | `amount` | string | Staked amount. | | `value` | string | USD value. | | `price` | string | Token price. | </Tab> </Tabs> ## Shared building blocks <AccordionGroup> <Accordion title="Token object (deposits, borrows, tokenA, tokenB)"> Entries in `deposits`, `borrows`, and the liquidity `tokenA` / `tokenB` share a common shape, with a few context-specific extras. | Field | Type | Description | | - | - | - | | `mint` | string | Token mint. | | `symbol` | string | Token symbol. | | `amount` | string | Token amount. | | `value` | string | USD value. | | `price` | string | Token price. | | `reserve` | string | Reserve pubkey (deposits and borrows). | | `maxLtv` | string | Deposits only: collateral max LTV. | | `liquidationLtv` | string | Deposits only: collateral liquidation LTV. | | `borrowFactor` | string | Borrows only: borrow factor. | </Accordion> <Accordion title="Section state (sections object)"> Each product key in `sections` reports whether the wallet has data and how fresh it is. A section with `indexed: false` has no data for this wallet. | Field | Type | Description | | - | - | - | | `indexed` | boolean | `false` means no data for this wallet and product. | | `positionsRefreshedOn` | string \| null | ISO timestamp positions were last refreshed. | | `pricesRefreshedOn` | string \| null | ISO timestamp prices were last refreshed. | | `errors` | array | Errors encountered while loading this section. | </Accordion> </AccordionGroup> ## Pending rewards `GET /portfolio/{pubkey}/rewards` returns pending farm rewards across products: a `timestamp` and a `farms` array. Each farm entry lists its pending `rewards`. | Field | Type | Description | | - | - | - | | `farm` | string | Farm pubkey. | | `userState` | string | User state pubkey. | | `delegatee` | string | Wallet pubkey. | | `positionType` | string | Human-readable source (for example `Borrow Markets`). | | `activeStakeAmount` | string | Active staked amount. | | `tokenMints` | array | Associated token mints. | | `rewards` | array | Pending rewards (see below). | <Accordion title="Reward entry fields"> | Field | Type | Description | | - | - | - | | `mint` | string | Reward token mint. | | `amount` | string | Pending amount. | | `index` | number | Reward index. | | `type` | number | Reward type. | | `tokenProgram` | string | Token program of the reward mint. | </Accordion> ## Examples <Steps> <Step> ### Calculate LTV and liquidation headroom for each lending position Compare `ltv` against `liquidationLtv` to measure how close a position is to liquidation. ```typescript icon="typescript" lendingPositions theme={null} const WALLET = 'YOUR_WALLET_ADDRESS'; const API = 'https://api.kamino.finance'; const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); (portfolio.lending || []).forEach((pos, i) => { const ltvPct = (parseFloat(pos.ltv) * 100).toFixed(2); const liqPct = (parseFloat(pos.liquidationLtv) * 100).toFixed(2); const headroom = ((parseFloat(pos.liquidationLtv) - parseFloat(pos.ltv)) * 100).toFixed(2); console.log(`\n--- Lending position ${i + 1} (${pos.tag}) ---`); console.log(` Net value: $${parseFloat(pos.netValue).toFixed(2)}`); console.log(` LTV: ${ltvPct}% (liq ${liqPct}%)`); console.log(` Headroom: ${headroom}% before liquidation`); }); ``` </Step> <Step> ### List earn vault positions with shares and USD value ```typescript icon="typescript" earnPositions theme={null} const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); (portfolio.earn || []).forEach((pos) => { console.log({ vault: pos.vault, name: pos.name, symbol: pos.symbol, shares: pos.shares, amount: parseFloat(pos.amount).toFixed(6), netValueUsd: '$' + parseFloat(pos.netValue).toFixed(4), }); }); ``` </Step> <Step> ### Check which product sections are stale or failed to load Use `sections` to decide whether positions are stale or a product failed to load. ```typescript icon="typescript" sectionFreshness theme={null} const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); const now = Date.now(); Object.entries(portfolio.sections).forEach(([name, sec]) => { if (!sec.indexed) return console.log(`${name}: not indexed`); const age = (ts) => (ts ? ((now - new Date(ts).getTime()) / 60_000).toFixed(1) + 'm ago' : 'never'); const errors = sec.errors.length ? ` ⚠ ${sec.errors.length} error(s)` : ''; console.log(`${name}: positions ${age(sec.positionsRefreshedOn)}, prices ${age(sec.pricesRefreshedOn)}${errors}`); }); ``` </Step> <Step> ### List pending farm rewards across all products ```typescript icon="typescript" pendingRewards theme={null} const rewards = await (await fetch(`${API}/portfolio/${WALLET}/rewards?rewardTypes=0,1,2,3`)).json(); const farms = rewards.farms || []; console.log(`Pending rewards across ${farms.length} farm(s):`); farms.forEach((f) => { console.log(`\n Farm: ${f.farm} (${f.positionType})`); (f.rewards || []).forEach((r) => console.log(` ${r.amount} (mint ${r.mint}, type ${r.type})`)); }); ``` </Step> <Step> ### Sum total portfolio value and break it down per product Sum `netValue` from each section (and `value` for staking) for a portfolio total, then break it down per product. ```typescript icon="typescript" totalValue theme={null} const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); const products = ['lending', 'multiply', 'leverage', 'liquidity', 'earn', 'privateCredit', 'staking']; let totalValue = 0; const breakdown = []; products.forEach((p) => { const positions = portfolio[p] || []; const value = positions.reduce((sum, pos) => sum + parseFloat((p === 'staking' ? pos.value : pos.netValue) || '0'), 0); totalValue += value; if (positions.length) breakdown.push({ product: p, value, count: positions.length }); }); console.log(`Total portfolio value: $${totalValue.toFixed(2)}`); breakdown .sort((a, b) => b.value - a.value) .forEach((b) => console.log(` ${b.product}: $${b.value.toFixed(2)} (${b.count} position(s))`)); ``` </Step> </Steps> ## Calculate portfolio totals The API returns valued positions but no portfolio-wide rollups, so you compose them: * **Net worth:** sum `netValue` across every section, except **staking**, which exposes `value` instead. Multiply and leverage `netValue` is already deposits minus borrows, so totals reflect real equity. * **USD conversion:** positions carry `value` and `price`, but for any raw amounts you price yourself, use the [Oracle prices](/docs/build/developers/oracle/data/prices) endpoint. # Farms Source: https://kamino.com/docs/build/developers/rewards/data/farm-state Read farm state, discover farms, and compute reward APY with the Kamino Farms SDK ## Reading Farm Data <Note> A **delegated** farm (for example a klend reserve farm or a kvault farm) has no stake-token mint of its own. A delegate authority stakes on users' behalf, so `farmState.token.mint` is empty and `farmState.delegateAuthority` is set. A **non-delegated** farm owns its stake token, so `farmState.token` gives the stake mint and decimals. For the TypeScript shapes used below, see [Farm Types](#farm-types). </Note> <Accordion title="Farm state fields reference"> A `FarmState` account exposes the values below. An `Address` field set to the default pubkey means it is unused, for example `strategyId` and `vaultId` on a farm attached to neither. | Field | Type | Description | | - | - | - | | `token` | `TokenInfo` | Stake token: mint, decimals, and token program. Empty on delegated farms. | | `rewardInfos` | `RewardInfo[]` | Fixed-size array of reward slots. Only slots with a real mint are active. | | `numRewardTokens` | `BN` | Count of active reward tokens. | | `totalStakedAmount` | `BN` | Total tokens staked and earning rewards, in raw units. | | `isFarmDelegated` | `number` | `1` when the farm is delegated, so a delegate authority stakes on users' behalf. | | `isFarmFrozen` | `number` | `1` when the farm is frozen and no new deposits are allowed. | | `delegateAuthority` | `Address` | The delegate that stakes for users. Set only on delegated farms. | | `depositWarmupPeriod` | `number` | Seconds between a deposit and when it starts earning. `0` if unused. | | `withdrawalCooldownPeriod` | `number` | Seconds between unstaking and being able to withdraw. | | `depositCapAmount` | `BN` | Maximum total stake the farm accepts, in raw units. | | `lockingDuration` | `BN` | Deposit loc
프로젝트로 돌아가기