Kamino 백서

Kamino

원문

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

mF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6"); const UNSTAKE_AMOUNT = new Decimal(0.02); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); const farmState = await FarmState.fetch(rpc, FARM); if (!farmState) console.log(`Farm not found: ${FARM}`); const existing = await farms .getUserStateKeyForUndelegatedFarm(signer.address, FARM) .catch(() => null); if (!existing) console.log("No position on this farm to unstake."); const scopePrices = getScopePricesFromFarm(farmState); const decimals = farmState.token.decimals.toNumber(); const userState = await UserState.fetch(rpc, existing.key); const activeStakeScaled = new Decimal(userState.activeStakeScaled.toString()); const requestedScaled = UNSTAKE_AMOUNT.mul(new Decimal(10).pow(decimals)).mul(WAD); const amountScaled = Decimal.min(requestedScaled, activeStakeScaled); const instructions = [ await farms.refreshFarmIx(FARM, scopePrices), await farms.refreshUserIx(existing.key, FARM, scopePrices), await farms.unstakeIx(signer, FARM, amountScaled, scopePrices), ]; const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Unstake successful! Signature:", signature); ``` # Withdraw Source: https://kamino.com/docs/build/developers/rewards/operations/withdraw-unstaked Withdraw unstaked tokens from a Kamino farm to your wallet ## Withdraw The second half of unwinding a position. After you [unstake](/docs/build/developers/rewards/operations/unstake) and the farm's withdrawal cooldown elapses, the stake sits as pending withdrawal. This moves those tokens out of the farm vault back to your token account. <Note> This flow requires a non-delegated farm, since the instruction needs the stake token mint. No Scope prices or refresh are needed here, because it moves already-unstaked tokens and does not touch reward accounting. The instruction only succeeds on-chain once the withdrawal cooldown has elapsed; if there is nothing past cooldown, it fails. </Note> <Steps> <Step> ### Import Dependencies Import the packages for Solana RPC communication, Kit transaction building, the keypair loader, and the Farms SDK. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms } from "@kamino-finance/farms-sdk"; ``` </Step> <Step> ### Configure Constants and Initialize Set the keypair path, RPC endpoints, target farm, and stake token mint. Load the signer and initialize the farms client. ```typescript theme={null} const KEYPAIR_FILE = "/path/to/your/keypair.json"; const RPC_ENDPOINT = "https://api.mainnet-beta.solana.com"; const WS_ENDPOINT = "wss://api.mainnet-beta.solana.com"; const FARM = address("DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi"); // non-delegated farm const STAKE_MINT = address("AYUjc3a3QQUiLE6jP7V29UMeUZGADdtiVxhSjoLcqYwr"); // the farm's stake token const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); ``` </Step> <Step> ### Build Withdraw Instruction Resolve the user-state key, then build the withdraw-unstaked instruction. The third argument is the farm address. ```typescript theme={null} const { key: userState } = await farms.getUserStateKeyForUndelegatedFarm( signer.address, FARM, ); const instructions = [ await farms.withdrawUnstakedDepositIx(signer, userState, FARM, STAKE_MINT), ]; ``` </Step> <Step> ### Build, Sign, and Send Transaction Compose the v0 transaction, sign, verify it fits the size limit, then send and confirm. ```typescript theme={null} const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Withdraw-unstaked successful! Signature:", signature); ``` <Check> The withdrawal is complete. Your unstaked tokens have been transferred back to your wallet. </Check> </Step> </Steps> #### Full Code Example ```typescript expandable theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms } from "@kamino-finance/farms-sdk"; const KEYPAIR_FILE = "/path/to/your/keypair.json"; const RPC_ENDPOINT = "https://api.mainnet-beta.solana.com"; const WS_ENDPOINT = "wss://api.mainnet-beta.solana.com"; const FARM = address("DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi"); const STAKE_MINT = address("AYUjc3a3QQUiLE6jP7V29UMeUZGADdtiVxhSjoLcqYwr"); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); const { key: userState } = await farms.getUserStateKeyForUndelegatedFarm( signer.address, FARM, ); const instructions = [ await farms.withdrawUnstakedDepositIx(signer, userState, FARM, STAKE_MINT), ]; const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Withdraw-unstaked successful! Signature:", signature); ``` # Farms Source: https://kamino.com/docs/build/developers/rewards/overview Learn how to build with Kamino Farms, the rewards distribution layer for Kamino products ## Overview Kamino Farms is the rewards distribution layer for Kamino products. Farms distribute incentive tokens to depositors, suppliers, and borrowers across the protocol, including KMNO emissions on vaults and lending positions. The TypeScript SDK provides access to farm and user state, along with instructions to stake, unstake, and harvest rewards. <Note> Farms attached to lending positions and kvaults are **delegated**: position accounting lives in the parent program (klend or kvault), and unstake is a two-step flow gated by a cooldown. Read [Farm rewards](/docs/curators/vaults/concepts/yield-and-fees#farm-rewards) for the conceptual model before integrating. </Note> ## Key Components of Farms Integration <CardGroup> <Card title="Farm State" icon="database"> Decode a farm's reward tokens, per-second emission rates, total staked amount, cooldown period, and scope-oracle binding. </Card> <Card title="User Positions" icon="user"> Read a wallet's stake across one or many farms, pending rewards per reward token, and pending-unstake cooldown status. </Card> <Card title="Stake & Claim" icon="hand-holding-dollar"> Initialize user state, stake / unstake (with cooldown handling), and harvest accrued rewards in one or all reward tokens. </Card> </CardGroup> ## Locating a Farm Address The SDK reads any farm given its pubkey. Three places that pubkey can come from: | Source | Where to look | | - | - | | **CDN** | `https://cdn.kamino.finance/resources.json`, under `mainnet-beta.extraFarms`. | | **Klend reserve fields** | A reserve account's `state.farmCollateral` (supply side) or `state.farmDebt` (borrow side) field. | | **Kvault state** | A kvault account's `state.vaultFarm` field. List vaults at `https://api.kamino.finance/kvaults/vaults`. | ## Integration Options <CardGroup> <Card title="TypeScript SDK" icon="code"> On-chain reads and transaction building for stake, unstake, harvest, and user-state management. TS/JS only. </Card> </CardGroup> ### Stake <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { Farms, FarmState } from '@kamino-finance/farms-sdk'; import { getScopePricesFromFarm } from '@kamino-finance/farms-sdk/dist/utils/option'; import Decimal from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const farms = new Farms(rpc); const FARM = address('9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6'); const STAKE_MINT = address('3EmfhZ3KUaYdwKZ9CwfGoKRqQqUV1MhSCVL5Ch7szX7e'); const farmState = await FarmState.fetch(rpc, FARM); if (!farmState) console.log(`Farm not found: ${FARM}`); const scopePrices = getScopePricesFromFarm(farmState); const amountLamports = new Decimal(0.02).mul( new Decimal(10).pow(farmState.token.decimals.toNumber()), ); // Refresh the farm so reward accounting is current, then stake. const instructions = [ await farms.refreshFarmIx(FARM, scopePrices), await farms.stakeIx(signer, FARM, amountLamports, STAKE_MINT, scopePrices), ]; console.log('Stake Instructions:', instructions); ``` <a href="https://github.com/Kamino-Finance/farms-sdk"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> <Note> For the full stake flow including first-time user-state creation and transaction confirmation, see [Stake](/docs/build/developers/rewards/operations/stake). </Note> ### Unstake <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { Farms, FarmState } from '@kamino-finance/farms-sdk'; import { getScopePricesFromFarm } from '@kamino-finance/farms-sdk/dist/utils/option'; import { WAD } from '@kamino-finance/farms-sdk/dist/utils/utils'; import Decimal from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const farms = new Farms(rpc); const FARM = address('9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6'); const farmState = await FarmState.fetch(rpc, FARM); if (!farmState) console.log(`Farm not found: ${FARM}`); const scopePrices = getScopePricesFromFarm(farmState); const { key: userStateKey } = await farms.getUserStateKeyForUndelegatedFarm(signer.address, FARM); // unstakeIx takes WAD-scaled shares. Refresh the farm and user, then unstake. const amountScaled = new Decimal(0.02) .mul(new Decimal(10).pow(farmState.token.decimals.toNumber())) .mul(WAD); const instructions = [ await farms.refreshFarmIx(FARM, scopePrices), await farms.refreshUserIx(userStateKey, FARM, scopePrices), await farms.unstakeIx(signer, FARM, amountScaled, scopePrices), ]; console.log('Unstake Instructions:', instructions); ``` <a href="https://github.com/Kamino-Finance/farms-sdk"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> <Note> Unstaking starts the withdrawal cooldown. After it elapses, withdraw the tokens back to your wallet. See [Unstake](/docs/build/developers/rewards/operations/unstake). </Note> ## What's Covered <CardGroup> <Card title="Farms" icon="database" href="/docs/build/developers/rewards/data/farm-state"> Read farm state, discover farms, and compute or simulate incentive APY. </Card> <Card title="User Position Data" icon="user" href="/docs/build/developers/rewards/data/user-position"> Fetch a wallet's stake, lockup and cooldown status, and pending rewards. </Card> <Card title="Stake" icon="arrow-down-to-line" href="/docs/build/developers/rewards/operations/stake"> Initialize user state and stake share tokens into a farm. </Card> <Card title="Unstake" icon="arrow-up-from-line" href="/docs/build/developers/rewards/operations/unstake"> Unstake into pending withdrawal and start the cooldown. </Card> <Card title="Withdraw" icon="wallet" href="/docs/build/developers/rewards/operations/withdraw-unstaked"> Move unstaked tokens back to your wallet after the cooldown. </Card> <Card title="Harvest" icon="hand-holding-dollar" href="/docs/build/developers/rewards/operations/harvest"> Claim all pending reward tokens in one transaction. </Card> </CardGroup> ## Relevant Links <CardGroup> <Card title="Farms SDK repository" icon="github" href="https://github.com/Kamino-Finance/farms-sdk"> TypeScript SDK source, on-chain program docs, and example scripts. </Card> <Card title="KFarms program" icon="github" href="https://github.com/Kamino-Finance/kfarms"> Rust source for the on-chain farms program. </Card> <Card title="NPM SDK package" icon="npm" href="https://www.npmjs.com/package/@kamino-finance/farms-sdk"> Install the TypeScript SDK to integrate reward operations. </Card> <Card title="Farm Rewards Concepts" icon="book-open" href="/docs/curators/vaults/concepts/yield-and-fees#farm-rewards"> Vault Farm, Autocompound, Insurance Pool farm, and cooldowns explained. </Card> </CardGroup> # Create a distributor Source: https://kamino.com/docs/build/distributors/create-a-distributor /kamino-api.json post /distributors Registers a distributor under a unique name and returns its generated 5-character memo code. Private (authorized) API access only, please add a basic auth header to your request. # Get distributor-tagged transactions of a vault Source: https://kamino.com/docs/build/distributors/get-distributor-tagged-transactions-of-a-vault /kamino-api.json get /kvaults/vaults/{pubkey}/distributor-transactions Cursor-paginated list of deposits into and withdrawals out of a Kamino Earn vault whose transaction carried a distributor code, newest first. One row per instruction, so a transaction with several gives several rows. Private (authorized) API access only, please add a basic auth header to your request. # Get per-wallet totals for a distributor code Source: https://kamino.com/docs/build/distributors/get-per-wallet-totals-for-a-distributor-code /kamino-api.json get /kvaults/distributors/{code}/wallets For each wallet that transacted under this distributor code in the range: the total amount per token and direction, deposits and withdrawals as separate lines. Private (authorized) API access only, please add a basic auth header to your request. # Get transactions tagged with a distributor code Source: https://kamino.com/docs/build/distributors/get-transactions-tagged-with-a-distributor-code /kamino-api.json get /kvaults/distributors/{code}/transactions Cursor-paginated list of deposits and withdrawals, across every Kamino Earn vault, whose transaction carried this distributor code, newest first. One row per instruction. Private (authorized) API access only, please add a basic auth header to your request. # Get transactions tagged with a distributor code on one vault Source: https://kamino.com/docs/build/distributors/get-transactions-tagged-with-a-distributor-code-on-one-vault /kamino-api.json get /kvaults/distributors/{code}/vaults/{vault}/transactions Cursor-paginated list of deposits into and withdrawals out of one Kamino Earn vault whose transaction carried this distributor code, newest first. One row per instruction. Private (authorized) API access only, please add a basic auth header to your request. # Get a wallet earn activity feed Source: https://kamino.com/docs/build/earn/get-a-wallet-earn-activity-feed /kamino-api.json get /v3/earn/users/{userPubkey}/activity Get cursor-paginated vault and filtered lending deposits, direct and withdraw-queue withdrawals, repayments, and daily interest accrual. Current-day interest can grow until the day closes. # Get a wallet earn summary Source: https://kamino.com/docs/build/earn/get-a-wallet-earn-summary /kamino-api.json get /v3/earn/users/{userPubkey}/summary Get live vault and lending deposits, idle eligible holdings, APYs, and wallet-global lifetime interest by token for the requested obligation types. Pass Vanilla,Lending,LendingFixedRate for Earn products. # Get Vault APYs Source: https://kamino.com/docs/build/earn/get-vault-apys Fetch vault APY data using the API or SDK ## How Vault APY Is Calculated Vault APY is a blended rate based on the reserves the vault's capital is deployed across. ``` Vault APY ≈ Σ (Reserve APY × Allocation Weight) ``` Each reserve earns yield based on its utilization and borrow rate. A reserve at 80% utilization earning 8% APY contributes to the vault's total yield based on its allocation weight, the share of capital deployed there. Allocation weights sum to 100% across all active reserves. **Example — a USDC vault with two allocations:** | Reserve | Allocation | APY | | - | - | - | | USDC SOL/BTC Market | 60% | 8% | | USDC JLP Market | 40% | 12% | ``` Blended APY = (60% × 8%) + (40% × 12%) = 9.6% ``` Underlying borrow rates and utilization levels change continuously, so vault APY fluctuates. Quoted APYs are trailing averages and are not guaranteed forward-looking rates. The displayed APY includes base interest from borrowers plus KMNO emissions when active. APY accounts for compounding. In Kamino vaults, earnings are continuously reinvested, increasing the vault share price over time. <Tabs> <Tab title="API"> <Steps> <Step> ### Fetch All Vaults Retrieve the list of all available vaults on Kamino. ```typescript theme={null} const API_BASE_URL = 'https://api.kamino.finance'; const response = await fetch(`${API_BASE_URL}/kvaults/vaults`); const vaults = await response.json(); ``` <Info> The `/kvaults/vaults` endpoint returns all vaults with basic information including vault addresses, token mints, and strategies. </Info> </Step> <Step> ### Get APY for Each Vault Fetch APY metrics for all vaults in parallel using the vault public keys. ```typescript theme={null} // Fetch all vault metrics in parallel const vaultMetrics = await Promise.all( vaults.map(async (vault) => { const response = await fetch( `${API_BASE_URL}/kvaults/vaults/${vault.address}/metrics` ); const metrics = await response.json(); return { address: vault.address, apy7d: metrics.apy7d, apy30d: metrics.apy30d, apy90d: metr
프로젝트로 돌아가기