Kamino 백서

Kamino

원문

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

g 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> # Calculate Reserve Reward APY Source: https://kamino.com/docs/build/developers/borrow/rewards/calculate-reserve-reward-apy Calculate collateral and debt farm reward APY for market 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 } from '@kamino-finance/klend-sdk'; import { FarmState, calculateCurrentRewardPerToken } from '@kamino-finance/farms-sdk'; import Decimal from 'decimal.js'; type PriceData = { mint: string; price: string }; const DEFAULT_PUBKEY = '11111111111111111111111111111111'; ``` </Step> <Step> ### Initialize RPC and Fetch Prices Set up the Solana RPC connection and fetch token prices from the Kamino API. ```typescript theme={null} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const mainMarket = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const usdsMint = address('USDSwr9ApdHk5bvJKMjzff41FfuX8bSxdKcR81vTwcA'); // Fetch token prices from Kamino API const pricesRes = await fetch('https://api.kamino.finance/oracles/prices?markets=main'); const pricesData = (await pricesRes.json()) as PriceData[]; const priceMap = new Map<string, number>(); for (const p of pricesData) { priceMap.set(p.mint, parseFloat(p.price)); } ``` <Info> Creating a price map allows quick lookups for multiple reward tokens. The example uses USDS reserve which has both collateral and debt farm rewards active. </Info> </Step> <Step> ### Load Market and Reserve Load the Kamino market and get the reserve by its mint address. ```typescript theme={null} // Load market and reserve const market = await KaminoMarket.load(rpc, mainMarket, 400, PROGRAM_ID); const reserve = market!.getReserveByMint(usdsMint); if (!reserve) { console.log('Reserve not found'); } else { ``` <Info> The `getReserveByMint` method retrieves the reserve configuration including references to both the collateral farm and debt farm addresses. </Info> </Step> <Step> ### Collect and Fetch Farm Addresses Collect both collateral and debt farm addresses, checking they're not the default pubkey, then fetch all farms in parallel. ```typescript theme={null} // Collect debt and collateral farm addresses const farmsToFetch: { name: string; address: Address }[] = []; if (reserve.state.farmCollateral.toString() !== DEFAULT_PUBKEY) { farmsToFetch.push({ name: 'Collateral Farm Rewards', address: reserve.state.farmCollateral }); } if (reserve.state.farmDebt.toString() !== DEFAULT_PUBKEY) { farmsToFetch.push({ name: 'Debt Farm Rewards', address: reserve.state.farmDebt }); } // Fetch all farms in batch const farmAddresses = farmsToFetch.map((f) => f.address); const farmStates = await FarmState.fetchMultiple(rpc, farmAddresses); const farms = farmsToFetch.flatMap((farmInfo, index) => { const state = farmStates[index]; return state ? [{ name: farmInfo.name, state }] : []; }); ``` <Info> Checking for the default pubkey ensures we only fetch farms that are actually configured on the reserve. Using `FarmState.fetchMultiple` fetches all farm states in a single batch request, which is more efficient than individual fetches. </Info> </Step> <Step> ### Calculate Farm Reward APY Calculate APY for each active reward on both collateral and debt farms. ```typescript theme={null} for (const farm of farms) { const totalStaked = lamportsToNumberDecimal( farm.state.totalStakedAmount.toString(), farm.state.token.decimals.toNumber() || 6 ); console.log(farm.name + ':'); for (const rewardInfo of farm.state.rewardInfos) { if (rewardInfo.rewardsAvailable.gtn(0) && !totalStaked.isZero()) { const rewardMint = rewardInfo.token.mint.toString(); const rewardPrice = priceMap.get(rewardMint) || 1; const currentTime = new Decimal(Date.now() / 1000); // Calculate APY from farm rewards const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(rewardInfo, currentTime); // returns the raw value const divisor = new Decimal(10) .pow(rewardInfo.rewardsPerSecondDecimals.toString()) .mul(new Decimal(10).pow(rewardInfo.token.decimals.toString())); const adjustedRewardPerToken = new Decimal(rewardPerTokenPerSecond).div(divisor); const dailyRewards = adjustedRewardPerToken.mul(86400).mul(rewardPrice); const apy = Decimal.pow(dailyRewards.div(totalStaked).plus(1), 365).minus(1); console.log(` Reward Token: ${rewardMint}`); console.log(` APY: ${(apy.toNumber() * 100).toFixed(2)}%\n`); } } } } ``` <Check> The script outputs APY for all active rewards on both the collateral and debt farms. The `calculateCurrentRewardPerToken` helper from farms-sdk handles the reward schedule logic. Each reward is priced in USD and the total staked amount represents the value of all positions earning that reward. </Check> </Step> </Steps> # Claim User Rewards Source: https://kamino.com/docs/build/developers/borrow/rewards/claim-user-rewards Claim all pending rewards from lending farm positions <Note> **Delegated vs Non-Delegated Farms** Different farm types use different delegation patterns. For the correct delegatees for your specific farm, check the user farm state returned by `getAllFarmsForUser` in the "Calculate Claimable User Rewards" tutorial. </Note> ## Claim User Rewards Claim all pending rewards from a user's farm position. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, parseKeypairFile, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import { Farms } from '@kamino-finance/farms-sdk'; ``` </Step> <Step> ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={null} // Configuration - UPDATE THESE VALUES const KEYPAIR_FILE = '/path/to/your/keypair.json'; // Load keypair from file const signer = await parseKeypairFile(KEYPAIR_FILE); // Initialize RPC and RPC Subscriptions const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); ``` </Step> <Step> ### Load Market and Get Obligation Load the Kamino market and get the user's obligation address. ```typescript theme={null} const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const market = await KaminoMarket.load(rpc, marketPubkey, 400); // Get obligation address for delegatees array const kaminoObligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!kaminoObligation) { throw new Error('No obligation found'); } console.log('Obligation:', kaminoObligation.obligationAddress.toString()); ``` </Step> <Step> ### Build Claim Instructions Use the Farms SDK to build claim instructions for all rewards on the farm. ```typescript theme={null} // Build claim instructions using farms-sdk const farm = new Farms(rpc); const claimIxs = await farm.claimForUserForFarmAllRewardsIx( signer, // payer signer.address, // user (wallet address = owner) address('Gsoc83qRQ5X1LfGGbPqU2FdxZnveqbkP2vMXq6BcmtMk'), // farm true, // isDelegated = true for lending farms [signer.address, kaminoObligation.obligationAddress] // delegatees array ); ``` <Warning> The `delegatees` array values depend on your specific farm position. To find the correct delegatee addresses for your farm, use the "Calculate Claimable User Rewards" tutorial - it shows the actual delegatee in the user farm state. </Warning> </Step> <Step> ### Build and Sign Transaction Use Kit's functional pipe pattern to build and sign the transaction with a fresh blockhash. ```typescript theme={null} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const claimTx = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(claimIxs, tx) ); const claimSigned = await signTransactionMessageWithSigners(claimTx); const claimSignature = getSignatureFromTransaction(claimSigned); ``` </Step> <Step> ### Send and Confirm Transaction Send the transaction to the network and wait for confirmation. ```typescript theme={null} await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(claimSigned, { commitment: 'confirmed', skipPreflight: true, }); console.log(`Claim farm rewards successful! Signature: ${claimSignature}`); ``` <Check> The rewards have been claimed and transferred to your wallet. You can verify the transaction using the signature on a Solana explorer. </Check> </Step> </Steps> # Calculate Extra Farm Reward APY Source: https://kamino.com/docs/build/developers/borrow/rewards/extra-farm-reward-apy Calculate APY for extra farm stablecoin rewards <Note> Extra farms provide additional rewards to users who deposit specific collateral and borrow specific assets. </Note> ## Calculate Extra Farm Reward APY Calculate APY for extra farm rewards paid in stablecoins like CASH that are pegged to USD. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { FarmState, calculateCurrentRewardPerToken } from '@kamino-finance/farms-sdk'; import { KaminoMarket, PROGRAM_ID, lamportsToNumberDecimal } from '@kamino-finance/klend-sdk'; import Decimal from 'decimal.js'; type ExtraFarm = { market: string; farm: string; collMint: string; debtMint: string }; type Resources = { 'mainnet-beta': { extraFarms: ExtraFarm[] } }; ``` </Step> <Step> ### Initialize RPC and Load Market Set up the Solana RPC connection and load the Kamino market. ```typescript theme={null} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const mainMarketAddress = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); // Load market and get CASH and SOL mints from reserves const market = await KaminoMarket.load(rpc, mainMarketAddress, 400, PROGRAM_ID); let cashReserve, solReserve; for (const reserve of market!.reserves.values()) { if (reserve.stats.symbol === 'CASH') cashReserve = reserve; if (reserve.stats.symbol === 'SOL') solReserve = reserve; } if (!cashReserve || !solReserve) { throw new Error('CASH or SOL reserve not found'); } const cashMint = cashReserve.getLiquidityMint().toString(); const solMint = solReserve.getLiquidityMint().toString(); ``` <Info> This example targets the SOL/CASH extra farm pair where users deposit SOL collateral and borrow CASH to earn rewards. </Info> </Step> <Step> ### Get and Filter Extra Farms Fetch the list of extra farms from the CDN and filter by SOL collateral and CASH debt. ```typescript theme={null} // Get extraFarms from CDN API and filter by SOL/CASH pair const cdnRes = await fetch('https://cdn.kamino.finance/resources.json'); const allResources = (await cdnRes.json()) as Resources; const kaminoResources = allResources['mainnet-beta']; const extraFarmsForMarket = kaminoResources.extraFarms.filter((f) => f.market === mainMarketAddress.toString()); // Filter by collateral (SOL) and debt (CASH) mints const solCashFarms = extraFarmsForMarket.filter((f) => f.collMint === solMint && f.debtMint === cashMint); ``` <Info> The CDN resources endpoint provides a list of all extra farms. We filter for farms that specifically reward SOL collateral deposits paired with CASH borrows. </Info> </Step> <Step> ### Fetch All Farm States in Batch Fetch all farm states in a single batch request for better performance. ```typescript theme={null} // Fetch all farm states in batch const farmAddresses = solCashFarms.map((f) => address(f.farm)); const farmStates = await FarmState.fetchMultiple(rpc, farmAddresses); const farms = solCashFarms.flatMap((extraFarm, index) => { const farmState = farmStates[index]; return farmState ? [{ farm: extraFarm.farm, farmState }] : []; }); ``` <Info> Using `FarmState.fetchMultiple` fetches all farm states in a single batch request. </Info> </Step> <Step> ### Calculate APY for SOL/CASH Farms Loop through the fetched farms and calculate APY for CASH rewards. ```typescript theme={null} for (const { farm, farmState } of farms) { const totalStaked = lamportsToNumberDecimal( farmState.totalStakedAmount.toString(), farmState.token.decimals.toNumber() || 6 ); const cashReward = farmState.rewardInfos.find( (r) => r.token.mint.toString() === cashMint && r.rewardsAvailable.gtn(0) ); if (cashReward && !totalStaked.isZero()) { const currentTime = new Decimal(Date.now() / 1000); // Calculate APY from farm rewards const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(cashReward, currentTime); // returns the raw value const divisor = new Decimal(10) .pow(cashReward.rewardsPerSecondDecimals.toString()) .mul(new Decimal(10).pow(cashReward.token.decimals.toString())); const adjustedRewardPerToken = new Decimal(rewardPerTokenPerSecond).div(divisor); const dailyRewards = adjustedRewardPerToken.mul(86400); const apy = Decimal.pow(dailyRewards.div(totalStaked).plus(1), 365).minus(1); console.log(`ExtraFarm: ${farm}`); console.log(` CASH APY: ${(apy.toNumber() * 100).toFixed(2)}%\n`); } } ``` <Check> The script outputs the APY for SOL/CASH extra farms paying CASH rewards. The `calculateCurrentRewardPerToken` helper from farms-sdk handles the reward schedule logic. Since CASH is pegged to USD, no price lookup is required. </Check> </Step> </Steps> # Create a Vault Source: https://kamino.com/docs/build/developers/earn/data/advanced-concepts/creating-a-vault Create and configure Kamino vaults with custom fee structures to earn revenue <Info> Learn how to create a Kamino vault with [custom fee structures](#configure-vault), deposit limits, and allocation strategies. The SDK manages vault initialization, metadata setup, and lookup table creation to optimize future transactions. </Info> ## Creating a Vault Initialize a new vault with custom configuration and prepare it for user deposits. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoManager, KaminoVaultConfig, getMedianSlotDur
프로젝트로 돌아가기