Kamino 백서

Kamino

원문

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

SDK" icon="globe" href="https://github.com/Kamino-Finance/scope-sdk"> Oracle price aggregation SDK </Card> </CardGroup> # Redeem cTokens Source: https://kamino.com/docs/build/tutorials/borrow/redeem-ctokens Redeem cTokens to receive the underlying asset plus earned interest <Info> Redeem cTokens (collateral tokens) to receive the underlying asset plus any accrued interest. This process burns your cTokens and returns the deposited assets along with earned yield. </Info> ## Redeeming cTokens Burn cTokens to withdraw your deposit and interest from Kamino lending reserves. <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, parseKeypairFile } from '@kamino-finance/klend-sdk'; 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('DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek'); const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const kUsdcMint = address('7D8C5pDFxug58L9zkwK7bCiDg4kD4AygzbcZUmf5usHS'); const market = await KaminoMarket.load(rpc, marketPubkey, 400); ``` <Note> Replace `/path/to/your/keypair.json` with the actual path to your keypair file. The `kUsdcMint` address represents the cToken (kV-STKUSDC) that you'll be redeeming. </Note> </Step> <Step> ### Get User's cToken Balance Query the user's cToken account to determine how many tokens can be redeemed. ```typescript theme={null} const tokenAccounts = await rpc .getTokenAccountsByOwner(signer.address, { mint: kUsdcMint }, { encoding: 'jsonParsed' }) .send(); if (!tokenAccounts.value.length) { throw new Error('No kUSDC token account found'); } const kUsdcAccount = tokenAccounts.value[0]!; const kUsdcBalance = new BN(kUsdcAccount.account.data.parsed.info.tokenAmount.amount); console.log(`Redeeming ${kUsdcBalance.toString()} kUSDC...`); ``` <Info> The `getTokenAccountsByOwner` method fetches all token accounts owned by your wallet for the specified mint. The balance represents the total amount of cTokens you can redeem. </Info> </Step> <Step> ### Build Redeem Reserve Collateral Instructions Generate instructions to redeem cTokens and receive the underlying asset plus interest. ```typescript theme={null} const action = await KaminoAction.buildRedeemReserveCollateralTxns( market!, kUsdcBalance, usdcMint, signer, new VanillaObligation(PROGRAM_ID), undefined ); const lendingInstructions = [...action.lendingIxs, ...action.cleanupIxs]; if (!lendingInstructions.length) { throw new Error('No instructions returned by Kamino SDK'); } ``` <Info> The `buildRedeemReserveCollateralTxns` method creates instructions to burn your cTokens (kV-STKUSDC) and receive the underlying USDC plus any accrued interest. The redemption amount is calculated based on the current exchange rate. </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(lendingInstructions, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); ``` </Step> <Step> ### Send and Confirm Transaction Send the redemption transaction and wait for confirmation to receive your underlying assets. ```typescript theme={null} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`Redemption successful! Signature: ${signature}`); ``` <Check> Once the transaction is confirmed, your cTokens (kV-STKUSDC) will be burned and you'll receive the underlying asset (USDC) plus any interest earned during the holding period. The USDC will appear in your wallet. </Check> </Step> </Steps> # Refer User Without Deposit Source: https://kamino.com/docs/build/tutorials/borrow/refer-user-without-deposit Create UserMetadata with a referrer without requiring an initial deposit This tutorial shows you how to link a referrer to a user by creating UserMetadata without requiring an initial deposit. ## Refer User Without Deposit Create a UserMetadata account with a referrer without requiring an initial deposit. This allows you to link a referrer to a user before they perform any lending operations. <Note> The referrer must be set when the UserMetadata account is created and cannot be changed afterward. </Note> <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, sendAndConfirmTransactionFactory, getSignatureFromTransaction, some, } from '@solana/kit'; import { KaminoMarket, getUserLutAddressAndSetupIxs, parseKeypairFile } from '@kamino-finance/klend-sdk'; ``` </Step> <Step> ### Initialize RPC and Load Market Set up configuration constants and initialize RPC connections. ```typescript theme={null} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const REFERRER = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCfqY'); const MARKET_PUBKEY = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const WS_ENDPOINT = 'wss://api.mainnet-beta.solana.com'; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const market = await KaminoMarket.load(rpc, MARKET_PUBKEY, 400); ``` <Note> Update the `REFERRER` address with the wallet address of the referrer who will earn commission from the user's borrowing activity. </Note> </Step> <Step> ### Check Existing UserMetadata Verify that UserMetadata does not already exist for the user. ```typescript theme={null} const [, existingUserMetadata] = await market!.getUserMetadata(signer.address); if (existingUserMetadata) { throw new Error('UserMetadata already created - referrer cannot be changed!'); } ``` <Warning> Once UserMetadata is created with a referrer, the referrer cannot be changed. Always check if UserMetadata exists before attempting to create it. </Warning> </Step> <Step> ### Build User Metadata Setup Instructions Generate instructions to create the UserMetadata account with the referrer. ```typescript theme={null} const [, setupIxsArray] = await getUserLutAddressAndSetupIxs( market!, signer, some(REFERRER), false, [], [] ); const instructions = setupIxsArray.flat(); ``` <Info> `getUserLutAddressAndSetupIxs` creates the necessary instructions to set up UserMetadata with a referrer without requiring a deposit operation. </Info> </Step> <Step> ### Build and Sign Transaction Build the transaction using Kit's functional pipe pattern. ```typescript theme={null} const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const tx = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), (tx) => appendTransactionMessageInstructions(instructions, tx) ); const signed = await signTransactionMessageWithSigners(tx); ``` </Step> <Step> ### Send and Confirm Transaction Send the transaction and confirm it using WebSocket. ```typescript theme={null} const signature = getSignatureFromTransaction(signed); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { commitment: 'confirmed', skipPreflight: true, }); console.log('UserMetadata created with referrer'); console.log(`Signature: ${signature}`); ``` <Check> UserMetadata creation complete. The referrer is now permanently linked to the user and will earn commission from the user's future borrowing activity. </Check> </Step> </Steps> </Tab> <Tab title="Rust"> <Steps> <Step> ### Add Dependencies ```toml theme={null} [dependencies] klend-interface = "0.1.0" solana-pubkey = "2.1" solana-instruction = "2.1" solana-sdk = "~2.3" solana-client = "~2.3" spl-token = "7" spl-associated-token-account = "6" ``` <Note> `klend-interface` is a lightweight Rust instruction builder that creates `Vec<Instruction>` with required refresh instructions prepended automatically. </Note> </Step> <Step> ### Set Up RPC Client ```rust theme={null} use solana_client::rpc_client::RpcClient; use solana_sdk::signer::keypair::read_keypair_file; use solana_sdk::signer::Signer; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let signer = read_keypair_file("/path/to/your/keypair.json") .expect("Failed to read keypair file"); let owner = signer.pubkey(); ``` </Step> <Step> ### Derive PDAs and Build Instruction Create the `init_user_metadata` instruction linking the user to a referrer without requiring a deposit. ```rust theme={null} use klend_interface::instructions::referrer::{ init_user_metadata, InitUserMetadataAccounts, }; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; use std::str::FromStr; let referrer = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCfqY").unwrap(); // Derive PDAs let (user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &owner); let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer); // Your user's address lookup table (created during onboarding) let user_lookup_table = Pubkey::from_str("YOUR_USER_LOOKUP_TABLE_PUBKEY").unwrap(); let ix = init_user_metadata( InitUserMetadataAccounts { owner, fee_payer: owner, user_metadata, referrer_user_metadata: Some(referrer_user_metadata), }, user_lookup_table, ); ``` <Warning> Once UserMetadata is created with a referrer, the referrer cannot be changed. Always check if UserMetadata exists before attempting to create it. </Warning> </Step> <Step> ### Send Transaction ```rust theme={null} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&[ix], Some(&owner)); let recent_blockhash = rpc_client.get_latest_blockhash()?; let tx = Transaction::new(&[&signer], message, recent_blockhash); let signature = rpc_client.send_and_confirm_transaction(&tx)?; println!("UserMetadata created with referrer! Signature: {signature}"); ``` </Step> </Steps> </Tab> </Tabs> <Accordion title="When to Use This vs Deposit with Referral"> **Use this method when:** * You want to link a referrer to a user before they make their first deposit * You're creating UserMetadata as a separate step from deposit operations * You have a simpler flow that doesn't require immediate deposit **Use Deposit with Referral when:** * You want to combine UserMetadata creation and deposit in a single transaction * The user is ready to deposit immediately * You want to minimize the number of transactions </Accordion> # Referral Code Setup Source: https://kamino.com/docs/build/tutorials/borrow/referrer-setup Set up referrer state with a unique referral code This tutorial shows you how to set up your own referral code that you can share with users to earn commission from their borrowing activity. ## How Referral Codes Work Kamino's referral system allows referrers to earn commission from the borrowing activity of referred users. Each referrer creates a unique referral code that can be shared publicly without revealing a wallet address, providing a user-friendly way to distribute referral codes. <Note>In the SDK, the `shortUrl` field represents the referral code.</Note> <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, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { getInitReferrerStateAndShortUrlIxs, getReferrerForShortUrl, PROGRAM_ID, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; ``` </Step> <Step> ### Initialize RPC Load the keypair and initialize RPC connections. ```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'); ``` </Step> <Step> ### Create Referrer State with Short URL Generate a unique short URL and create the referrer state initialization instruction. ```typescript theme={null} const shortUrl = `ref-${Date.now()}`; const initReferrerIx = await getInitReferrerStateAndShortUrlIxs({ referrer: signer, shortUrl, programId: PROGRAM_ID, }); ``` <Note> The short URL must be unique, contain a maximum of 32 characters, and use only ASCII alphanumeric characters plus underscore and hyphen. </Note> </Step> <Step> ### Send Referrer Setup Transaction Build and send the transaction to initialize the referrer state on-chain. ```typescript theme={null} const { value: setupBlockhash } = await rpc .getLatestBlockhash({ commitment: 'finalized' }) .send(); const setupTx = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(setupBlockhash, tx), (tx) => appendTransactionMessageInstructions([initReferrerIx], tx) ); const setupSigned = await signTransactionMessageWithSigners(setupTx); const setupSignature = getSignatureFromTransaction(setupSigned); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(setupSigned, { commitment: 'confirmed', skipPreflight: true, }); console.log(`Referrer setup successful! Signature: ${setupSignature}`); ``` </Step> <Step> ### Verify Short URL Resolution Confirm that the short URL correctly resolves to the referrer wallet address. ```typescript theme={null} const lookedUpReferrer = await getReferrerForShortUrl(rpc, shortUrl, PROGRAM_ID); console.log(`Short URL "${shortUrl}" resolves to: ${lookedUpReferrer}`); ``` <Check> Referrer setup complete. The short URL is active and can be shared with users to establish referral relationships. </Check> </Step> </Steps> </Tab> <Tab title="Rust"> <Steps> <Step> ### Add Dependencies ```toml theme={null} [dependencies] klend-interface = "0.1.0" solana-pubkey = "2.1" solana-instruction = "2.1" solana-sdk = "~2.3" solana-client = "~2.3" spl-token = "7" spl-associated-token-account = "6" ``` <Note> `klend-interface` is a lightweight Rust instruction builder that creates `Vec<Instruction>` with required refresh instructions prepended automatically. </Note> </Step> <Step> ### Set Up RPC Client ```rust theme={null} use solana_client::rpc_client::RpcClient; use solana_sdk::signer::keypair::read_keypair_file; use solana_sdk::signer::Signer; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let signer = read_keypair_file("/path/to/your/keypair.json") .expect("Failed to read keypair file"); let owner = signer.pubkey(); ``` </Step> <Step> ### Derive PDAs and Build Instruction ```rust theme={null} use klend_interface::instructions::referrer::{ init_referrer_state_and_short_url, InitReferrerStateAndShortUrlAccounts, }; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; let referrer = signer.pubkey(); let short_url = format!("ref-{}", std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()); // Derive required PDAs let (referrer_state, _) = pda::referrer_state(&KLEND_PROGRAM_ID, &referrer); let (referrer_short_url, _) = pda::referrer_short_url(&KLEND_PROGRAM_ID, &short_url); let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer); let ix = init_referrer_state_and_short_url( InitReferrerStateAndShortUrlAccounts { referrer, referrer_state, referrer_short_url, referrer_user_metadata, }, short_url.clone(), ); ``` <Note> The short URL must be unique, contain a maximum of 32 characters, and use only ASCII alphanumeric characters plus underscore and hyphen. </Note> </Step> <Step> ### Send Transaction ```rust theme={null} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&[ix], Some(&referrer)); let recent_blockhash = rpc_client.get_latest_blockhash()?; let tx = Transaction::new(&[&signer], message, recent_blockhash); let signature = rpc_client.send_and_confirm_transaction(&tx)?; println!("Referrer setup successful! Short URL: {short_url}"); println!("Signature: {signature}"); ``` </Step> </Steps> </Tab> </Tabs> # Repay and Withdraw Source: https://kamino.com/docs/build/tutorials/borrow/repay-and-withdraw Repay borrowed assets and withdraw your collateral ## Repay Debt Repay borrowed assets to improve your position health. <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); c
프로젝트로 돌아가기