Kamino 백서

Kamino

원문

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

ize)] struct KswapResponse { data: KswapData } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct KswapData { transaction: String, expected_amount_out: String, min_amount_out: String, } let liquidator_debt_ata = spl_associated_token_account::get_associated_token_address_with_program_id( &owner, &repay_reserve.liquidity.mint_pubkey, &repay_reserve.liquidity.token_program, ); use spl_token::state::Account as TokenAccount; use solana_sdk::program_pack::Pack; let wallet_balance = rpc_client.get_account(&liquidator_debt_ata) .ok() .and_then(|a| TokenAccount::unpack(&a.data).ok()) .map(|acct| acct.amount) .unwrap_or(0); if wallet_balance < repay_amount { let wsol = Pubkey::from_str("So11111111111111111111111111111111111111112")?; // Calculate how much SOL to swap based on debt USD value let debt_price: f64 = Fraction::from_bits( u128::from(repay_reserve.liquidity.market_price_sf) ).to_num(); let repay_usd = repay_amount as f64 / 10f64.powi(repay_reserve.liquidity.mint_decimals as i32) * debt_price; let sol_price = parsed_reserves.iter() .find(|(_, r)| r.liquidity.mint_pubkey == wsol) .map(|(_, r)| Fraction::from_bits( u128::from(r.liquidity.market_price_sf) ).to_num::<f64>()) .unwrap_or(100.0); let sol_balance = rpc_client.get_balance(&owner)?; let swap_amount = (repay_usd / sol_price * 1e9) as u64; let swap_amount = swap_amount.min(sol_balance.saturating_sub(5_000_000)); let client = reqwest::blocking::Client::new(); let resp = client .get("https://api.kamino.finance/kswap/swap/") .query(&[ ("tokenIn", wsol.to_string()), ("tokenOut", repay_reserve.liquidity.mint_pubkey.to_string()), ("amountIn", swap_amount.to_string()), ("maxSlippageBps", "50".to_string()), ("wallet", owner.to_string()), ("wrapAndUnwrapSol", "true".to_string()), ]) .send()?; if !resp.status().is_success() { let status = resp.status(); let body = resp.text().unwrap_or_default(); return Err(format!("KSwap API error {status}: {body}").into()); } let kswap: KswapResponse = resp.json()?; // Decode, re-sign, and send the swap transaction use base64::Engine; let tx_bytes = base64::engine::general_purpose::STANDARD .decode(&kswap.data.transaction)?; let swap_tx: VersionedTransaction = bincode::deserialize(&tx_bytes)?; let blockhash = rpc_client.get_latest_blockhash()?; let mut msg = swap_tx.message; msg.set_recent_blockhash(blockhash); let signed = VersionedTransaction::try_new(msg, &[&signer])?; rpc_client.send_and_confirm_transaction_with_spinner(&signed)?; } ``` </Step> <Step> ### Derive Token Accounts Derive ATAs using the actual token programs from the reserve data. The collateral cToken mint address is read directly from the `Reserve` struct. ```rust theme={null} let user_source_liquidity = spl_associated_token_account::get_associated_token_address_with_program_id( &owner, &repay_reserve.liquidity.mint_pubkey, &repay_reserve.liquidity.token_program, ); let ctoken_mint = withdraw_reserve.collateral.mint_pubkey; let ctoken_program = rpc_client.get_account(&ctoken_mint) .map(|a| a.owner) .unwrap_or(spl_token::ID); let user_destination_collateral = spl_associated_token_account::get_associated_token_address_with_program_id( &owner, &ctoken_mint, &ctoken_program, ); let user_destination_liquidity = spl_associated_token_account::get_associated_token_address_with_program_id( &owner, &withdraw_reserve.liquidity.mint_pubkey, &withdraw_reserve.liquidity.token_program, ); ``` </Step> <Step> ### Create Token Accounts Create the associated token accounts if they do not already exist. Uses `create_associated_token_account_idempotent` which is a no-op if the account is already initialized. ```rust theme={null} let ata_ixs = vec![ spl_associated_token_account::instruction::create_associated_token_account_idempotent( &owner, &owner, &repay_reserve.liquidity.mint_pubkey, &repay_reserve.liquidity.token_program, ), spl_associated_token_account::instruction::create_associated_token_account_idempotent( &owner, &owner, &ctoken_mint, &ctoken_program, ), spl_associated_token_account::instruction::create_associated_token_account_idempotent( &owner, &owner, &withdraw_reserve.liquidity.mint_pubkey, &withdraw_reserve.liquidity.token_program, ), ]; let blockhash = rpc_client.get_latest_blockhash()?; let ata_tx = Transaction::new(&[&signer], Message::new(&ata_ixs, Some(&owner)), blockhash); rpc_client.send_and_confirm_transaction(&ata_tx)?; ``` </Step> <Step> ### Build Liquidation Instructions Build refresh instructions for each reserve and the obligation, then the liquidation instruction using actual addresses from the `Reserve` struct. ```rust theme={null} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let (lma, _) = pda::lending_market_authority( &KLEND_PROGRAM_ID, &repay_reserve.lending_market, ); let obligation_info = ObligationInfo::from_obligation( obligation_pubkey, obligation, ); let all_reserve_infos: Vec<ReserveInfo> = parsed_reserves.iter() .map(|(pk, r)| ReserveInfo::from_reserve(*pk, r)) .collect(); // Refresh reserves and obligation let mut instructions = Vec::new(); for info in &all_reserve_infos { if obligation_info.deposit_reserves.contains(&info.address) || obligation_info.borrow_reserves.contains(&info.address) { instructions.push(refresh::refresh_reserve(info)); } } instructions.push(refresh::refresh_obligation( &repay_reserve.lending_market, &obligation_info, )); // Remaining accounts: deposit reserves + borrow reserves let mut remaining: Vec<AccountMeta> = Vec::new(); for r in &obligation_info.deposit_reserves { remaining.push(AccountMeta::new(*r, false)); } for r in &obligation_info.borrow_reserves { remaining.push(AccountMeta::new(*r, false)); } // Calculate slippage protection to guard against sandwich attacks. // Without this, a malicious validator could reorder transactions // to extract the full liquidation bonus. const MIN_RECEIVED_SLIPPAGE_BPS: u16 = 200; // 2% let collateral_price: f64 = Fraction::from_bits( u128::from(withdraw_reserve.liquidity.market_price_sf) ).to_num(); let collateral_decimals = withdraw_reserve.liquidity.mint_decimals; let bonus_bps = withdraw_reserve.config.min_liquidation_bonus_bps as f64; let protocol_fee_pct = withdraw_reserve.config.protocol_liquidation_fee_pct as f64; let debt_price: f64 = Fraction::from_bits( u128::from(repay_reserve.liquidity.market_price_sf) ).to_num(); let repay_usd = repay_amount as f64 / 10f64.powi(repay_reserve.liquidity.mint_decimals as i32) * debt_price; let min_received = if collateral_price > 0.0 { let collateral_value = repay_usd * (1.0 + bonus_bps / 10_000.0); let after_fee = collateral_value * (1.0 - protocol_fee_pct / 100.0); let expected_tokens = after_fee / collateral_price * 10f64.powi(collateral_decimals as i32); let with_slippage = expected_tokens * (10_000.0 - MIN_RECEIVED_SLIPPAGE_BPS as f64) / 10_000.0; (with_slippage as u64).max(1) } else { 1 }; // Liquidation instruction with actual reserve struct addresses instructions.push(liquidate_obligation_and_redeem_reserve_collateral_v2( LiquidateObligationAndRedeemReserveCollateralV2Accounts { liquidator: owner, obligation: obligation_pubkey, lending_market: repay_reserve.lending_market, lending_market_authority: lma, repay_reserve: repay_reserve_pubkey, repay_reserve_liquidity_mint: repay_reserve.liquidity.mint_pubkey, repay_reserve_liquidity_supply: repay_reserve.liquidity.supply_vault, withdraw_reserve: withdraw_reserve_pubkey, withdraw_reserve_liquidity_mint: withdraw_reserve.liquidity.mint_pubkey, withdraw_reserve_collateral_mint: withdraw_reserve.collateral.mint_pubkey, withdraw_reserve_collateral_supply: withdraw_reserve.collateral.supply_vault, withdraw_reserve_liquidity_supply: withdraw_reserve.liquidity.supply_vault, withdraw_reserve_liquidity_fee_receiver: withdraw_reserve.liquidity.fee_vault, user_source_liquidity, user_destination_collateral, user_destination_liquidity, repay_liquidity_token_program: repay_reserve.liquidity.token_program, withdraw_liquidity_token_program: withdraw_reserve.liquidity.token_program, collateral_obligation_farm_user_state: None, collateral_reserve_farm_state: None, debt_obligation_farm_user_state: None, debt_reserve_farm_state: None, }, repay_amount, min_received, 0, // max_allowed_ltv_override_percent (must be 0 on mainnet) remaining, )); ``` <Warning> The `helpers::liquidate::liquidate()` helper uses `ReservePdas::derive()` which does not match reserves created by older program versions. Use the actual addresses from the `Reserve` struct as shown above. </Warning> </Step> <Step> ### Simulate and Send ```rust theme={null} let recent_blockhash = rpc_client.get_latest_blockhash()?; let message = Message::new(&instructions, Some(&owner)); let tx = Transaction::new(&[&signer], message, recent_blockhash); // Simulate first let sim = rpc_client.simulate_transaction(&tx)?; if let Some(err) = sim.value.err { println!("Simulation failed: {err}"); return Ok(()); } // Send with fresh blockhash let fresh_blockhash = rpc_client.get_latest_blockhash()?; let fresh_msg = Message::new(&instructions, Some(&owner)); let fresh_tx = Transaction::new(&[&signer], fresh_msg, fresh_blockhash); let signature = rpc_client.send_and_confirm_transaction(&fresh_tx)?; println!("Liquidation executed: {signature}"); ``` </Step> </Steps> </Tab> </Tabs> # Mint cTokens Source: https://kamino.com/docs/build/tutorials/borrow/mint-ctokens Mint cTokens by depositing liquidity into Kamino lending reserves <Info> Mint cTokens (collateral tokens) by depositing assets into Kamino lending reserves. cTokens represent your deposit and accrue interest over time, which can be redeemed later for the underlying asset plus earned interest. </Info> ## Minting cTokens Deposit reserve liquidity to receive cTokens in your wallet. <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, type Signature, } 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 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 Reserve Liquidity Instructions Generate instructions to deposit USDC and receive cTokens (kV-STKUSDC) in your wallet. ```typescript theme={null} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const depositAmount = new BN(1_000_000); // 1 USDC (6 decimals) const action = await KaminoAction.buildDepositReserveLiquidityTxns( market!, depositAmount, usdcMint, signer, new VanillaObligation(PROGRAM_ID), undefined ); ``` <Info> The `buildDepositReserveLiquidityTxns` method creates instructions to deposit liquidity into the reserve. This will mint cTokens (e.g., kV-STKUSDC) to your wallet representing your deposit plus accrued interest. </Info> </Step> <Step> ### Send Setup Transaction (If Needed) If setup instructions are present, send the setup transaction first and wait for confirmation. ```typescript theme={null} let setupSignature: Signature | undefined; if (action.setupIxs && action.setupIxs.length > 0) { const { value: setupBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const setupTxMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(setupBlockhash, tx), (tx) => appendTransactionMessageInstructions(action.setupIxs, tx) ); const setupSignedTx = await signTransactionMessageWithSigners(setupTxMessage); setupSignature = getSignatureFromTransaction(setupSignedTx); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(setupSignedTx, { commitment: 'confirmed', skipPreflight: true, }); // Wait for accounts to settle and LUT activation await new Promise((resolve) => setTimeout(resolve, 2000)); } ``` <Warning> Setup transactions must be confirmed and Address Lookup Tables (ALTs) must be activated before sending the main deposit transaction. Waiting 2 seconds ensures account settlement. </Warning> </Step> <Step> ### Build and Sign Deposit Transaction Build and sign the main deposit transaction with a fresh blockhash. ```typescript theme={null} const lendingInstructions = [...action.computeBudgetIxs, ...action.lendingIxs, ...action.cleanupIxs]; if (!lendingInstructions.length) { throw new Error('No instructions returned by Kamino SDK'); } 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); ``` <Note> A fresh blockhash is fetched for the main transaction to ensure it remains valid after the setup transaction completes. </Note> </Step> <Step> ### Send and Confirm Transaction Send the deposit transaction and wait for confirmation to receive your cTokens. ```typescript theme={null} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log( `Deposit successful! You should now have kUSDC cTokens in your wallet. Signature: ${signature}${ setupSignature ? `\nSetup transaction: https://solscan.io/tx/${setupSignature}` : '' }` ); ``` <Check> Once the transaction is confirmed, cTokens (kV-STKUSDC) will appear in your wallet. These tokens represent your deposit and will accrue interest over time. You can redeem them later for the underlying asset plus earned interest. </Check> </Step> </Steps> # Multiply Deposit with KSwap Source: https://kamino.com/docs/build/tutorials/borrow/multiply-deposit-kswap Create leveraged positions using flash loans in a single atomic transaction <p>A multiply deposit creates a leveraged collateral position in a single, atomic transaction by combining an initial deposit with temporary liquidity.</p> <p>When a multiply deposit is initiated, the protocol first temporarily borrows the debt token (for example, USDC) through a flash loan. The borrowed amount is swapped into the collateral token (for example, TSLAx) using KSwap (Kamino's token swap SDK). The resulting collateral is then deposited into Kamino Lend. With the collateral in place, the position borrows the debt token against it, and the borrowed amount is used to repay the flash loan before the transaction completes. The result is a leveraged position with increased exposure to the collateral token and an outstanding debt balance.</p> ## Multiply Deposit with xStocks Create a leveraged position in a single atomic transaction using Klend's multiply feature and KSwap multi-route swap optimization. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, KSwap routing, and transaction building. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, none, compressTransactionMessageUsingAddressLookupTables, } from '@solana/kit'; import type { Address } from '@solana/kit'; import { KaminoMarket, MultiplyObligation, PROGRAM_ID, parseKeypairFile, getDepositWithLeverageIxs, getUserLutAddressAndSetupIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, ObligationTypeTag, simulateTx, DEFAULT_RECENT_SLOT_DURATION_MS, } from '@kamino-finance/klend-sdk'; import { KswapSdk } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; import Decimal from 'decimal.js'; import { getKswapQuoter, getKswapSwapper } from './kswap_utils.js'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; ``` </Step> <Step> ### Load Configuration and Initialize SDKs Load the keypair and initialize RPC connections, the market, Scope for oracle prices, and KSwap for routing. ```typescript theme={null} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const CDN_ENDPOINT = 'https://cdn.kamino.finance'; 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const debtTokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const XSTOCKS_MARKET_LUT = address('8ofreL6hKfEet1DnhHVGvCTnSdz4pg85PpbuCUHnEcKm'); // xStocks Market LUT let collTokenMint: Address; const market = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS); const scope = new Scope('mainnet-beta', rpc); const kswapSdk = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); ``` <Note> The xStocks Market LUT can be found via the Markets API: `https://api.kamino.finance/v2/kamino-market?programId=KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD`. The Scope SDK provides oracle price data, and the KSwap SDK enables multi-DEX routing for optimal swap execution. </Note> </Step> <Step> ### Find TSLAx Reserve in Market Dynamically discover the TSLAx token mint by searching the market reserves by symbol. ```typescript theme={null} const tslaReserve = Array.from(market!.reserves.values()).find((reserve) => reserve.symbol === 'TSLAx'); if (!tslaReserve) { console.log('TSLAx reserve not found in xStocks market'); } collTokenMint = tslaReserve.getLiquidityMint(); console.log(`Found TSLAx mint: ${collTokenMint}`); ``` <Info> This dynamic discovery approach allows the code to work across different markets without hardcoding token mint addresses. The reserve symbol identifies the asset (TSLAx for tokenized Tesla stock), and we retrieve its mint address programmatically. </Info> </Step> <Step> ### Fetch Multiply Lookup Tables Fetch multiply-specific Address Lookup Tables (LUTs) from Kamino's CDN for the TSLAx/USDC pair to compress transaction size. ```typescript theme
프로젝트로 돌아가기