Kamino 백서

Kamino

원문

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

peed: * **`processed`**: Fastest, used for sending (no false timeout errors) * **`confirmed`**: Medium speed, confirmed by majority of cluster stake * **`finalized`**: Slowest, used for blockhash (maximum security, \~32 blocks) * **Recommended**: Use `processed` for multiply transactions to avoid false errors </Accordion> </AccordionGroup> ### 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> ## Related Resources <CardGroup> <Card title="Deposit and Borrow" icon="coins" href="/docs/build/tutorials/borrow/deposit-and-borrow"> Learn basic deposit and borrow operations </Card> <Card title="Market Data" icon="chart-line" href="/docs/build/developers/borrow/data/market-data"> Read market metrics and reserve data </Card> <Card title="KSwap SDK" icon="code" href="https://www.npmjs.com/package/@kamino-finance/kswap-sdk"> Multi-DEX swap routing SDK </Card> <Card title="Scope SDK" icon="globe" href="https://github.com/Kamino-Finance/scope-sdk"> Oracle price aggregation SDK </Card> </CardGroup> # Multiply Repay with xStocks Source: https://kamino.com/docs/build/borrow/multiply/multiply-repay-xstocks Repay debt on multiply positions with tokenized stocks to reduce leverage <p>Repaying debt on a multiply position reduces your outstanding debt balance, lowers your LTV (Loan-to-Value) ratio, and improves position health. This example shows how to repay USDC debt on a TSLAx multiply position using the Klend SDK.</p> ## Multiply Repay with xStocks Repay debt on a TSLAx multiply position to reduce leverage and improve position health. <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 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/borrow/multiply/multiply-withdraw-xstocks Withdraw collateral from multiply positions with tokenized stocks <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> # Repay with Collateral Source: https://kamino.com/docs/build/borrow/multiply/repay-collateral-kswap Swap collateral to repay borrowed assets in a single transaction <p>Repay with collateral reduces debt in a single atomic transaction by converting collateral into the debt token without requiring additional funds. The protocol flash borrows the debt token, repays the debt, withdraws the freed collateral, swaps it to the debt token via KSwap, and repays the flash loan—all in one transaction.</p> ## Repay with Collateral using KSwap Reduce debt in a single transaction by converting collateral using a flash loan and KSwap. <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, getRepayWithCollIxs, getUserLutAddressAndSetupIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, lamportsToNumberDecimal, 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, initialize RPC connections, and set up the market and SDKs. ```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'); 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); ``` </Step> <Step> ### Find Collateral Reserve Dynamically discover the collateral 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(); ``` </Step> <Step> ### Fetch Multiply Lookup Tables Retrieve the multiply-specific lookup tables from Kamino's CDN. ```typescript theme={null} const kaminoResourcesResponse = await fetch(`${CDN_ENDPOINT}/resources.json`); const kaminoResourcesData = await kaminoResourcesResponse.json(); const kaminoResources = kaminoResourcesData['mainnet-beta']; const multiplyColPairs = kaminoResources.multiplyLUTsPairs[collTokenMint] || {}; const multiplyLut = multiplyColPairs[debtTokenMint] || []; const multiplyLutKeys = multiplyLut.map((lut: string) => address(lut)); ``` </Step> <Step> ### Configure Repay Parameters Set the amount of debt to repay using collateral and the slippage tolerance. ```typescript theme={null} const repayAmount = new Decimal(5); // $5 worth of debt to repay using collateral const slippageBps = 100; // 1% slippage ``` <Note> Some assets may require higher slippage than others. </Note> </Step> <Step> ### Setup Lookup Tables Initialize the user's lookup table and execute any required setup transactions. ```typescript theme={null} const multiplyMints: { coll: Address; debt: Address }[] = [{ coll: collTokenMint, debt: debtTokenMint }]; const leverageMints: { coll: Address; debt: Address }[] = []; const [userLookupTable, setupTxsIxs] = await getUserLutAddressAndSetupIxs( market!, signer, none(), true, multiplyMints, leverageMints ); for (const setupIxs of setupTxsIxs) { 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(setupIxs, tx) ); const signedSetupTx = await signTransactionMessageWithSigners(setupTx); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedSetupTx, { commitment: 'confirmed', skipPreflight: true, }); await new Promise((resolve) => setTimeout(resolve, 2000)); } ``` <Note> Setup transactions extend the lookup table with addresses specific to the position. This is a one-time operation per collateral/debt pair. </Note> </Step> <Step> ### F
프로젝트로 돌아가기