Kamino 백서

Kamino

원문

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

e={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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const market = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS); ``` </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'); } const collTokenMint = tslaReserve.getLiquidityMint(); const debtTokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC ``` <Info> This dynamic discovery approach allows the code to work across different markets without hardcoding token mint addresses. </Info> </Step> <Step> ### Configure Repay Parameters Set the amount of USDC to repay. This example repays \$10 USDC. ```typescript theme={null} const repayAmount = new BN(10_000_000); // 10.00 USDC (6 decimals) const currentSlot = await rpc.getSlot().send(); ``` <Note> You can repay any amount up to your total debt. After repaying, you are able to withdraw your collateral. </Note> </Step> <Step> ### Fetch Existing Multiply Obligation Create the multiply obligation type and fetch the existing position from the blockchain. ```typescript theme={null} const obligationType = new MultiplyObligation(collTokenMint, debtTokenMint, PROGRAM_ID); const obligation = await market!.getObligationByWallet(address(signer.address), obligationType); if (!obligation) { console.log('No obligation found for this wallet. You must have an active borrow to repay.'); } ``` <Info> The `MultiplyObligation` type identifies this as a leveraged position rather than a standard borrow. The obligation must exist before you can repay debt. </Info> </Step> <Step> ### Build Repay Transaction Use `KaminoAction.buildRepayTxns` to generate the repay instructions. ```typescript theme={null} const repayAction = await KaminoAction.buildRepayTxns( market!, repayAmount, debtTokenMint, signer, obligationType, true, // useV2Ixs undefined, // scopeRefreshConfig currentSlot, signer, // payer 1_000_000, // extraComputeBudget true, // includeAtaIxs false // requestElevationGroup ); const allInstructions = [ ...(repayAction.setupIxs || []), ...(repayAction.lendingIxs || []), ...(repayAction.cleanupIxs || []), ]; ``` <Info> `buildRepayTxns` handles all the complexity of repaying multiply positions, including ATA creation, scope price refreshes, and obligation updates. </Info> </Step> <Step> ### Send Transaction Get a fresh blockhash, build the transaction, sign it, and send it to the network. ```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); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`Multiply repay successful! Repaid $10 USDC debt on TSLAx multiply position.`); console.log(`Transaction signature: ${signature}`); ``` <Check> The repay transaction is complete, reducing your debt balance and improving your position's health factor. </Check> </Step> </Steps> ### Borrow and Multiply SDK Methods <div> | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid | | `getWithdrawWithLeverageIxs` | Deleverage and withdraw | Sell collateral to repay debt and receive remaining value in wallet | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | <Note> **Multiply operations** use `MultiplyObligation`. **Vanilla operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. </Note> </div> # Multiply Withdraw with xStocks Source: https://kamino.com/docs/build/developers/multiply/operations/withdraw-xstocks Withdraw collateral from leveraged xStocks positions after repaying debt <p>Withdrawing collateral from a multiply position after fully repaying debt allows you to unlock and retrieve your equity.</p> <Note> This operation uses `buildWithdrawTxns` (not `getWithdrawWithLeverageIxs`, which is for deleveraging by selling collateral to repay debt). </Note> ## Multiply Withdraw with xStocks Withdraw TSLAx collateral from a multiply position after all debt has been repaid. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and transaction building. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, MultiplyObligation, PROGRAM_ID, parseKeypairFile, DEFAULT_RECENT_SLOT_DURATION_MS, } from '@kamino-finance/klend-sdk'; import BN from 'bn.js'; ``` </Step> <Step> ### Load Configuration and Initialize Market Load the keypair and initialize the xStocks 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const market = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS); ``` </Step> <Step> ### Find TSLAx Reserve 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'); } const collTokenMint = tslaReserve.getLiquidityMint(); const debtTokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC ``` </Step> <Step> ### Configure Withdrawal Parameters Set the amount of TSLAx collateral to withdraw. ```typescript theme={null} const withdrawAmount = new BN(1_250_000); // ~$5 worth of TSLAx (8 decimals) const currentSlot = await rpc.getSlot().send(); ``` <Note> TSLAx uses 8 decimals. </Note> <Warning> `buildWithdrawTxns` requires all debt to be repaid before withdrawing collateral. If you have outstanding debt, repay it first or use `getWithdrawWithLeverageIxs` to deleverage by selling collateral. </Warning> </Step> <Step> ### Fetch Existing Multiply Obligation Create the multiply obligation type and fetch the existing position from the blockchain. ```typescript theme={null} const obligationType = new MultiplyObligation(collTokenMint, debtTokenMint, PROGRAM_ID); const obligation = await market!.getObligationByWallet(address(signer.address), obligationType); if (!obligation) { console.log('No obligation found for this wallet. You must have collateral deposited to withdraw.'); } ``` </Step> <Step> ### Build Withdrawal Transaction Use `KaminoAction.buildWithdrawTxns` to generate the withdrawal instructions. ```typescript theme={null} const withdrawAction = await KaminoAction.buildWithdrawTxns( market!, withdrawAmount, collTokenMint, signer, obligationType, true, // useV2Ixs undefined, // scopeRefreshConfig currentSlot, 1_000_000, // extraComputeBudget true, // includeAtaIxs false // requestElevationGroup ); const allInstructions = [ ...(withdrawAction.setupIxs || []), ...(withdrawAction.lendingIxs || []), ...(withdrawAction.cleanupIxs || []), ]; ``` <Info> `buildWithdrawTxns` is used for withdrawing collateral when debt is fully repaid. For deleveraging (selling collateral to repay outstanding debt), use `getWithdrawWithLeverageIxs` instead. </Info> </Step> <Step> ### Send Transaction Get a fresh blockhash, build the transaction, sign it, and send it to the network. ```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); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`Withdraw successful! Withdrew ~$5 worth of TSLAx from multiply position.`); console.log(`Transaction signature: ${signature}`); ``` <Check> The withdrawal is complete. Your TSLAx collateral has been transferred to your wallet. </Check> </Step> </Steps> ### Borrow and Multiply SDK Methods <div> | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid | | `getWithdrawWithLeverageIxs` | Deleverage and withdraw | Sell collateral to repay debt and receive remaining value in wallet | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | <Note> **Multiply operations** use `MultiplyObligation`. **Vanilla operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. </Note> </div> # Multiply Source: https://kamino.com/docs/build/developers/multiply/overview Understanding how Multiply creates leveraged positions through atomic looping with flash loans ## What is Multiply? Multiply creates leveraged positions in a single atomic transaction by automating the looping process through flash loans. Instead of manually executing 8-10 separate deposit-borrow-swap cycles, Multiply collapses the entire leverage-building process into one transaction that either succeeds completely or reverts with no state changes. ### Borrow and Multiply SDK Methods <div> | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid | | `getWithdrawWithLeverageIxs` | Deleverage and withdraw | Sell collateral to repay debt and receive remaining value in wallet | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | <Note> **Multiply operations** use `MultiplyObligation`. **Standard borrow operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. </Note> </div> ### Borrow and Multiply: Rust Crate Helpers The Rust [`klend-interface`](https://crates.io/crates/klend-interface) crate exposes the lending primitives and flash loans, but does not include leveraged combo helpers. <div> | Helper | Operation | When to Use | | - | - | - | | `helpers::flash::flash_loan` | Atomic flash borrow + repay pair | Building any flash-loan-based flow | | `ObligationContext.repay` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `ObligationContext.withdraw` | Withdraw collateral | Withdrawing collateral after debt is repaid | <Note> Leveraged combo operations (`getDepositWithLeverageIxs`, `getWithdrawWithLeverageIxs`, `getRepayWithCollIxs`) are **not** available in the Rust crate — they bundle flash loans with KSwap routing, which only the TypeScript SDK builds. </Note> </div> *** ## SDK vs API vs Rust Crate: What's Available Understanding which operations are reachable from the SDK, the API, and the Rust crate is critical for building Multiply integrations. | Operation | SDK | API | Rust Crate | Notes | | - | - | - | - | - | | **Flash Loans** | Available | Not available | Available | Atomic transactions — SDK or Rust crate | | **Multiply Deposit (with KSwap)** | Required | Not available | Not available | Leveraged positions with swap routing — SDK only | | **Standard Borrow Operations** | Available | Available | Available | Deposit, borrow, repay, withdraw across SDK / API / Rust | | **Position Data** | Available | Available | Available | Read obligation data via any path | | **Market Reserve Data** | Available | Available | Limited | APYs, utilization, liquidity via SDK or API | ## Flash Loans A flash loan is an uncollateralized loan that must be borrowed and fully repaid within the same transaction block. This atomic property makes flash loans risk-free for the protocol. ### Flash Loan Properties | Property | Description | | - | - | | **Collateral Required** | None — uncollateralized | | **Repayment Window** | Same transaction block | | **Failure Behavior** | Entire transaction reverts (no state changes) | | **Fee** | 0.001% per transaction | | **Risk to Protocol** | Zero — atomicity guarantees repayment or reversion | <Info> If a flash loan cannot be repaid — due to slippage, insufficient liquidity, or any other failure — the entire transaction reverts. No intermediate state is committed to the blockchain. </Info> *** ## Looping: Manual vs Atomic Looping is the process of repeatedly depositing collateral, borrowing against it, and reinvesting the borrowed funds to amplify exposure. The method determines risk, cost, and execution complexity. ### Comparison Table | Aspect | Manual Looping | Atomic Looping (Multiply) | | - | - | - | | **Transaction Count** | 8-10 separate transactions | 1 atomic transaction | | **Price Exposure** | Exposed to price changes between each step | No exposure — all steps execute atomically | | **Slippage Risk** | Slippage on each swap individually | Single consolidated slippage check | | **Gas Costs** | Higher — multiple transactions | Lower — single transaction | | **Execution Risk** | High — any step can fail independently | Low — all-or-nothing execution | | **Time to Complete** | Minutes (dependent on block confirmations) | Single block (\~400ms on Solana) | | **Complexity** | Requires manual coordination of steps | Fully automated | <Warning> Manual looping exposes you to market price movements between transactions. If the collateral asset price drops or borrow rates spike mid-loop, you may end up with a worse position than intended — or fail to complete the loop entirely. </Warning> *** ## The Multiply Transaction Flow Multiply executes leverage creation in a precise sequence of steps within a single atomic transaction. <Steps> <Step title="Flash Borrow"> Protocol borrows the required debt token amount (e.g., SOL) via flash loan. No collateral is required. </Step> <Step title="Swap to Collateral"> Flash-borrowed funds are swapped into the target collateral asset (e.g., SOL → JitoSOL) using Kamino Swap (KSwap) with multi-DEX routing for optimal execution. </Step> <Step title="Deposit Collateral"> The full collateral amount (user deposit + swapped amount) is deposited into Kamino Lend as collateral. </Step> <Step title="Borrow Against Collateral"> With collateral deposited, the protocol borrows the debt token against the collateral position. </Step> <Step title="Repay Flash Loan"> Borrowed funds are used to repay the flash loan plus the 0.001% fee. </Step> <Step title="Position Established"> Net result: Leveraged position with amplified collateral exposure and outstanding debt balance recorded on Kamino Lend. </Step> </Steps> <Note> All steps execute in a single transaction. If any step fails (slippage exceeds tolerance, insufficient liquidity, etc.), the entire transaction reverts and no position is created. </Note> *** ## eMode (Elevation Mode) eMode enables significantly higher leverage for correlated asset pairs by raising the maximum permitted LTV ratio. ### How eMode Works Standard lending markets limit LTV to protect against price divergence between collateral and debt. When both assets are highly correlated (e.g., JitoSOL and SOL), price divergence risk is minimal — both assets move together. eMode reflects this reduced risk by permitting higher LTV ratios. ### eMode Leverage Comparison | Mode | Asset Pair | Max LTV | Max Leverage | Use Case | | - | - | - | - | - | | **Standard** | SOL / USDC | 75% | 4x | Uncorrelated assets | | **eMode (Main)** | mSOL, bSOL, JupSOL / SOL | \~87% | \~7.7x | Correlated LST/SOL pairs | | **eMode (Jito)** | JitoSOL / SOL | 90% | 10x | JitoSOL-specific correlation | | **No eMode** | JLP / USDC | 67% | \~3.2x | Uncorrelated (JLP is basket of assets) | <Warning> Higher LTV from eMode means a smaller buffer between your operating LTV and liquidation threshold. Operating near maximum eMode leverage requires continuous monitoring of the yield spread (collateral yield minus borrow rate). </Warning> ### Why Correlation Matters **Correlated pairs (LST/SOL)**: When SOL price moves, both JitoSOL and SOL debt move proportionally. Your LTV ratio stays relatively stable regardless of SOL's USD price. **Uncorrelated pairs (JLP/USDC)**: JLP value fluctuates with crypto markets while USDC stays flat. Price drops in SOL/ETH/BTC directly increase your LTV, creating liquidation risk independent of borrow rates. # Feeds Source: https://kamino.com/docs/build/developers/oracle/data/feeds Inspect a Scope feed's configuration, chain metadata, and oracle mappings ## Reading Feed Internals Beyond prices, the Scope SDK exposes the wiring behind a feed: its top-level `Configuration` account, the per-hop metadata for a scope chain (provider plus oracle type), and the raw per-slot oracle mappings. ### Feed Configuration A feed's `Configuration` holds the admin and the accounts it owns: `oraclePrices`, `oracleMappings`, `tokensMetadata`, and `oracleTwaps`. ```typescript icon="typescript" feedConfiguration theme={null} import { createSolanaRpc } from '@solana/kit'; import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const rpc = createSolanaRpc(RPC_ENDPOINT); const scope = new Scope('mainnet-beta', rpc); const [configAddress, c
프로젝트로 돌아가기