Kamino 백서

Kamino

원문

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

{ console.log("Strategy not found:", STRATEGY); process.exit(1); } const strategyWithAddress = { strategy, address: STRATEGY }; const [sharesAta, sharesMintData] = await getAssociatedTokenAddressAndAccount( rpc, strategy.sharesMint, signer.address, ); const [tokenAAta, tokenAData] = await getAssociatedTokenAddressAndAccount( rpc, strategy.tokenAMint, signer.address, ); const [tokenBAta, tokenBData] = await getAssociatedTokenAddressAndAccount( rpc, strategy.tokenBMint, signer.address, ); const ataIxs = await kamino.getCreateAssociatedTokenAccountInstructionsIfNotExist( signer, strategyWithAddress, tokenAData, tokenAAta, tokenBData, tokenBAta, sharesMintData, sharesAta, ); const bundle = await kamino.withdrawAllShares(strategyWithAddress, signer); if (!bundle) { console.log("No shares to withdraw"); process.exit(0); } const instructions = [ createComputeUnitLimitIx(1_400_000), ...ataIxs, ...bundle.prerequisiteIxs, bundle.withdrawIx, ...(bundle.closeSharesAtaIx ? [bundle.closeSharesAtaIx] : []), ]; const allAddresses = new Set<string>(); for (const ix of instructions) { allAddresses.add(ix.programAddress.toString()); for (const acc of ix.accounts ?? []) allAddresses.add(acc.address.toString()); } const lutResp = await fetch("https://api.kamino.finance/luts/find-minimal", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ addresses: Array.from(allAddresses) }), }); if (!lutResp.ok) { console.log( "luts/find-minimal failed:", lutResp.status, await lutResp.text(), ); process.exit(1); } const { lutAddresses: minimalLutAddresses } = (await lutResp.json()) as { lutAddresses: string[]; }; const dedupedLutAddresses = Array.from(new Set(minimalLutAddresses)).map((a) => address(a), ); const lutAccounts = await fetchAllAddressLookupTable(rpc, dedupedLutAddresses); const lutsByAddress: Record<Address, Address[]> = {}; for (const acc of lutAccounts) { lutsByAddress[acc.address] = acc.data.addresses; } 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(instructions, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lutsByAddress), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })( signedTransaction, { commitment: "confirmed", skipPreflight: true, }, ); console.log("Strategy withdraw-all successful! Signature:", signature); ``` # Liquidity Source: https://kamino.com/docs/build/developers/liquidity/overview Learn how to build with Kamino's automated concentrated liquidity vaults <div> ## Overview Kamino Liquidity provides access to automated concentrated liquidity strategies on Solana via a TypeScript SDK and public API. A strategy manages a CLMM position for a token pair within a defined price range, handling rebalancing, fee compounding, and reward collection. Depositors receive [kTokens](/docs/products/liquidity/concepts#ktokens), which represent a proportional share of the strategy and are redeemable for the underlying assets based on the current share price. <Note> Providing liquidity carries impermanent loss risk — see [Liquidity Concepts](/docs/products/liquidity/concepts) for the full explanation before integrating. </Note> ## Key Components of Liquidity Integration <CardGroup> <Card title="Strategy Operations" icon="right-left"> Two-sided and single-sided deposits, partial and full withdrawals, with ATA management and lookup-table resolution handled by the SDK. </Card> <Card title="Position Tracking" icon="user"> User share holdings, USD valuation, pending fees and rewards, PnL, and transaction history. </Card> <Card title="Strategy Analytics" icon="chart-mixed"> Share price, TVL, APR/APY, price range, and historical metrics for charts and dashboards. </Card> </CardGroup> ## Integration Options <CardGroup> <Card title="Public API" icon="globe"> Read-only access to strategy metrics, historical performance, user PnL, fees and rewards, and transaction history. Language-agnostic REST endpoints. </Card> <Card title="TypeScript SDK" icon="code"> On-chain reads and transaction building for deposits, withdrawals, and position tracking. TS/JS only. </Card> </CardGroup> ### Deposit <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { Kamino } from '@kamino-finance/kliquidity-sdk'; import Decimal from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const kamino = new Kamino('mainnet-beta', rpc); const STRATEGY = address('CEz5keL9hBCUbtVbmcwenthRMwmZLupxJ6YtYAgzp4ex'); const strategyState = (await kamino.getStrategiesWithAddresses([STRATEGY]))[0]; // Single-sided deposit: 2 USDC with 100 bps slippage. The SDK swaps half // the input into the other side via Jupiter v6 before depositing. const { instructions, lookupTablesAddresses } = await kamino.singleSidedDepositTokenB( { address: STRATEGY, strategy: strategyState.strategy }, new Decimal(2.0), signer, // TransactionSigner new Decimal(100), ); console.log('Deposit Instructions:', instructions); ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> <Note> For the full deposit flow including lookup-table resolution and transaction confirmation, see [Deposit Operations](/docs/build/developers/liquidity/operations/deposit). </Note> ### Withdraw <Tabs> <Tab title="TypeScript"> ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { Kamino } from '@kamino-finance/kliquidity-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const kamino = new Kamino('mainnet-beta', rpc); const STRATEGY = address('CEz5keL9hBCUbtVbmcwenthRMwmZLupxJ6YtYAgzp4ex'); const strategy = await kamino.getStrategyByAddress(STRATEGY); const strategyWithAddress = { strategy, address: STRATEGY }; // Burn all shares and receive Token A + Token B back to the user's ATAs. const bundle = await kamino.withdrawAllShares( strategyWithAddress, signer, // TransactionSigner ); console.log('Withdraw Instructions:', bundle?.withdrawIx); ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> </Tab> </Tabs> <Note> For the full withdraw flow including ATA setup, lookup-table resolution, and transaction confirmation, see [Withdraw Operations](/docs/build/developers/liquidity/operations/withdraw). </Note> ## What's Covered <CardGroup> <Card title="Strategy Data" icon="chart-line" href="/docs/build/developers/liquidity/data/strategy"> List strategies, read share price, TVL, APR/APY, price range, and token balances. </Card> <Card title="User Position Data" icon="user" href="/docs/build/developers/liquidity/data/user-position"> Fetch user positions, USD valuation, pending fees and rewards, and PnL. </Card> <Card title="Deposit" icon="arrow-down-to-line" href="/docs/build/developers/liquidity/operations/deposit"> Two-sided deposits and single-sided deposits via auto-swap. </Card> <Card title="Withdraw" icon="arrow-up-from-line" href="/docs/build/developers/liquidity/operations/withdraw"> Withdraw a specific share amount or close the full position. </Card> </CardGroup> ## Relevant Links <CardGroup> <Card title="Fetch Data via the API" icon="globe" href="https://api-docs.kamino.com/"> Access strategy metrics and performance data through REST endpoints. </Card> <Card title="Kliquidity SDK repository" icon="github" href="https://github.com/Kamino-Finance/kliquidity-sdk"> Explore the SDK source, on-chain program docs, and example scripts. </Card> <Card title="NPM SDK package" icon="npm" href="https://www.npmjs.com/package/@kamino-finance/kliquidity-sdk"> Install the TypeScript SDK to integrate liquidity operations. </Card> <Card title="Liquidity Concepts" icon="book-open" href="/docs/products/liquidity/concepts"> AMMs, concentrated liquidity, impermanent loss, and kTokens explained. </Card> </CardGroup> </div> # Monitor Position Health Source: https://kamino.com/docs/build/developers/multiply/data/health-metrics Monitor LTV, leverage, and liquidation risk of multiply positions When a Multiply position is opened, Kamino's on-chain program immediately begins tracking and updating position health metrics. These metrics update with every transaction that affects the position and recalculate based on current collateral prices and debt accrual. The protocol stores six core metrics that describe position size, leverage level, borrowing capacity, and liquidation risk. ### Position Health Metrics | Metric | Description | | - | - | | **Total Deposit** | The total USD value of all collateral deposited into the position | | **Total Borrow** | The total USD value of debt owed on the position | | **Net Value** | Equity in the position. Calculated as Total Deposit - Total Borrow. Represents the value that would be received if all debt were repaid and collateral withdrawn | | **Leverage** | Capital amplification multiplier. 1x = no leverage (collateral only), 2x = borrowed amount equals deposit, 3x = borrowed twice the deposit amount | | **Borrow Limit** | Maximum borrowing capacity before approaching liquidation threshold. Total Borrow must remain below this value | | **Liquidation LTV** | The loan-to-value percentage at which the position becomes eligible for liquidation. Varies by asset pair and eMode settings | Leverage amplifies both gains and losses. When Current LTV approaches Liquidation LTV, the position risks partial liquidation. When borrow rates exceed collateral yield, Net APY turns negative and debt grows faster than earnings. Regular monitoring enables integrations to alert users when conditions warrant position adjustment—whether through debt repayment, leverage reduction, or position closure. *** ## Get Position Health Metrics <Tabs> <Tab title="SDK"> <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication and Kamino SDK operations. ```typescript theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, parseKeypairFile, ObligationTypeTag, DEFAULT_RECENT_SLOT_DURATION_MS } from '@kamino-finance/klend-sdk'; ``` </Step> <Step> ### Load Market and Initialize RPC Load the keypair, initialize RPC connection, and load 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 marketPubkey = address('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const market = await KaminoMarket.load(rpc, marketPubkey, DEFAULT_RECENT_SLOT_DURATION_MS); ``` </Step> <Step> ### Fetch Multiply Obligations Retrieve all multiply obligations for the wallet address using the obligation type filter. ```typescript theme={null} const obligations = await market!.getUserObligationsByTag( ObligationTypeTag.Multiply, address(signer.address) ); if (obligations.length === 0) { console.log('No multiply obligations found.'); } ``` <Note> `getUserObligationsByTag` filters obligations by type. For example, use `ObligationTypeTag.Multiply` to retrieve only multiply positions. </Note> <br /> <div> **ObligationTypeTag Values:** | Type | Value & Description | | - | - | | `ObligationTypeTag.Vanilla` | 0: Cross-collateral mode positions | | `ObligationTypeTag.Multiply` | 1: Leveraged positions created via Multiply | | `ObligationTypeTag.Lending` | 2: Lending-only positions | | `ObligationTypeTag.Leverage` | 3: Legacy leverage positions | </div> </Step> <Step> ### Read Position Health Metrics Access the position health statistics from each obligation's `refreshedStats`. ```typescript theme={null} obligations.forEach((obligation) => { console.log(`\nObligation Address: ${obligation.obligationAddress}`); console.log(`Stats:`); console.log(` Total Deposit: $${obligation.refreshedStats.userTotalDeposit.toFixed(2)}`); console.log(` Total Borrow: $${obligation.refreshedStats.userTotalBorrow.toFixed(2)}`); console.log(` Net Value: $${obligation.refreshedStats.userTotalDeposit.minus(obligation.refreshedStats.userTotalBorrow).toFixed(2)}`); console.log(` Leverage: ${obligation.refreshedStats.leverage.toFixed(2)}x`); console.log(` Borrow Limit: $${obligation.refreshedStats.borrowLimit.toFixed(2)}`); console.log(` Liquidation LTV: ${obligation.refreshedStats.liquidationLtv.toFixed(2)}%`); }); ``` <Check> You now have access to all position health metrics including leverage, borrowing capacity, and liquidation thresholds. </Check> </Step> </Steps> </Tab> <Tab title="API"> ```typescript theme={null} const walletAddress = 'your-wallet-address-here'; const marketAddress = '5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'; // xStocks Market const response = await fetch( `https://api.kamino.finance/kamino-market/${marketAddress}/users/${walletAddress}/obligations` ); const data = await response.json(); if (data.length === 0) { console.log('No obligations found.'); } data.forEach((obligation) => { console.log(`\nObligation Address: ${obligation.obligationAddress}`); console.log(`Type: ${obligation.humanTag}`); const stats = obligation.refreshedStats; console.log(`Stats:`); console.log(` Total Deposit: $${parseFloat(stats.userTotalDeposit).toFixed(2)}`); console.log(` Total Borrow: $${parseFloat(stats.userTotalBorrow).toFixed(2)}`); console.log(` Net Value: $${(parseFloat(stats.userTotalDeposit) - parseFloat(stats.userTotalBorrow)).toFixed(2)}`); console.log(` Leverage: ${parseFloat(stats.leverage).toFixed(2)}x`); console.log(` Borrow Limit: $${parseFloat(stats.borrowLimit).toFixed(2)}`); console.log(` Liquidation LTV: ${(parseFloat(stats.liquidationLtv) * 100).toFixed(2)}%`); }); ``` </Tab> </Tabs> *** ## Liquidation LTV by Asset Pair | Mode | Asset Pair | Liquidation LTV | Max Leverage | | - | - | - | - | | **Standard** | SOL / USDC | 75% | 4x | | **Standard** | TSLAx / USDC | 65% | \~2.9x | | **eMode (Main)** | mSOL, bSOL, JupSOL / SOL | \~87% | \~7.7x | | **eMode (Jito)** | JitoSOL / SOL | 90% | 10x | | **No eMode** | JLP / USDC | 67% | \~3.2x | <Note> For detailed leverage calculations and eMode mechanics, see [LTV and Leverage Concepts](/docs/build/developers/multiply/data/concepts). </Note> # Flash Loans Source: https://kamino.com/docs/build/developers/multiply/flash-loans Execute flash loans for atomic, uncollateralized borrowing within a single transaction ## Flash Loans <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, none, getProgramDerivedAddress, getAddressEncoder, } from '@solana/kit'; import { KaminoMarket, PROGRAM_ID, getFlashLoanInstructions } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { getAddMemoInstruction } from '@solana-program/memo'; import Decimal from 'decimal.js'; ``` </Step> <Step> ### Setup Market and Signer Load your keypair, initialize RPC connections, and load 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'); // SOL/BTC Market const market = await KaminoMarket.load(rpc, marketPubkey, 400); ``` </Step> <Step> ### Configure Flash Loan Parameters Set the token mint, flash loan amount, and derive the user's token account address. ```typescript theme={null} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const usdcReserve = market!.getReserveByMint(usdcMint)!; // Flash loan amount: 1 USDC const flashLoanAmount = new Decimal(1_000_000); // Derive user's USDC token account (ATA) const ASSOCIATED_TOKEN_PROGRAM = address('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'); const TOKEN_PROGRAM = usdcReserve.getLiquidityTokenProgram(); const addressEncoder = getAddressEncoder(); const [usdcAta] = await getProgramDerivedAddress({ programAddress: ASSOCIATED_TOKEN_PROGRAM, seeds: [ addressEncoder.encode(signer.address), addressEncoder.encode(TOKEN_PROGRAM), addressEncoder.encode(usdcMint) ], }); ``` </Step> <Step> ### Build Flash Loan Instructions Generate the flash borrow and flash repay instructions using the Kamino SDK. ```typescript theme={null} // Build flash loan instructions const lendingMarketAuthority = await market!.getLendingMarketAuthority(); const { flashBorrowIx, flashRepayIx } = getFlashLoanInstructions({ borrowIxIndex: 0, userTransferAuthority: signer, lendingMarketAuthority, lendingMarketAddress: market!.getAddress(), reserve: usdcReserve, amountLamports: flashLoanAmount, destinationAta: usdcAta, referrerAccount: none(), referrerTokenState: none(), programId: PROGRAM_ID, }); ``` <Info> The `borrowIxIndex:0 ` parameter specifies that the flash borrow instruction is at index 0 in the transaction. The SDK uses this to validate that repayment occurs in the same transaction. </Info> </Step> <Step> ### Add Your Custom Instructions Create your custom instructions to execute with the borrowed funds. In this example, we use a simple memo instruction. ```typescript theme={null} // Create memo instruction const memoIx = getAddMemoInstruction({ memo: 'Hello Kamino' }); // Arrange instructions: flash borrow → your instructions → flash repay const allInstructions = [flashBorrowIx, memoIx, flashRepayIx]; ``` <Note> Replace the memo instruction with your actual business logic. </Note> </Step> <Step> ### Build and Send Transaction Build the transaction with a fresh blockhash and send it to the network. ```typescript theme={null} // Get fresh blockhash const { value: latestBlockhash } = await rpc .getLatestBlockhash({ commitment: 'finalized' }) .send(); // Build transaction const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => appendTransactionMessageInstructions(allInstructions, tx), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })( signedTransaction, { commitment: 'confirmed', skipPreflight: false, } ); console.log(`Flash loan successful! Signature: ${signature}`); ``` <Check> Your f
프로젝트로 돌아가기