Kamino 백서

Kamino

원문

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

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/tutorials/borrow/claim-user-rewards Claim all pending rewards from lending farm positions Follow this tutorial to claim all accumulated rewards from your collateral or debt farm positions on Kamino lending reserves. <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> # Deposit and Borrow Source: https://kamino.com/docs/build/tutorials/borrow/deposit-and-borrow Deposit collateral and borrow assets against it ## Deposit Collateral Deposit assets as collateral to enable borrowing. <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, KaminoAction, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` </Step> <Step> ### Load Signer and Initialize Market Load your keypair from a file and initialize RPC connections and the Kamino market. ```typescript theme={null} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const market = await KaminoMarket.load(rpc, marketPubkey, 400); ``` <Note> Replace `/path/to/your/keypair.json` with the actual path to your keypair file. The `KaminoMarket.load()` method fetches the current market state including all reserve data. </Note> </Step> <Step> ### Build Deposit Instructions Build deposit instructions for depositing collateral to enable borrowing. ```typescript theme={null} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const depositAmount = new BN(3_000_000); // 3 USDC (6 decimals) const signatures: string[] = []; let depositAction = await KaminoAction.buildDepositTxns( market!, depositAmount, usdcMint, signer, new VanillaObligation(PROGRAM_ID), true, undefined, 1_000_000, true, false, { skipInitialization: false, skipLutCreation: false } ); const hasSetup = (depositAction.setupIxs || []).length > 0; let instructions = [ ...(depositAction.setupIxs || []), ...(depositAction.lendingIxs || []), ...(depositAction.cleanupIxs || []), ]; ``` <Info> The `buildDepositTxns` method creates instructions to deposit collateral. This enables you to borrow other assets against your deposit. </Info> </Step> <Step> ### Send Deposit Transaction with Error Handling Send the deposit transaction with automatic retry logic for setup-related errors. ```typescript theme={null} try { const { value: depositBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const depositTx = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(depositBlockhash, tx), (tx) => appendTransactionMessageInstructions(instructions, tx) ); const depositSigned = await signTransactionMessageWithSigners(depositTx); const depositSignature = getSignatureFromTransaction(depositSigned); signatures.push(depositSignature); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(depositSigned, { commitment: 'confirmed', skipPreflight: true, }); console.log(`Deposit successful! Signature: ${depositSignature}`); } catch (error: any) { const errorMsg = error?.message || error?.toString() || ''; const is0x17a3 = errorMsg.includes('0x17a3') || errorMsg.includes('6051') || errorMsg.includes('IncorrectInstructionInPosition'); if (hasSetup && is0x17a3) { await new Promise((resolve) => setTimeout(resolve, 2000)); const reloadedMarket = await KaminoMarket.load(rpc, marketPubkey, 400); depositAction = await KaminoAction.buildDepositTxns( reloadedMarket!, depositAmount, usdcMint, signer, new VanillaObligation(PROGRAM_ID), true, undefined, 1_000_000, true, false, { skipInitialization: false, skipLutCreation: false } ); instructions = [ ...(depositAction.setupIxs || []), ...(depositAction.lendingIxs || []), ...(depositAction.cleanupIxs || []), ]; const { value: retryBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const retryTx = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(retryBlockhash, tx), (tx) => appendTransactionMessageInstructions(instructions, tx) ); const retrySigned = await signTransactionMessageWithSigners(retryTx); const retrySignature = getSignatureFromTransaction(retrySigned); signatures.push(retrySignature); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(retrySigned, { commitment: 'confirmed', skipPreflight: true, }); console.log( `Deposit successful! Signature: ${retrySignature}\nSetup transaction: https://solscan.io/tx/${signatures[0]}` ); } else { console.error('Deposit failed:', error); } } ``` <Warning> When setup instructions are included, the first transaction may fail with error 0x17a3. The retry logic handles this by waiting for blockchain state to settle, reloading the market, and rebuilding instructions. </Warning> <Check> Once the deposit transaction is confirmed, your collateral is deposited and you can now borrow assets against it. An obligation is created to track your position. </Check> </Step> </Steps> ## Borrow Assets Borrow assets against your deposited collateral. <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, KaminoAction, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` </Step> <Step> ### Load Signer and Initialize Market Load your keypair from a file and initialize RPC connections and the Kamino market. ```typescript theme={null} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const market = await KaminoMarket.load(rpc, marketPubkey, 400); ``` <Note> Replace `/path/to/your/keypair.json` with the actual path to your keypair file. The `KaminoMarket.load()` method fetches the current market state including all reserve data. </Note> </Step> <Step> ### Check for Existing Obligation Verify that an obligation exists before attempting to borrow. ```typescript theme={null} const existingObligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!existingObligation) { throw new Error('No existing obligation found. Please deposit collateral first.'); } ``` <Warning> You must have an existing obligation with deposited collateral before you can borrow. If you haven't deposited collateral yet, do that first. </Warning> </Step> <Step> ### Build Borrow Instructions Generate borrow instructions for the specified token and amount. ```typescript theme={null} const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); const borrowAmount = new BN(1_000_000); // 1.00 USDT (6 decimals) const borrowAction = await KaminoAction.buildBorrowTxns( market!, borrowAmount, usdtMint, signer, new VanillaObligation(PROGRAM_ID), true, undefined, 1_000_000, true, false ); const allInstructions = [ ...(borrowAction.setupIxs || []), ...(borrowAction.lendingIxs || []), ...(borrowAction.cleanupIxs || []), ]; ``` <Info> The `buildBorrowTxns` method creates borrow instructions that withdraw assets from the reserve pool to your wallet. The amount borrowed is added to your debt obligation. </Info> </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 transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(allInstructions, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); ``` </Step> <Step> ### Send and Confirm Transaction Send the borrow transaction and wait for confirmation. ```typescript theme={null} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Borrow successful! Signature:', signature); ``` <Check> Once the borrow transaction is confirmed, the borrowed assets are transferred to your wallet. You now have a debt obligation that accrues interest. Monitor your loan-to-value ratio to avoid liquidation. </Check> </Step> </Steps> # Deposit with Referral Source: https://kamino.com/docs/build/tutorials/borrow/deposit-with-referral Deposit funds with a referrer who earns commission from a user's borrowing activity Follow this tutorial to make a deposit with a referrer who will earn commission from your future borrowing activity. ## Deposit with Referral A UserMetadata account stores the referrer information. The referrer must be included when the account is created. After it is set, the referrer cannot be changed. <Tabs> <Tab title="TypeScript"> <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, sendAndConfirmTra
프로젝트로 돌아가기