Kamino 백서

Kamino

원문

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

address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, compressTransactionMessageUsingAddressLookupTables, assertIsTransactionWithinSizeLimit, } from "@solana/kit"; import type { Address } from "@solana/kit"; import { Kamino, createComputeUnitLimitIx, getAssociatedTokenAddressAndAccount, } from "@kamino-finance/kliquidity-sdk"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { fetchAllAddressLookupTable } from "@solana-program/address-lookup-table"; import { getTransferSolInstruction } from "@solana-program/system"; import { getSyncNativeInstruction, getCloseAccountInstruction, } from "@solana-program/token"; import Decimal from "decimal.js"; ``` </Step> <Step> ### Configure Constants and Initialize Kamino Set the keypair path, RPC endpoints, target strategy, and per-side deposit amounts. 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("5EfeGn1h7m6Rx9mGEmamDoxMtdhRmUh2N9fYRiDQqteS"); const solAmount = new Decimal(0.05); const usdcAmount = new Decimal(1.0); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const kamino = new Kamino("mainnet-beta", rpc); ``` <Note> This example uses a SOL/USDC strategy where Token A is wSOL and Token B is USDC. Pick a strategy from the live list (`status=LIVE` on the Kamino API) that is currently in-range — the closer the pool price is to the middle of the band, the more of both inputs the deposit consumes. </Note> </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); } const strategyWithAddress = { strategy: strategyState.strategy, address: STRATEGY, }; ``` </Step> <Step> ### Resolve User Token Accounts Compute the user's associated token accounts for shares, Token A, and Token B. Build creation instructions for any that don't already exist. ```typescript theme={null} const [sharesAta, sharesMintData] = await getAssociatedTokenAddressAndAccount( rpc, strategyState.strategy.sharesMint, signer.address, ); const [tokenAAta, tokenAData] = await getAssociatedTokenAddressAndAccount( rpc, strategyState.strategy.tokenAMint, signer.address, ); const [tokenBAta, tokenBData] = await getAssociatedTokenAddressAndAccount( rpc, strategyState.strategy.tokenBMint, signer.address, ); const ataIxs = await kamino.getCreateAssociatedTokenAccountInstructionsIfNotExist( signer, strategyWithAddress, tokenAData, tokenAAta, tokenBData, tokenBAta, sharesMintData, sharesAta, ); ``` </Step> <Step> ### Wrap Native SOL Transfer lamports into the wSOL ATA, then `syncNative` so the SPL token program reflects the new balance. wSOL has 9 decimals. ```typescript theme={null} const solLamports = BigInt(solAmount.mul(1_000_000_000).ceil().toString()); const wrapIxs = [ getTransferSolInstruction({ source: signer, destination: tokenAAta, amount: solLamports, }), getSyncNativeInstruction({ account: tokenAAta }), ]; ``` <Note> The lamport amount is rounded up so the wrapped balance never under-funds the deposit by a lamport. Any surplus is recovered when the wSOL ATA is closed at the end of the transaction. </Note> </Step> <Step> ### Build Two-Sided Deposit Instructions Build the deposit instruction and the wSOL ATA close instruction, then assemble the final instruction list. ```typescript theme={null} const depositIx = await kamino.deposit( strategyWithAddress, solAmount, usdcAmount, signer, ); const closeWsolIx = getCloseAccountInstruction({ account: tokenAAta, destination: signer.address, owner: signer, }); const instructions = [ createComputeUnitLimitIx(1_400_000), ...ataIxs, ...wrapIxs, depositIx, closeWsolIx, ]; ``` <Note> Closing the wSOL ATA at the end recovers the rounding-up surplus and the ATA rent. </Note> </Step> <Step> ### Resolve Address Lookup Tables Collect every account referenced by the deposit instructions, fetch the minimal LUT set from the Kamino API, then load each LUT account. <Note> The strategy's own LUT is intentionally excluded — for this strategy it contains stale entries that cause `AccountOwnedByWrongProgram`. The minimal LUT set from Kamino's API is 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(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; } ``` </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 two-sided deposit successful! Signature:", signature, ); ``` <Check> The two-sided deposit is complete. Both SOL and USDC have been deposited at the strategy's current ratio, with any surplus on the unmatched side returned to your wallet. </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, createComputeUnitLimitIx, getAssociatedTokenAddressAndAccount, } from "@kamino-finance/kliquidity-sdk"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { fetchAllAddressLookupTable } from "@solana-program/address-lookup-table"; import { getTransferSolInstruction } from "@solana-program/system"; import { getSyncNativeInstruction, getCloseAccountInstruction, } from "@solana-program/token"; 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("5EfeGn1h7m6Rx9mGEmamDoxMtdhRmUh2N9fYRiDQqteS"); const solAmount = new Decimal(0.05); const usdcAmount = new Decimal(1.0); 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 strategyWithAddress = { strategy: strategyState.strategy, address: STRATEGY, }; const [sharesAta, sharesMintData] = await getAssociatedTokenAddressAndAccount( rpc, strategyState.strategy.sharesMint, signer.address, ); const [tokenAAta, tokenAData] = await getAssociatedTokenAddressAndAccount( rpc, strategyState.strategy.tokenAMint, signer.address, ); const [tokenBAta, tokenBData] = await getAssociatedTokenAddressAndAccount( rpc, strategyState.strategy.tokenBMint, signer.address, ); const ataIxs = await kamino.getCreateAssociatedTokenAccountInstructionsIfNotExist( signer, strategyWithAddress, tokenAData, tokenAAta, tokenBData, tokenBAta, sharesMintData, sharesAta, ); const solLamports = BigInt(solAmount.mul(1_000_000_000).ceil().toString()); const wrapIxs = [ getTransferSolInstruction({ source: signer, destination: tokenAAta, amount: solLamports, }), getSyncNativeInstruction({ account: tokenAAta }), ]; const depositIx = await kamino.deposit( strategyWithAddress, solAmount, usdcAmount, signer, ); const closeWsolIx = getCloseAccountInstruction({ account: tokenAAta, destination: signer.address, owner: signer, }); const instructions = [ createComputeUnitLimitIx(1_400_000), ...ataIxs, ...wrapIxs, depositIx, closeWsolIx, ]; 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 two-sided deposit successful! Signature:", signature, ); ``` # Withdraw Source: https://kamino.com/docs/build/developers/liquidity/operations/withdraw Withdraw all shares from a Kamino liquidity strategy ## Withdraw Redeem a position to receive a proportional share of the underlying assets, including accrued fees and rewards. <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, createComputeUnitLimitIx, getAssociatedTokenAddressAndAccount, } from "@kamino-finance/kliquidity-sdk"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { fetchAllAddressLookupTable } from "@solana-program/address-lookup-table"; ``` </Step> <Step> ### Configure Constants and Initialize Kamino Set the keypair path, RPC endpoints, and target strategy. 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 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 strategy account so the SDK has the current state and token mints. ```typescript theme={null} const strategy = await kamino.getStrategyByAddress(STRATEGY); if (!strategy) { console.log("Strategy not found:", STRATEGY); process.exit(1); } const strategyWithAddress = { strategy, address: STRATEGY }; ``` </Step> <Step> ### Resolve User Token Accounts Compute the user's associated token accounts for shares, Token A, and Token B. Build creation instructions for any that don't already exist. ```typescript theme={null} 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, ); ``` </Step> <Step> ### Build Withdraw All Shares Instructions Call `withdrawAllShares` to build the withdraw bundle, then compose the full instruction list with a compute unit limit, ATA creations, prerequisites, the withdraw, and the optional shares ATA close. ```typescript theme={null} 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] : []), ]; ``` </Step> <Step> ### Resolve Address Lookup Tables Collect every account referenced by the withdraw instructions, fetch the minimal LUT set from the Kamino API, then load each LUT account. <Note> The strategy's own LUT is intentionally excluded — for this strategy it contains stale entries that cause `AccountOwnedByWrongProgram`. The minimal LUT set from Kamino's API is 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(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; } ``` </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 withdraw-all successful! Signature:", signature); ``` <Check> The withdrawal is complete. Token A and Token B have been transferred to your ATAs. </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, createComputeUnitLimitIx, getAssociatedTokenAddressAndAccount, } from "@kamino-finance/kliquidity-sdk"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { fetchAllAddressLookupTable } from "@solana-program/address-lookup-table"; 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 signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const kamino = new Kamino("mainnet-beta", rpc); const strategy = await kamino.getStrategyByAddress(STRATEGY); if (!strategy)
프로젝트로 돌아가기