Kamino 백서

Kamino

원문

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

OINT = 'https://api.mainnet-beta.solana.com'; const WS_ENDPOINT = 'wss://api.mainnet-beta.solana.com'; const MAIN_MARKET = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; const SOL_RESERVE = 'd4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q'; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); ``` </Step> <Step> ### Call the Kamino API Make a POST request to the Kamino API to build the repay transaction. ```typescript theme={null} const res = await fetch(`${API_BASE_URL}/ktx/klend/repay`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ wallet: signer.address, market: MAIN_MARKET, reserve: SOL_RESERVE, amount: '0.02', }), }); const data = await res.json(); if (!res.ok) { console.error('Response error:', data); } const encodedTransaction = data.transaction; ``` <Info> The API returns a pre-built transaction encoded in base64 format ready for signing. </Info> </Step> <Step> ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={null} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` </Step> <Step> ### Resolve Address Lookup Tables and Sign Fetch the latest blockhash, decompile the transaction to resolve Address Lookup Tables, and sign. ```typescript theme={null} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const signedTransaction = await pipe( await decompileTransactionMessageFetchingLookupTables(compiledMessage, rpc), tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), tx => setTransactionMessageFeePayerSigner(signer, tx), tx => addSignersToTransactionMessage([signer], tx), tx => signTransactionMessageWithSigners(tx) ); const signature = getSignatureFromTransaction(signedTransaction); ``` <Info> `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. </Info> </Step> <Step> ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={null} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions, }); await sendAndConfirm(signedTransaction, { commitment: 'confirmed', skipPreflight: false, }); console.log('Repay successful! Signature:', signature); ``` <Check> Your repayment is complete! The API built the transaction, you signed it locally (keeping your keys secure), and it was successfully submitted to the network. </Check> </Step> </Steps> # Withdraw via the API Source: https://kamino.com/docs/build/recipes/borrow/withdraw-via-api The API generates the unsigned transaction, and the client signs it securely Withdraw collateral from Kamino reserve using the API. The API builds the transaction, and you sign it locally keeping your keys secure. ## Withdraw via the API <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, getTransactionDecoder, getCompiledTransactionMessageDecoder, decompileTransactionMessageFetchingLookupTables, pipe, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, addSignersToTransactionMessage, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer'; ``` </Step> <Step> ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={null} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const API_BASE_URL = 'https://api.kamino.finance'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const WS_ENDPOINT = 'wss://api.mainnet-beta.solana.com'; const MAIN_MARKET = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; const CASH_RESERVE = 'ApQkX32ULJUzszZDe986aobLDLMNDoGQK8tRm6oD6SsA'; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); ``` </Step> <Step> ### Call the Kamino API Make a POST request to the Kamino API to build the withdraw transaction. ```typescript theme={null} const res = await fetch(`${API_BASE_URL}/ktx/klend/withdraw`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ wallet: signer.address, market: MAIN_MARKET, reserve: CASH_RESERVE, amount: '2.0', }), }); const data = await res.json(); if (!res.ok) { console.error('Response error:', data); } const encodedTransaction = data.transaction; ``` <Info> The API returns a pre-built transaction encoded in base64 format ready for signing. </Info> </Step> <Step> ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={null} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` </Step> <Step> ### Resolve Address Lookup Tables and Sign Fetch the latest blockhash, decompile the transaction to resolve Address Lookup Tables, and sign. ```typescript theme={null} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const signedTransaction = await pipe( await decompileTransactionMessageFetchingLookupTables(compiledMessage, rpc), tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), tx => setTransactionMessageFeePayerSigner(signer, tx), tx => addSignersToTransactionMessage([signer], tx), tx => signTransactionMessageWithSigners(tx) ); const signature = getSignatureFromTransaction(signedTransaction); ``` <Info> `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. </Info> </Step> <Step> ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={null} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions, }); await sendAndConfirm(signedTransaction, { commitment: 'confirmed', skipPreflight: false, }); console.log('Withdraw successful! Signature:', signature); ``` <Check> Your withdrawal is complete! The API built the transaction, you signed it locally (keeping your keys secure), and it was successfully submitted to the network. </Check> </Step> </Steps> # Earn Deposit with the API Source: https://kamino.com/docs/build/recipes/earn/earn-via-api The API generates the unsigned transaction, and the client signs it securely ## Earn Deposit with API <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, pipe, getTransactionDecoder, getCompiledTransactionMessageDecoder, decompileTransactionMessageFetchingLookupTables, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, addSignersToTransactionMessage, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; ``` </Step> <Step> ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={null} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const API_BASE_URL = 'https://api.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'); ``` </Step> <Step> ### Call Kamino API Make a POST request to the Kamino API to build the deposit transaction. ```typescript theme={null} const response = await fetch(`${API_BASE_URL}/ktx/kvault/deposit`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ wallet: signer.address, kvault: 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E', amount: '1.0', }), }); if (!response.ok) { const error = await response.json(); throw new Error(`API error: ${error.message}`); } const { transaction: encodedTransaction } = await response.json(); ``` <Info> The API returns a pre-built transaction encoded in base64 format. This transaction includes Address Lookup Tables (ALTs) for efficiency. </Info> </Step> <Step> ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={null} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` </Step> <Step> ### Resolve Address Lookup Tables Fetch and resolve the Address Lookup Tables from the blockchain. ```typescript theme={null} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const signedTransaction = await pipe( await decompileTransactionMessageFetchingLookupTables(compiledMessage, rpc), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => addSignersToTransactionMessage([signer], tx), (tx) => signTransactionMessageWithSigners(tx) ); ``` <Info> `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. </Info> <Note> A fresh blockhash is fetched and set to ensure the transaction remains valid. </Note> </Step> <Step> ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={null} const signature = getSignatureFromTransaction(signedTransaction); console.log(`Sending transaction with signature: ${signature}`); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deposit successful! Signature:', signature); ``` <Check> Your deposit is complete! The API built the transaction, you signed it locally (keeping your keys secure), and it was successfully submitted to the network. </Check> </Step> </Steps> # Earn Deposit with the SDK Source: https://kamino.com/docs/build/recipes/earn/earn-via-sdk Deposit to vaults using TypeScript SDK ## Deposit to Earn Vault Deposit assets to start earning yield. <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, } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { Decimal } from 'decimal.js'; ``` </Step> <Step> ### Load Signer and Initialize Vault Load your keypair from a file and initialize RPC connections and the vault instance. ```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 vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E') ); ``` <Note> Replace `/path/to/your/keypair.json` with the actual path to your keypair file. The `rpcSubscriptions` enables real-time transaction confirmation. </Note> </Step> <Step> ### Build Deposit Instructions Generate deposit instructions for the vault. ```typescript theme={null} const depositAmount = new Decimal(1.0); const bundle = await vault.depositIxs(signer, depositAmount); const instructions = [...(bundle.depositIxs || [])]; if (!instructions.length) { throw new Error('No instructions returned by Kamino SDK'); } ``` <Info> The `depositIxs` method returns deposit instructions to add your assets to the vault and mint vault shares. </Info> </Step> <Step> ### Build and Sign Transaction Use Kit's functional pipe pattern to build and sign the transaction with a fresh blockhash. ```typescript theme={null} const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(instructions, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); ``` </Step> <Step> ### Send and Confirm Transaction Send the deposit transaction and wait for confirmation. ```typescript theme={null} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deposit successful! Signature:', signature); ``` <Check> Once the deposit transaction is confirmed, your assets are deposited into the vault and you start earning yield. Vault shares are minted to represent your position. </Check> </Step> </Steps> # Earn Deposit from Privy Wallet Source: https://kamino.com/docs/build/recipes/earn/earn-with-privy Use a Privy-managed wallet to perform secure Earn deposits Deposit to Kamino Earn vaults using Privy embedded wallets. This integration allows users to deposit without managing their own private keys. ## Earn Deposit from Privy <Steps> <Step> ### Import Dependencies Import the required packages for Privy client, Solana RPC communication, and Kamino SDK operations. ```typescript theme={null} import { PrivyClient } from '@privy-io/node'; import { createSolanaRpc, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, createNoopSigner, getBase64EncodedWireTransaction, compileTransaction, } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; ``` </Step> <Step> ### Configure Privy and Initialize Client Set up your Privy credentials and initialize the Privy client and RPC connection. ```typescript theme={null} const PRIVY_APP_ID = 'put-your-privy-app-id-here'; const PRIVY_APP_SECRET = 'put-your-privy-app-secret-here'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const VAULT_ADDRESS = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // Steakhouse USDC Vault const AUTH_KEY_ID = 'put-your-auth-key-id-here'; const AUTH_KEY_PRIVATE = 'put-your-auth-key-private-here'; const USER_EMAIL = 'put-your-email-here'; const privy = new PrivyClient({ appId: PRIVY_APP_ID, appSecret: PRIVY_APP_SECRET, }); const rpc = createSolanaRpc(RPC_ENDPOINT); ``` <Note> Update the configuration values with your Privy app credentials and user details. This example uses the Steakhouse USDC Vault. </Note> </Step> <Step> ### Create Privy User and Wallet Create a Privy user account and generate an embedded Solana wallet. ```typescript theme={null} await privy.users().create({ linked_accounts: [{ type: 'email', address: USER_EMAIL }] }); const { id: walletId, address: walletAddress } = await privy.wallets().create({ chain_type: 'solana', owner_id: AUTH_KEY_ID }); ``` <Warning> Before proceeding, fund the wallet with SOL (for transaction fees) and USDC (for deposit). The wallet cannot submit transactions without sufficient funds. </Warning> </Step> <Step> ### Build Deposit Instructions Initialize the vault and generate deposit instructions using a noop signer. ```typescript theme={null} const vault = new KaminoVault(rpc, address(VAULT_ADDRESS)); await vault.getState(); const noopSigner = createNoopSigner(address(walletAddress)); const bundle = await vault.depositIxs(noopSigner, new Decimal(1.0)); const instructions = [ ...(bundle.depositIxs || []), ]; if (!instructions.length) throw new Error('No instructions returned'); ``` <Info> A noop signer is used to build instructions without requiring the actual private key. Privy will handle signing later. </Info> </Step> <Step> ### Build Transaction Message Fetch the latest blockhash and construct the transaction message. ```typescript theme={null} const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const depositTransactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(noopSigner, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(instructions, tx) ); ``` </Step> <Step> ### Sign Transaction with Privy Compile the transaction, serialize it, and sign using Privy's wallet API. ```typescript theme={null} const compiledTransaction = compileTransaction(depositTransactionMessage); const serializedTx = getBase64EncodedWireTransaction(compiledTransaction); const signResponse = await privy.wallets().solana().signTransaction(walletId, { transaction: serializedTx, authorization_context: { authorization_private_keys: [AUTH_KEY_PRIVATE] } }); ``` <Note> Privy handles the signing securely using the embedded wallet. The private key never leaves Privy's infrastructure. </Note> </Step> <Step> ### Send Transaction Submit the signed transaction to the Solana network. ```typescript theme={null} const signature = await rpc.sendTransaction(signResponse.signed_transaction as any, { encoding: 'base64', skipPreflight: true, }).send(); console.log('Deposit successful! Signature:', signature); ``` <Check> Your deposit is complete! The user's funds are now deposited in the Kamino Earn vault using their Privy embedded wallet. </Check> </Step> </Steps> # Earn Withdraw with the API Source: https://kamino.com/docs/build/recipes/earn/earn-withdraw-via-api The API generates the unsigned transaction, and the client signs it securely ## Earn Withdraw with API <Steps> <Step> ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={null} import { createSolanaRpc, createSolanaRpcSubscriptions, pipe, getTransactionDecoder, getCompiledTransactionMessageDecoder, decompileTransactionMessageFetchingLookupTables, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, addSignersToTransactionMessage, signTransactionMess
프로젝트로 돌아가기