Kamino 백서

Kamino

원문

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

h(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log({ totalTvl: data }); ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> ### Get Strategy Fees and Rewards Returns fees and rewards earned across all strategies over a chosen time period (`24h`, `7d`, or `30d`). ```typescript icon="typescript" getStrategyFeesAndRewards theme={null} const url = 'https://api.kamino.finance/strategies/fees-and-rewards?env=mainnet-beta&period=24h'; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log(data); ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> ## Strategy Types TypeScript shapes used by the Kliquidity SDK for strategy reads — both arguments (e.g. `StrategiesFilters`) and return values. <Tabs> <Tab title="StrategyWithAddress"> On-chain strategy account paired with its address. ```typescript theme={null} type StrategyWithAddress = { address: Address; strategy: WhirlpoolStrategy; }; ``` </Tab> <Tab title="StrategyBalances"> Raw token amounts and computed position values. ```typescript theme={null} type StrategyBalances = { computedHoldings: Holdings; prices: PriceData; tokenAAmounts: Decimal; tokenBAmounts: Decimal; }; ``` </Tab> <Tab title="PriceData"> Pool price, range bounds, and rebalance triggers. ```typescript theme={null} type PriceData = { aPrice: Decimal | null; bPrice: Decimal | null; poolPrice: Decimal; lowerPrice: Decimal; upperPrice: Decimal; }; ``` </Tab> <Tab title="StrategyPrices"> Oracle and TWAP prices for strategy tokens and rewards. ```typescript theme={null} type StrategyPrices = { /* ... */ }; ``` </Tab> <Tab title="StrategiesFilters"> Query parameters for filtering strategies by type, status, and ownership. ```typescript theme={null} type StrategiesFilters = { /* ... */ }; ``` </Tab> </Tabs> ## Additional Resources <CardGroup> <Card title="API Examples" icon="book" href="https://api-docs.kamino.com/" /> <Card title="SDK Examples" icon="github" href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples" /> </CardGroup> # User Position Source: https://kamino.com/docs/build/developers/liquidity/data/user-position ## Reading User Position Data Retrieve user holdings, profit and loss, fees and rewards, and transaction history using the Kamino API. <Note> Historical user data is only available via the API. For the TypeScript shapes returned by the methods below, see [Position Types](#position-types). </Note> ### Get User Positions Live read of a wallet's positions with USD value calculated from each strategy's share price. ```typescript icon="typescript" getUserPositions theme={null} import { createSolanaRpc, address } from '@solana/kit'; import { Kamino } from '@kamino-finance/kliquidity-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const WALLET = address('YOUR_WALLET_ADDRESS'); // user address const rpc = createSolanaRpc(RPC_ENDPOINT); const kamino = new Kamino('mainnet-beta', rpc); const positions = await kamino.getUserPositions(WALLET); console.log(`Wallet: ${WALLET}`); console.log(`Positions: ${positions.length}`); for (const p of positions) { const shareData = await kamino.getStrategyShareData(p.strategy); const usdValue = p.sharesAmount.mul(shareData.price); console.log({ strategy: p.strategy.toString(), dex: p.strategyDex, shareMint: p.shareMint.toString(), sharesAmount: p.sharesAmount.toString(), sharePriceUsd: shareData.price.toString(), valueUsd: usdValue.toString(), }); } ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> ### Get User PnL Returns current profit and loss data for a user's position in a specific strategy. Returns USD, SOL, and token denominations. ```typescript icon="typescript" getUserPnl theme={null} const strategyPubkey = '2H4xebnp2M9JYgPPfUw58uUQahWF8f1YTNxwwtmdqVYV'; // strategy address const walletPubkey = 'YOUR_WALLET_ADDRESS'; // user address const url = `https://api.kamino.finance/v2/strategies/${strategyPubkey}/shareholders/${walletPubkey}/pnl?env=mainnet-beta`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log({ totalPnlUsd: data.totalPnl?.usd, totalPnlSol: data.totalPnl?.sol, totalPnlToken: data.totalPnl?.token, totalCostBasisUsd: data.totalCostBasis?.usd, }); ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> ### Get User PnL History Returns time-series PnL snapshots for charting a user's position over time. ```typescript icon="typescript" getUserPnlHistory theme={null} const strategyPubkey = '2H4xebnp2M9JYgPPfUw58uUQahWF8f1YTNxwwtmdqVYV'; // strategy address const walletPubkey = 'YOUR_WALLET_ADDRESS'; // user address const url = `https://api.kamino.finance/v2/strategies/${strategyPubkey}/shareholders/${walletPubkey}/pnl/history?env=mainnet-beta`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); for (const item of data.history) { console.log({ timestamp: item.timestamp, pnlUsd: item.pnl?.usd, positionValueUsd: item.positionValue?.usd, }); } ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> ### Get User Fees and Rewards Returns cumulative fees and rewards earned by the user in a specific strategy. ```typescript icon="typescript" getUserFeesAndRewards theme={null} const strategyPubkey = '2H4xebnp2M9JYgPPfUw58uUQahWF8f1YTNxwwtmdqVYV'; // strategy address const walletPubkey = 'YOUR_WALLET_ADDRESS'; // user address const url = `https://api.kamino.finance/strategies/${strategyPubkey}/shareholders/${walletPubkey}/fees-and-rewards?env=mainnet-beta`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log(data); ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> ### Get User Rewards History Returns historical rewards earned by a wallet across all strategies. ```typescript icon="typescript" getUserRewardsHistory theme={null} const walletPubkey = 'YOUR_WALLET_ADDRESS'; // user address const url = `https://api.kamino.finance/strategies/shareholders/${walletPubkey}/rewards/history?env=mainnet-beta`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log(data); ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> ### Get User Transactions Deposit, withdrawal, and claim transaction history for a wallet across all strategies. ```typescript icon="typescript" getUserTransactions theme={null} const walletPubkey = 'YOUR_WALLET_ADDRESS'; // user address const url = `https://api.kamino.finance/v2/shareholders/${walletPubkey}/transactions?env=mainnet-beta`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); for (const tx of data.transactions) { console.log({ timestamp: tx.timestamp, type: tx.type, strategy: tx.strategy, amountUsd: tx.amountUsd, }); } ``` <a href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples"> <Icon icon="github" /> <span>View Code</span> </a> ## Position Types TypeScript shapes returned by the Kliquidity SDK for user position reads. <Tabs> <Tab title="KaminoPosition"> A user's share holdings in a specific strategy. ```typescript theme={null} interface KaminoPosition { strategy: Address; shareMint: Address; sharesAmount: Decimal; strategyDex: Dex; } ``` </Tab> <Tab title="Holdings"> Available and invested token values with USD valuations. ```typescript theme={null} type Holdings = { available: TokenAmounts; availableUsd: Decimal; invested: TokenAmounts; investedUsd: Decimal; totalSum: Decimal; }; ``` </Tab> <Tab title="TokenAmounts"> Pair of token quantities (A and B amounts). ```typescript theme={null} type TokenAmounts = { a: Decimal; b: Decimal; }; ``` </Tab> <Tab title="ShareData"> Current share price with strategy balances. ```typescript theme={null} type ShareData = { price: Decimal; balance: StrategyBalances; }; ``` </Tab> <Tab title="StrategyHolder"> A wallet and its share count in a strategy. ```typescript theme={null} type StrategyHolder = { holderPubkey: Address; amount: Decimal; }; ``` </Tab> <Tab title="WithdrawShares"> Bundle of instructions for executing share withdrawals. `closeSharesAtaIx` is optional — it's only returned when the withdrawal closes the entire position and the shares ATA can be cleaned up. ```typescript theme={null} type WithdrawShares = { prerequisiteIxs: TransactionInstruction[]; withdrawIx: TransactionInstruction; closeSharesAtaIx?: TransactionInstruction; }; ``` </Tab> </Tabs> ## Additional Resources <CardGroup> <Card title="API Examples" icon="book" href="https://api-docs.kamino.com/" /> <Card title="SDK Examples" icon="github" href="https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples" /> </CardGroup> # Deposit Source: https://kamino.com/docs/build/developers/liquidity/operations/deposit Deposit into a Kamino liquidity strategy ## Single-Sided Deposit Deposit a single token. The SDK swaps half of the input into the other side and handles the wSOL ATA wrap/close internally, so the caller only provides the input amount and slippage tolerance. <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, address lookup table fetching, and Kit transaction building. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, compressTransactionMessageUsingAddressLookupTables, assertIsTransactionWithinSizeLimit, } from "@solana/kit"; import type { Address } from "@solana/kit"; import { Kamino } from "@kamino-finance/kliquidity-sdk"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { fetchAllAddressLookupTable } from "@solana-program/address-lookup-table"; import Decimal from "decimal.js"; ``` </Step> <Step> ### Configure Constants and Initialize Kamino Set the keypair path, RPC endpoints, target strategy, deposit amount, and slippage. Load the signer and initialize the Kamino client. ```typescript theme={null} const KEYPAIR_FILE = "/path/to/your/keypair.json"; const RPC_ENDPOINT = "https://api.mainnet-beta.solana.com"; const WS_ENDPOINT = "wss://api.mainnet-beta.solana.com"; const STRATEGY = address("CEz5keL9hBCUbtVbmcwenthRMwmZLupxJ6YtYAgzp4ex"); // strategy address const usdcAmount = new Decimal(2.0); const slippageBps = new Decimal(100); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const kamino = new Kamino("mainnet-beta", rpc); ``` </Step> <Step> ### Load Strategy State Fetch the on-chain strategy account so the SDK has current state to build instructions against. ```typescript theme={null} const strategyState = (await kamino.getStrategiesWithAddresses([STRATEGY]))[0]; if (!strategyState) { console.log("Strategy not found:", STRATEGY); process.exit(1); } ``` </Step> <Step> ### Build Single-Sided Deposit Instructions Call `singleSidedDepositTokenB` to deposit USDC only. The SDK swaps half the input into SOL using its built-in swap router and handles the wSOL ATA wrap/close internally. ```typescript theme={null} const { instructions, lookupTablesAddresses } = await kamino.singleSidedDepositTokenB( { address: STRATEGY, strategy: strategyState.strategy }, usdcAmount, signer, slippageBps, ); ``` </Step> <Step> ### Resolve Address Lookup Tables Collect every account referenced by the deposit instructions, fetch the minimal LUT set from the Kamino API, dedupe with the swap-router LUTs returned by the SDK, then load each LUT account. <Note> The strategy's own LUT is intentionally excluded — for this strategy it contains stale entries that resolve into the deposit instruction's `token_infos` slot. The swap-router LUTs from the SDK plus the minimal LUT set from Kamino's API are sufficient. </Note> ```typescript theme={null} 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( [ ...lookupTablesAddresses, ...minimalLutAddresses.map((a) => address(a)), ].map((a) => a.toString()), ), ).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; } ``` </Step> <Step> ### Build, Sign, and Send Transaction Compose the v0 transaction with LUT compression, sign, verify it fits the size limit, then send and confirm. ```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(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 single-sided USDC deposit successful! Signature:", signature, ); ``` <Check> The deposit is complete. Your USDC has been swapped and deposited into the strategy. </Check> </Step> </Steps> #### Full Code Example ```typescript expandable theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, compressTransactionMessageUsingAddressLookupTables, assertIsTransactionWithinSizeLimit, } from "@solana/kit"; import type { Address } from "@solana/kit"; import { Kamino } from "@kamino-finance/kliquidity-sdk"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { fetchAllAddressLookupTable } from "@solana-program/address-lookup-table"; import Decimal from "decimal.js"; const KEYPAIR_FILE = "/path/to/your/keypair.json"; const RPC_ENDPOINT = "https://api.mainnet-beta.solana.com"; const WS_ENDPOINT = "wss://api.mainnet-beta.solana.com"; const STRATEGY = address("CEz5keL9hBCUbtVbmcwenthRMwmZLupxJ6YtYAgzp4ex"); const usdcAmount = new Decimal(2.0); const slippageBps = new Decimal(100); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const kamino = new Kamino("mainnet-beta", rpc); const strategyState = (await kamino.getStrategiesWithAddresses([STRATEGY]))[0]; if (!strategyState) { console.log("Strategy not found:", STRATEGY); process.exit(1); } const { instructions, lookupTablesAddresses } = await kamino.singleSidedDepositTokenB( { address: STRATEGY, strategy: strategyState.strategy }, usdcAmount, signer, slippageBps, ); 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( [ ...lookupTablesAddresses, ...minimalLutAddresses.map((a) => address(a)), ].map((a) => a.toString()), ), ).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 single-sided USDC deposit successful! Signature:", signature, ); ``` ## Two-Sided Deposit Provide both Token A and Token B amounts directly. `kamino.deposit()` consumes whichever side hits the strategy's current ratio first; any surplus on the unmatched side stays in the user's ATA after the deposit runs. <Note> `kamino.deposit()` returns a single instruction with no auto-swap and no native-SOL handling. The caller is responsible for ATA setup and wrapping SOL into wSOL before the deposit runs. </Note> <Steps> <Step> ### Import Dependencies Import the standard Kamino + Kit packages, plus the system and token program helpers needed to wrap native SOL and close the wSOL ATA. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions,
프로젝트로 돌아가기