Kamino 백서

Kamino

원문

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

/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> ### Fetch Obligation and Build Repay Instructions Fetch the existing obligation and generate repay instructions for the specified token and amount. ```typescript theme={null} const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); const repayAmount = new BN(1_000_000); // 1.00 USDT (6 decimals) const currentSlot = await rpc.getSlot().send(); const obligation = await market!.getObligationByWallet(address(signer.address), new VanillaObligation(PROGRAM_ID)); if (!obligation) { throw new Error('No obligation found for this wallet. You must have an active borrow to repay.'); } const repayAction = await KaminoAction.buildRepayTxns( market!, repayAmount, usdtMint, signer, new VanillaObligation(PROGRAM_ID), true, undefined, currentSlot, signer, 1_000_000, true, false ); const allInstructions = [ ...(repayAction.setupIxs || []), ...(repayAction.lendingIxs || []), ...(repayAction.cleanupIxs || []), ]; ``` <Info> The `buildRepayTxns` method creates instructions to repay your borrowed assets. Repaying reduces your debt and improves your loan-to-value ratio. </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 repay transaction and wait for confirmation. ```typescript theme={null} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Repay successful! Signature:', signature); ``` <Check> Once the repay transaction is confirmed, your debt is reduced and your loan-to-value ratio improves. You stop paying interest on the repaid amount. </Check> </Step> </Steps> ## Withdraw Collateral Withdraw collateral from your obligation. <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 Withdraw Collateral Instructions Generate withdraw instructions for the specified collateral token and amount. ```typescript theme={null} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const withdrawAmount = new BN(1_000_000); // 1 USDC (6 decimals) const withdrawAction = await KaminoAction.buildWithdrawTxns( market!, withdrawAmount, usdcMint, signer, new VanillaObligation(PROGRAM_ID), true, undefined, 1_000_000, true, false ); const allInstructions = [ ...(withdrawAction.setupIxs || []), ...(withdrawAction.lendingIxs || []), ...(withdrawAction.cleanupIxs || []), ]; ``` <Info> The `buildWithdrawTxns` method creates instructions to withdraw your collateral. You can only withdraw collateral if your position remains healthy after the withdrawal. </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 withdraw transaction and wait for confirmation. ```typescript theme={null} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Withdrawal successful! Signature:', signature); ``` <Check> Once the withdraw transaction is confirmed, your collateral is returned to your wallet. Your borrowing capacity decreases and your loan-to-value ratio may increase. </Check> </Step> </Steps> # Deposit and Borrow Source: https://kamino.com/docs/build/borrow/tutorials/rust/deposit-and-borrow Deposit collateral and borrow assets using the klend-interface Rust crate ## Deposit Collateral Deposit assets as collateral to enable borrowing. <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> ### Build Obligation Context Derive the obligation PDA, fetch its account data along with all associated reserves, and build an `ObligationContext`. ```rust theme={null} use klend_interface::ObligationContext; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; use std::str::FromStr; let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); // Derive the obligation PDA let (obligation_pubkey, _) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, &Pubkey::default(), &Pubkey::default(), ); // Fetch the obligation account let obligation_data = rpc_client.get_account(&obligation_pubkey)?; // Discover which reserves the obligation references let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; // Fetch all reserve accounts in one RPC call let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; // Build the context let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() .zip(reserve_accounts.iter()) .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) .collect(); let ctx = ObligationContext::from_account_data( obligation_pubkey, &obligation_data.data, &reserves )?; ``` <Note> `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. </Note> </Step> <Step> ### Derive Token Accounts ```rust theme={null} use spl_associated_token_account::get_associated_token_address; // User's ATA for the deposit token (e.g. USDC) let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); let user_source_liquidity = get_associated_token_address(&owner, &liquidity_mint); ``` </Step> <Step> ### Build Instructions ```rust theme={null} let instructions = ctx.deposit( owner, &reserve_pubkey, user_source_liquidity, 3_000_000, // 3 USDC (6 decimals) )?; // Returns: [refresh_reserves..., refresh_obligation, deposit_and_collateral_v2] ``` </Step> <Step> ### Build and Send Transaction ```rust theme={null} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&instructions, 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!("Deposit successful! Signature: {signature}"); ``` <Check> The deposit is complete. Your collateral has been supplied and your borrow position is open. </Check> </Step> </Steps> # Repay and Withdraw Source: https://kamino.com/docs/build/borrow/tutorials/rust/repay-and-withdraw Repay borrowed assets and withdraw collateral using the klend-interface Rust crate ## Repay Debt Repay borrowed assets to improve your position health. <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> ### Build Obligation Context ```rust theme={null} use klend_interface::ObligationContext; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; use std::str::FromStr; let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let repay_reserve_pubkey = Pubkey::from_str("FBSyPnxtHKLBZ4UeeUyAnbtFuAmTHLtso9YtsqRDRWpM").unwrap(); // Derive the obligation PDA let (obligation_pubkey, _) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, &Pubkey::default(), &Pubkey::default(), ); // Fetch the obligation account let obligation_data = rpc_client.get_account(&obligation_pubkey)?; // Discover which reserves the obligation references let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; // Fetch all reserve accounts in one RPC call let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; // Build the context let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() .zip(reserve_accounts.iter()) .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) .collect(); let ctx = ObligationContext::from_account_data( obligation_pubkey, &obligation_data.data, &reserves )?; ``` <Note> `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. </Note> </Step> <Step> ### Derive Token Accounts ```rust theme={null} use spl_associated_token_account::get_associated_token_address; // User's ATA for the repay token (e.g. USDT) let repay_liquidity_mint = Pubkey::from_str("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB").unwrap(); let user_source_liquidity = get_associated_token_address(&owner, &repay_liquidity_mint); ``` </Step> <Step> ### Build Instructions ```rust theme={null} let instructions = ctx.repay( owner, &repay_reserve_pubkey, user_source_liquidity, 1_000_000, // 1 USDT (6 decimals) )?; // Returns: [refresh_reserves..., refresh_obligation, repay_obligation_liquidity_v2] ``` </Step> <Step> ### Build and Send Transaction ```rust theme={null} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&instructions, 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!("Repay successful! Signature: {signature}"); ``` <Info> Repaying reduces your debt and improves your loan-to-value (LTV) ratio, making your position healthier and reducing liquidation risk. </Info> <Check> The repay is complete. Your debt has been reduced. </Check> </Step> </Steps> ## Withdraw <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> ### Build Obligation Context ```rust theme={null} use klend_interface::ObligationContext; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; use std::str::FromStr; let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); // Derive the obligation PDA let (obligation_pubkey, _) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, &Pubkey::default(), &Pubkey::default(), ); // Fetch the obligation account let obligation_data = rpc_client.get_account(&obligation_pubkey)?; // Discover which reserves the obligation references let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; // Fetch all reserve accounts in one RPC call let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; // Build the context let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() .zip(reserve_accounts.iter()) .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) .collect(); let ctx = ObligationContext::from_account_data( obligation_pubkey, &obligation_data.data, &reserves )?; ``` <Note> `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. </Note> </Step> <Step> ### Derive Token Accounts ```rust theme={null} use spl_associated_token_account::get_associated_token_address; // User's ATA for the withdrawal token (e.g. USDC) let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); let user_dest_liquidity = get_associated_token_address(&owner, &liquidity_mint); ``` </Step> <Step> ### Build Instructions ```rust theme={null} let instructions = ctx.withdraw( owner, &reserve_pubkey, user_dest_liquidity, 1_000_000, // 1 USDC (6 decimals) )?; // Returns: [refresh_reserves..., refresh_obligation, withdraw_and_redeem] ``` <Note> Use `helpers::withdraw::redeem()` if you hold cTokens without an obligation — see the [Withdraw for Lending](/docs/build/developers/borrow/operations/withdraw#withdraw-for-lending) tab. </Note> </Step> <Step> ### Build and Send Transaction ```rust theme={null} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&instructions, 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!("Withdrawal successful! Signature: {signature}"); ``` <Check> The withdrawal is complete. Your collateral has been returned to your wallet. </Check> </Step> </Steps> # Overview Source: https://kamino.com/docs/build/cli/index Command line tool to manage Kamino Lend markets, reserves, and vaults The Kamino Manager CLI is a command line tool used to create and manage Kamino lending markets, reserves, and Kamino vaults. The Kamino CLI provides: * Create and configure lending markets with reserves for different token types and custom risk parameters * Build and manage automated liquidity vaults with adjustable allocation strategies and yield optimization * Monitor performance metrics and update market or vault settings as needed <CardGroup> <Card title="Installation & Setup" icon="download" href="/docs/build/cli/installation-setup"> Install and configure the Kamino Manager CLI </Card> <Card title="Market Operations" icon="coins" href="/docs/build/cli/market-operations"> Create and manage Kamino lending markets and reserves </Card> <Card title="Vault Operations" icon="chart-line" href="/docs/build/cli/vault-operations"> Create and manage Kamino vaults </Card> </CardGroup> # Install and Setup the Kamino CLI Source: https://kamino.com/docs/build/cli/installation-setup Get started with the Kam
프로젝트로 돌아가기