Kamino 백서

Kamino

원문

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

oken's pending amount on a position. ```typescript theme={null} type PendingReward = { rewardTokenMint: Address; rewardTokenProgramId: Address; rewardType: number; cumulatedPendingRewards: Decimal; pendingRewardsByDelegatee: Map<Address, Decimal>; }; ``` </Tab> </Tabs> ## Additional Resources <CardGroup> <Card title="API Examples" icon="book" href="https://api-docs.kamino.com/" /> <Card title="SDK Repository" icon="github" href="https://github.com/Kamino-Finance/farms-sdk" /> </CardGroup> # Harvest Source: https://kamino.com/docs/build/developers/rewards/operations/harvest Claim all pending rewards from a Kamino farm ## Harvest Claim every pending reward token accrued on a farm to your wallet in one call. <Note> `claimForUserForFarmAllRewardsIx` walks every reward slot, skips any still under its claim cooldown, and returns one harvest instruction per claimable reward, plus an idempotent ATA-create instruction if the reward token account is missing. It reads on-chain Scope prices itself, so there is nothing to refresh. If the returned array is empty, nothing is past its cooldown to claim. </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, and target farm. 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 signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); ``` </Step> <Step> ### Build Harvest Instructions Build one harvest instruction per claimable reward. The payer signs and pays fees; the rewards land in the user's wallet. ```typescript theme={null} const instructions = await farms.claimForUserForFarmAllRewardsIx( signer, // payer signer.address, // user (owner of the position) FARM, false, // isDelegated ); if (instructions.length === 0) console.log("Nothing to claim for", signer.address); ``` <Note> Pass `isDelegated: false` for a non-delegated farm. For a delegated klend or kvault farm, pass `true` and the obligation as a delegatee in the optional `delegatees` argument. See [Claim user rewards](/docs/build/developers/borrow/rewards/claim-user-rewards) for the delegated case. </Note> </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("Claim successful! Signature:", signature); ``` <Check> The harvest is complete. Every reward token past its claim cooldown has been transferred 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 signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); const instructions = await farms.claimForUserForFarmAllRewardsIx( signer, signer.address, FARM, false, ); if (instructions.length === 0) console.log("Nothing to claim for", signer.address); 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("Claim successful! Signature:", signature); ``` # Stake Source: https://kamino.com/docs/build/developers/rewards/operations/stake Stake share tokens into a Kamino farm ## Stake Stake a farm's share token to start earning rewards. Refresh the farm (and the user, if a position already exists) so reward accounting is current, then stake. <Note> This flow requires a non-delegated farm. `stakeIx` needs a `stakeTokenMint`, which delegated farms (klend reserve and kvault farms) do not have. The wallet needs SOL for fees plus the farm's stake token to stake. </Note> <Steps> <Step> ### Import Dependencies Import the packages for Solana RPC communication, Kit transaction building, the Farms SDK, and the keypair loader. ```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, FarmState } from "@kamino-finance/farms-sdk"; import { getScopePricesFromFarm } from "@kamino-finance/farms-sdk/dist/utils/option"; import Decimal from "decimal.js"; ``` </Step> <Step> ### Configure Constants and Initialize Set the keypair path, RPC endpoints, target farm, stake token mint, and amount. 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("9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6"); // non-delegated farm const STAKE_MINT = address("3EmfhZ3KUaYdwKZ9CwfGoKRqQqUV1MhSCVL5Ch7szX7e"); // the farm's stake token const STAKE_AMOUNT = new Decimal(0.02); // amount of shares to stake const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); ``` </Step> <Step> ### Load Farm State Fetch the farm account, read its Scope prices for the refresh instructions, and convert the stake amount to raw token units. ```typescript theme={null} const farmState = await FarmState.fetch(rpc, FARM); if (!farmState) console.log(`Farm not found: ${FARM}`); const scopePrices = getScopePricesFromFarm(farmState); const decimals = farmState.token.decimals.toNumber(); const amountLamports = STAKE_AMOUNT.mul(new Decimal(10).pow(decimals)); ``` <Note> `stakeIx` takes the raw lamport amount (the share amount times 10^decimals). The on-chain program scales it up internally. </Note> </Step> <Step> ### Build Stake Instructions Check whether the wallet already has a user-state account, then assemble the instruction list: create the user state if needed, refresh, and stake. ```typescript theme={null} const existing = await farms .getUserStateKeyForUndelegatedFarm(signer.address, FARM) .catch(() => null); const instructions = [ ...(existing ? [] : [await farms.createNewUserIx(signer, FARM)]), await farms.refreshFarmIx(FARM, scopePrices), ...(existing ? [await farms.refreshUserIx(existing.key, FARM, scopePrices)] : []), await farms.stakeIx(signer, FARM, amountLamports, STAKE_MINT, scopePrices), ]; ``` <Note> The Farms SDK exposes bare instruction builders that do not bundle a refresh, unlike klend. Prepend `refreshFarmIx` (and `refreshUserIx` for an existing position) so reward accounting is current before you stake. A first-time staker has no user-state account yet, so `createNewUserIx` creates it in the same transaction. </Note> </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("Stake successful! Signature:", signature); ``` <Check> The stake is complete. Your shares are staked, and rewards accrue once any deposit warmup period elapses. </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, FarmState } from "@kamino-finance/farms-sdk"; import { getScopePricesFromFarm } from "@kamino-finance/farms-sdk/dist/utils/option"; import Decimal from "decimal.js"; 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("9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6"); const STAKE_MINT = address("3EmfhZ3KUaYdwKZ9CwfGoKRqQqUV1MhSCVL5Ch7szX7e"); const STAKE_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 scopePrices = getScopePricesFromFarm(farmState); const decimals = farmState.token.decimals.toNumber(); const amountLamports = STAKE_AMOUNT.mul(new Decimal(10).pow(decimals)); const existing = await farms .getUserStateKeyForUndelegatedFarm(signer.address, FARM) .catch(() => null); const instructions = [ ...(existing ? [] : [await farms.createNewUserIx(signer, FARM)]), await farms.refreshFarmIx(FARM, scopePrices), ...(existing ? [await farms.refreshUserIx(existing.key, FARM, scopePrices)] : []), await farms.stakeIx(signer, FARM, amountLamports, STAKE_MINT, 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("Stake successful! Signature:", signature); ``` # Unstake Source: https://kamino.com/docs/build/developers/rewards/operations/unstake Unstake share tokens from a Kamino farm ## Unstake Unstaking moves stake from active into pending withdrawal and starts the farm's withdrawal cooldown. After the cooldown elapses, call [Withdraw](/docs/build/developers/rewards/operations/withdraw-unstaked) to move the tokens back to your wallet. Refresh first, then unstake. <Note> This flow requires an existing position on a non-delegated farm. The wallet needs SOL for fees. </Note> <Steps> <Step> ### Import Dependencies Import the packages for Solana RPC communication, Kit transaction building, and the Farms SDK. `UserState` and `WAD` are used to scale the unstake amount. ```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, FarmState, UserState } 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"; ``` </Step> <Step> ### Configure Constants and Initialize Set the keypair path, RPC endpoints, target farm, and amount. 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("9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6"); // non-delegated farm const UNSTAKE_AMOUNT = new Decimal(0.02); // amount of shares to unstake const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); ``` </Step> <Step> ### Load State and Scale the Amount Fetch the farm and the user state, then convert the unstake amount to WAD-scaled shares and clamp it to the on-chain active stake. ```typescript theme={null} 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); ``` <Note> `unstakeIx` takes WAD-scaled shares, not raw lamports like `stakeIx`. Scale with `UNSTAKE_AMOUNT * 10^decimals * WAD`, then clamp to `userState.activeStakeScaled` so you never request more than is staked. The clamp also handles dust and an "unstake all" request. </Note> </Step> <Step> ### Build Unstake Instructions Refresh the farm and user so reward accounting is current, then unstake. ```typescript theme={null} const instructions = [ await farms.refreshFarmIx(FARM, scopePrices), await farms.refreshUserIx(existing.key, FARM, scopePrices), await farms.unstakeIx(signer, FARM, amountScaled, scopePrices), ]; ``` </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("Unstake successful! Signature:", signature); ``` <Check> The unstake is complete. Your stake is now pending withdrawal and cooling down. Once the farm's withdrawal cooldown elapses, withdraw it 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, FarmState, UserState } 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 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("9wSac
프로젝트로 돌아가기