Kamino 백서

Kamino

원문

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

amino", "lending vaults", "yield", "vault shares", "auto-compounding"] } } ``` # Kamino Program Addresses Source: https://kamino.com/docs/build/resources/program-addresses The official program addresses for Kamino's protocols across different environments ## Klend | Environment | Address | | - | - | | Mainnet | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | | Staging (Mainnet) | `SLendK7ySfcEzyaFqy93gDnD3RtrpXJcnRwb6zFHJSh` | | Devnet | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | ## Kvault | Environment | Address | | - | - | | Mainnet | `KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd` | | Staging (Mainnet) | `stKvQfwRsQiKnLtMNVLHKS3exFJmZFsgfzBPWHECUYK` | | Devnet | `devkRngFnfp4gBc5a3LsadgbQKdPo8MSZ4prFiNSVmY` | ## Kfarms | Environment | Address | | - | - | | Mainnet | `FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr` | | Devnet | `FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr` | ## Limo | Environment | Address | | - | - | | Mainnet | `LiMoM9rMhrdYrfzUCxQppvxCSG1FcrUK9G8uLq4A1GF` | | Staging (Mainnet) | `sLim6uuAFC8kAWstWpu1r6oJD4T8VR6raukSpU2Zim7` | ## Scope | Environment | Address | | - | - | | Mainnet | `HFn8GnPADiny6XqUoWE8uRPPxb29ikn4yTuPa9MF2fWJ` | | Staging (Mainnet) | `scpStzYvKzE7DHwsGMP5XLhcMTuLr3feoiC9mJ3yHr5` | ## Kliquidity | Environment | Address | | - | - | | Mainnet | `6LtLpnUFNByNXLyCoK9wA2MykKAmQNZKBdY8s47dehDc` | # Get all KVault season rewards Source: https://kamino.com/docs/build/season-rewards/get-all-kvault-season-rewards /kamino-api.json get /kvaults/rewards Get all active season points rewards for each Kamino Earn Vault # Get final vesting pool allocation Source: https://kamino.com/docs/build/season-rewards/get-final-vesting-pool-allocation /kamino-api.json get /season-rewards/final-vesting-pool Total rewards forfeited to the final vesting pool by users who claimed before full vesting # Get summary of the KVault program earnings Source: https://kamino.com/docs/build/season-rewards/get-summary-of-the-kvault-program-earnings /kamino-api.json get /kvaults/summary Get an aggregated all-time summary of all Kamino Earn Vault rewards and interest earned, in SOL and USD # Get user season claim status Source: https://kamino.com/docs/build/season-rewards/get-user-season-claim-status /kamino-api.json get /season-rewards/users/{pubkey}/claim-status Fetches season reward claim and forfeiture data for a specific user # Get user season rewards Source: https://kamino.com/docs/build/season-rewards/get-user-season-rewards /kamino-api.json get /season-rewards/users/{pubkey} Fetches combined season reward data from both KLend and KVault for a specific user # Get user staking boosts Source: https://kamino.com/docs/build/season-rewards/get-user-staking-boosts /kamino-api.json get /users/{pubkey}/staking-boosts Fetches staking boost multipliers for a specific user # Get mean staking yields Source: https://kamino.com/docs/build/staking-yields/get-mean-staking-yields /kamino-api.json get /v2/staking-yields/mean Fetches staking yields and calculates mean (average) APY over the last 10 epochs # Get median staking yields Source: https://kamino.com/docs/build/staking-yields/get-median-staking-yields /kamino-api.json get /v2/staking-yields/median Fetches staking yields and calculates median APY over the last 10 epochs # Get staking yields Source: https://kamino.com/docs/build/staking-yields/get-staking-yields /kamino-api.json get /v2/staking-yields Fetches the latest staking yields for all LSTs # Calculate Claimable User Rewards Source: https://kamino.com/docs/build/tutorials/borrow/calculate-claimable-user-rewards Calculate pending rewards for a user across all farm positions and check claimability Follow this tutorial to retrieve all pending rewards for a user across Liquidity, Lend, Borrow Markets, and Multiply farm positions, and check if they're claimable based on cooldown periods. <Note> **Farm Position Types** User rewards can come from different types of farm positions: * **Liquidity Farms**: Rewards from providing liquidity to Kamino vaults * **Lend Farms**: Rewards from depositing collateral or holding vault shares * **Borrow Markets Farms**: Rewards from borrowing assets (debt farms) or holding collateral/debt combinations (extra farms) * **Multiply Farms**: Rewards from leveraged positions This tutorial shows how to identify all farm positions for a user and calculate their claimable rewards across all position types. </Note> ## Calculate Claimable User Rewards Calculate pending rewards for a user across all farm positions and check if they are claimable based on cooldown periods. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={null} import { createSolanaRpc, address, type Address } from '@solana/kit'; import { Farms, FarmState, type UserFarm, type PendingReward } from '@kamino-finance/farms-sdk'; import { VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import Decimal from 'decimal.js'; type FarmPositionType = 'Liquidity' | 'Lend' | 'Borrow Markets' | 'Multiply'; type RewardWithAmount = { reward: PendingReward; rewardInfo: FarmState['rewardInfos'][0]; lastClaimTs: string; amount: Decimal; }; const DEFAULT_PUBKEY = '11111111111111111111111111111111'; ``` </Step> <Step> ### Initialize RPC and User Address Set up the Solana RPC connection and define the user wallet and lending market addresses. ```typescript theme={null} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const user = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); const lendingMarket = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); ``` </Step> <Step> ### Define Helper Functions Create helper functions to validate addresses and determine farm position types. First, define the address validation helper: ```typescript theme={null} // Helper function: Check if address is not default pubkey const isNotDefaultPubkey = (addr: Address): boolean => { return addr.toString() !== DEFAULT_PUBKEY; }; ``` Next, create the farm type determination function that checks for Liquidity and Lend farms: ```typescript theme={null} // Helper function: Determine farm position type based on farm and user state const determineFarmType = ( farmState: FarmState, userFarm: UserFarm, walletPubKey: Address, lendingMarketAddress: Address, obligationPDA: Address ): FarmPositionType => { // Check for Liquidity farm (has strategyId) if (isNotDefaultPubkey(farmState.strategyId)) { return 'Liquidity'; } // Check for Lend vault farm (has vaultId) const isVaultFarm = isNotDefaultPubkey(farmState.vaultId); if (isVaultFarm) { return 'Lend'; } ``` Finally, add the delegation logic to identify Borrow Markets and Multiply positions: ```typescript theme={null} // Calculate delegation variables const delegateeIsOwner = userFarm.userState.delegatee.toString() === userFarm.userState.owner.toString(); const farmHasSecondDelegatedAuthority = isNotDefaultPubkey(farmState.secondDelegatedAuthority); const farmUserStateIsForObligation = userFarm.userState.delegatee.toString() === obligationPDA.toString(); // Check for Lend collateral farm (delegated but not for obligation) if (!delegateeIsOwner && farmHasSecondDelegatedAuthority && !farmUserStateIsForObligation) { return 'Lend'; } // Check for Borrow Markets (delegated to obligation) if ( lendingMarketAddress && (farmUserStateIsForObligation || walletPubKey.toString() === userFarm.userState.delegatee.toString()) ) { return 'Borrow Markets'; } // Default to Multiply return 'Multiply'; }; ``` <Info> The `determineFarmType` function uses various state checks to identify the farm position type. Liquidity farms have a `strategyId`, Lend farms have a `vaultId` or specific delegation patterns, and Borrow Markets farms are identified by obligation delegation. </Info> </Step> <Step> ### Fetch User Farms Get all farms the user is participating in and fetch their states in parallel. ```typescript theme={null} const farms = new Farms(rpc); const currentTime = new Decimal(Math.floor(Date.now() / 1000)); // Get all farms user is participating in const userFarms = await farms.getAllFarmsForUser(user, currentTime); // Fetch farm states in batch const farmAddresses = Array.from(userFarms.keys()); const farmStates = await FarmState.fetchMultiple(rpc, farmAddresses); // Build farm data objects const farmsData = farmAddresses.flatMap((farmAddress, index) => { const farmState = farmStates[index]; const userFarm = userFarms.get(farmAddress); return farmState && userFarm ? [{ farmAddress, userFarm, farmState }] : []; }); ``` <Info> The `getAllFarmsForUser` method returns a map of all farms where the user has an active position. Using `FarmState.fetchMultiple` fetches all farm states in a single batch request. </Info> </Step> <Step> ### Calculate Obligation PDA and Display Rewards Calculate the obligation PDA, then loop through all user farms to calculate pending rewards and check if they're claimable based on cooldown periods. First, calculate the obligation PDA: ```typescript theme={null} // Calculate obligation PDA const obligationType = new VanillaObligation(PROGRAM_ID); const obligationPDA = await obligationType.toPda(lendingMarket, user); ``` Then iterate through farms and filter rewards with positive amounts: ```typescript theme={null} for (const { farmAddress, userFarm, farmState } of farmsData) { // Determine farm type const farmType = determineFarmType(farmState, userFarm, user, lendingMarket, obligationPDA); // Filter and calculate token amounts const rewardsWithAmount = userFarm.pendingRewards .map((reward: PendingReward, index: number) => { const rewardInfo = farmState.rewardInfos[index]; const lastClaimTs = userFarm.userState.lastClaimTs[index]; if (reward.rewardTokenMint === DEFAULT_PUBKEY || !rewardInfo || !lastClaimTs) { return null; } const amount = new Decimal(reward.cumulatedPendingRewards.toString()).div( new Decimal(10).pow(rewardInfo.token.decimals.toNumber()) ); if (amount.gt(0)) { return { reward, rewardInfo, lastClaimTs: lastClaimTs.toString(), amount }; } return null; }) .filter((r): r is RewardWithAmount => r !== null); ``` Finally, check claimability based on cooldown periods and display the results: ```typescript theme={null} // Only display farm if it has valid rewards if (rewardsWithAmount.length > 0) { console.log(`${farmType} Farm: ${farmAddress.toString()}`); console.log(` Owner: ${userFarm.userState.owner.toString()}`); console.log(` Delegatee: ${userFarm.userState.delegatee.toString()}`); for (const { reward, rewardInfo, lastClaimTs, amount } of rewardsWithAmount) { // Check if reward is claimable based on cooldown period const minClaimDuration = new Decimal(rewardInfo.minClaimDurationSeconds.toString()).toNumber(); const lastClaimTsNum = new Decimal(lastClaimTs).toNumber(); const currentTimeNum = currentTime.toNumber(); const timeSinceClaim = currentTimeNum - lastClaimTsNum; // Validate data (1 year = 31536000 seconds - anything larger is invalid) const isValidDuration = minClaimDuration < 31536000; const isValidTimestamp = timeSinceClaim >= 0 && timeSinceClaim < 31536000000; console.log(` Reward: ${reward.rewardTokenMint}`); console.log(` Amount: ${amount.toFixed(rewardInfo.token.decimals.toNumber())}`); if (!isValidDuration || !isValidTimestamp) { console.log(` Claimable: No\n`); } else { const claimable = timeSinceClaim >= minClaimDuration; if (claimable) { console.log(` Claimable: Yes\n`); } else { const timeRemaining = minClaimDuration - timeSinceClaim; console.log(` Claimable: ${Math.ceil(timeRemaining / 60)}m\n`); } } } } } ``` <Check> The script outputs all pending rewards grouped by farm type and position. Each reward shows the token mint, amount, and claimability status. If a reward has a cooldown period, the remaining time is displayed in minutes. </Check> </Step> </Steps> # Interest Rate Curve Source: https://kamino.com/docs/build/tutorials/borrow/calculate-interest-rate-curve Calculate how borrow and supply APY change based on pool utilization <Note> The interest rate curve shows how borrow and supply APY change as pool utilization increases from 0% to 100%, where utilization represents the share of supplied liquidity that is borrowed. </Note> ## Calculate Interest Rate Curve Generate curve points showing APY at different utilization levels. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication and Kamino SDK operations. ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, DEFAULT_RECENT_SLOT_DURATION_MS, SLOTS_PER_SECOND, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import { getBorrowRate, calculateAPYFromAPR } from '@kamino-finance/klend-sdk/dist/classes/utils'; ``` </Step> <Step> ### Configure Market and Reserve Set up the lending market, reserve address, and calculation parameters. ```typescript theme={null} const LENDING_MARKET_ID = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const RESERVE_ADDRESS = address('ESCkPWKHmgNE7Msf77n9yzqJd5kQVWWGy3o5Mgxhvavp'); const STEP = 0.05; ``` <Note> The STEP value determines curve granularity: 0.05 = 21 points, 0.01 = 101 points. Smaller steps provide smoother curves but increase computation. </Note> </Step> <Step> ### Load Market and Reserve Initialize RPC connection and load the market and reserve data. ```typescript theme={null} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const market = await KaminoMarket.load(rpc, LENDING_MARKET_ID, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); const reserve = market!.getReserveByAddress(RESERVE_ADDRESS); if (!reserve) throw new Error(`Reserve ${RESERVE_ADDRESS} not found`); const currentSlot = await rpc.getSlot().send(); ``` <Info> The `getReserveByAddress` method retrieves reserve configuration including the borrow rate curve points and protocol parameters needed for APY calculations. </Info> </Step> <Step> ### Extract Borrow Curve Points Convert the reserve's borrow rate curve from basis points to decimal values. ```typescript theme={null} const ONE_HUNDRED_PCT_IN_BPS = 10_000; const borrowCurve: [number, number][] = []; for (const { utilizationRateBps, borrowRateBps } of reserve.state.config.borrowRateCurve.points) { borrowCurve.push([utilizationRateBps / ONE_HUNDRED_PCT_IN_BPS, borrowRateBps / ONE_HUNDRED_PCT_IN_BPS]); if (utilizationRateBps === ONE_HUNDRED_PCT_IN_BPS) break; } ``` <Info> The borrow curve defines interest rates at specific utilization thresholds and interpolates between them. Rates rise sharply after 80% utilization to discourage the pool from becoming fully utilized. </Info> </Step> <Step> ### Calculate Adjustment Parameters Get parameters needed to convert per-slot rates to annual APY. ```typescript theme={null} const slotDuration = DEFAULT_RECENT_SLOT_DURATION_MS; const slotAdjustmentFactor = 1000 / SLOTS_PER_SECOND / slotDuration; const protocolTakeRatePct = 1 - (reserve.state.config.protocolTakeRatePct / 100); const fixedHostInterestRate = reserve.getFixedHostInterestRate(); ``` <Info> **Key Parameters Explained** * **Slot Adjustment Factor**: Converts per-slot rates to annual rates. Solana has \~2 slots per second with average 400ms duration. * **Protocol Take Rate**: The percentage of borrow interest paid to suppliers. If protocol takes 10%, suppliers receive 90% of interest paid by borrowers. * **Fixed Host Interest Rate**: A small base rate added to all borrows, ensuring borrowers pay at least a minimum rate even at 0% utilization. </Info> </Step> <Step> ### Generate Curve Points Calculate borrow and supply APY at each utilization level. ```typescript theme={null} const curvePoints = []; const numSteps = Math.round(1.0 / STEP); for (let i = 0; i <= numSteps; i++) { const utilization = i / numSteps; const borrowAPR = getBorrowRate(utilization, borrowCurve) * slotAdjustmentFactor; const borrowRate = calculateAPYFromAPR( fixedHostInterestRate.mul(slotAdjustmentFactor).add(borrowAPR).toNumber() ); const supplyRate = calculateAPYFromAPR(utilization * borrowAPR * protocolTakeRatePct); curvePoints.push({ utilization: utilization, borrowApy: borrowRate * 100, supplyApy: supplyRate * 100 }); } ``` <Info> **How the Calculation Works** 1. `getBorrowRate` interpolates the borrow rate from the curve at the given utilization 2. `calculateAPYFromAPR` converts APR to APY: `APY = (1 + rate/periods)^periods - 1`, accounting for compound interest per slot 3. Supply APY formula: `supplyAPY = utilization × borrowAPR × (1 - protocolFee)` - suppliers earn interest only on borrowed funds, minus the protocol fee </Info> </Step> <Step> ### Build Result with Current Metrics Combine the curve data with current reserve metrics. ```typescript theme={null} const result = { symbol: reserve.symbol, reserveAddress: RESERVE_ADDRESS.toString(), currentUtilization: reserve.calculateUtilizationRatio(), currentBorrowApy: reserve.totalBorrowAPY(currentSlot) * 100, currentSupplyApy: reserve.totalSupplyAPY(currentSlot) * 100, curvePoints }; console.log(JSON.stringify(result, null, 2)); ``` <Check> The result includes the reserve symbol, current utilization and APY values, plus an array of curve points. Each curve point contains the utilization level, borrow APY, and supply APY at that utilization. This data can be used to visualize the interest rate curve with charting libraries. </Check> </Step> </Steps> ## Understanding the Results The curve shows how rates change with utilization: * **Low utilization (0-50%)**: Borrow rates are low to encourage borrowing, supply rates are minimal * **Medium utilization (50-80%)**: Rates increase moderately to balance supply and demand - this is the target range * **High utilization (80-100%)**: Rates increase sharply to incentivize repayment and new deposits ### Example Output ```json theme={null} { "symbol": "USDG", "reserveAddress": "ESCkPWKHmgNE7Msf77n9yzqJd5kQVWWGy3o5Mgxhvavp", "currentUtilization": 0.7888, "currentBorrowApy": 8.2, "currentSupplyApy": 5.8, "curvePoints": [ { "utilization": 0.0, "borrowApy": 2.1, "supplyApy": 0.0 }, { "utilization": 0.25, "borrowApy": 3.5, "supplyApy": 0.8 }, { "utilization": 0.5, "borrowApy": 5.2, "supplyApy": 2.3 }, { "utilization": 0.75, "borrowApy": 8.9, "supplyApy": 5.9 }, { "utilization": 1.0, "borrowApy": 45.2, "supplyApy": 40.1 } ] } ``` # Calculate Reserve Reward APY Source: https://kamino.com/docs/build/tutorials/borrow/calculate-reserve-reward-apy Calculate collateral and debt farm reward APY for market reserves Follow this tutorial to calculate reward APY for both deposit and borrow positions on Kamino lending reserves. <Note> **Reserve Farms vs Extra Farms** Reserve farms are attached directly to a reserve and reward all users who deposit or borrow that reserve asset. Depositors earn rewards through collateral farms, while borrowers earn rewards through debt farms. Extra farms reward users only when specific collateral and debt combinations are used. Rewards are conditional on holding qualifying positions rather than simply depositing or borrowing a single reserve. This tutorial focuses on reserve farms. </Note> ## Calculate Reserve Reward APY Calculate APY for both collateral and debt farm rewards on a specific reserve. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={null} import { createSolanaRpc, address, type Address } from '@solana/kit'; import { KaminoMarket, PROGRAM_ID, lamportsToNumberDecimal }
프로젝트로 돌아가기