bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 50쪽
ageWithSigners,
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 withdrawal transaction.
```typescript theme={null}
const response = await fetch(`${API_BASE_URL}/ktx/kvault/withdraw`, {
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('Withdrawal 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 Withdraw with the SDK
Source: https://kamino.com/docs/build/recipes/earn/earn-withdraw-via-sdk
Withdraw from vaults using TypeScript SDK
## Withdraw from Earn Vault
Withdraw your vault shares to receive the underlying tokens plus accrued interest.
<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 Withdraw Instructions
Generate withdraw instructions including optional unstaking instructions.
```typescript theme={null}
const withdrawAmount = new Decimal(1.0);
const bundle = await vault.withdrawIxs(signer, withdrawAmount);
const instructions = [...(bundle.unstakeFromFarmIfNeededIxs || []), ...(bundle.withdrawIxs || [])];
if (!instructions.length) {
throw new Error('No instructions returned by Kamino SDK');
}
```
<Info>
The `withdrawIxs` method returns both unstaking and withdraw instructions. The amount represents **vault shares** to redeem, not the underlying token amount.
</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 withdraw transaction and wait for confirmation.
```typescript theme={null}
const signature = getSignatureFromTransaction(signedTransaction);
await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, {
commitment: 'confirmed',
skipPreflight: true,
});
console.log('Withdraw successful! Signature:', signature);
```
<Check>
Once the withdraw transaction is confirmed, your vault shares are burned and you receive the underlying tokens plus any accrued interest.
</Check>
</Step>
</Steps>
# Get Vault APYs
Source: https://kamino.com/docs/build/recipes/earn/get-vault-apys
Fetch Kamino vault APY data using the API or SDK
## How Vault APY Is Calculated
Vault APY is a blended rate based on the reserves the vault's capital is deployed across.
```
Vault APY ≈ Σ (Reserve APY × Allocation Weight)
```
Each reserve earns yield based on its utilization and borrow rate. A reserve at 80% utilization earning 8% APY contributes to the vault's total yield based on its allocation weight, the share of capital deployed there. Allocation weights sum to 100% across all active reserves.
**Example — a USDC vault with two allocations:**
| Reserve | Allocation | APY |
| - | - | - |
| USDC SOL/BTC Market | 60% | 8% |
| USDC JLP Market | 40% | 12% |
```
Blended APY = (60% × 8%) + (40% × 12%) = 9.6%
```
Underlying borrow rates and utilization levels change continuously, so vault APY fluctuates. Quoted APYs are trailing averages and are not guaranteed forward-looking rates.
The displayed APY includes base interest from borrowers plus KMNO emissions when active. APY accounts for compounding. In Kamino vaults, earnings are continuously reinvested, increasing the vault share price over time.
<Tabs>
<Tab title="API">
<Steps>
<Step>
### Fetch All Vaults
Retrieve the list of all available vaults on Kamino.
```typescript theme={null}
const API_BASE_URL = 'https://api.kamino.finance';
const response = await fetch(`${API_BASE_URL}/kvaults/vaults`);
const vaults = await response.json();
```
<Info>
The `/kvaults/vaults` endpoint returns all vaults with basic information including vault addresses, token mints, and strategies.
</Info>
</Step>
<Step>
### Get APY for Each Vault
Fetch APY metrics for all vaults in parallel using the vault public keys.
```typescript theme={null}
// Fetch all vault metrics in parallel
const vaultMetrics = await Promise.all(
vaults.map(async (vault) => {
const response = await fetch(
`${API_BASE_URL}/kvaults/vaults/${vault.address}/metrics`
);
const metrics = await response.json();
return {
address: vault.address,
apy7d: metrics.apy7d,
apy30d: metrics.apy30d,
apy90d: metrics.apy90d,
};
})
);
// Display all vault APYs
vaultMetrics.forEach((vault) => {
console.log(`\n${vault.address}:`);
console.log(` 7-day APY: ${(vault.apy7d * 100).toFixed(2)}%`);
console.log(` 30-day APY: ${(vault.apy30d * 100).toFixed(2)}%`);
console.log(` 90-day APY: ${(vault.apy90d * 100).toFixed(2)}%`);
});
```
<Info>
The `/kvaults/vaults/{pubkey}/metrics` endpoint returns historical APY data across multiple timeframes (7-day, 24-hour, 30-day, 90-day, 180-day, 365-day).
</Info>
<Check>
You now have APY data for all vaults across multiple timeframes.
</Check>
</Step>
</Steps>
</Tab>
<Tab title="SDK">
<Steps>
<Step>
### Import Dependencies
Import the required packages for Solana RPC communication and Kamino SDK.
```typescript theme={null}
import { createSolanaRpc } from '@solana/kit';
import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk';
```
</Step>
<Step>
### Initialize SDK
Set up the RPC connection and create a Kamino Manager instance.
```typescript theme={null}
const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com');
const kaminoManager = new KaminoManager(rpc, 400);
```
</Step>
<Step>
### Get All Vaults
Retrieve all available vaults using the Kamino Manager.
```typescript theme={null}
const vaults = await kaminoManager.getAllVaults();
```
</Step>
<Step>
### Get APYs for Each Vault
Fetch APY data for all vaults in parallel.
```typescript theme={null}
// Fetch APYs for all vaults in parallel
const vaultAPYs = await Promise.all(
vaults.map(async (vaultData) => {
const vault = new KaminoVault(rpc, vaultData.address);
const apys = await vault.getAPYs();
return {
address: vaultData.address.toString(),
name: vaultData.state?.name,
actualAPY: apys.actualAPY.netAPY,
theoreticalAPY: apys.theoreticalAPY.netAPY,
};
})
);
// Display all vault APYs
vaultAPYs.forEach((vault) => {
console.log(`\n${vault.address}:`);
console.log(` Actual APY: ${vault.actualAPY}`);
console.log(` Theoretical APY: ${vault.theoreticalAPY}`);
});
```
<Info>
The `vault.getAPYs()` method returns `theoreticalAPY` and `actualAPY`, each containing `grossAPY` and `netAPY` (after fees) calculated from on-chain state.
</Info>
<Check>
You've successfully fetched vault APYs using the Kamino SDK.
</Check>
</Step>
</Steps>
</Tab>
</Tabs>
## Related Resources
<CardGroup>
<Card title="Lending Vaults Concepts" icon="book" href="/docs/products/lending-vaults/concepts">
Learn how vaults work under the hood
</Card>
<Card title="Vault Data" icon="database" href="/docs/build/earn/vault-data-positions">
Query vault metrics and positions
</Card>
<Card title="Benchmark Rate" icon="chart-line" href="/docs/products/lending-vaults/benchmark-rate">
Compare vault yields to market baseline
</Card>
<Card title="Earn Deposit" icon="arrow-down" href="/docs/build/recipes/earn/earn-via-api">
Deposit into vaults via API
</Card>
</CardGroup>
# Withdraw to Privy Wallet and Check Balance
Source: https://kamino.com/docs/build/recipes/earn/withdraw-with-privy
Use a Privy-managed wallet to perform secure Earn withdrawals and check USDC balance
Withdraw from Kamino Earn vaults using Privy embedded wallets and check the resulting USDC balance. This integration allows users to withdraw without managing their own private keys.
## Earn Withdraw to 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,
createNoopSigner,
createTransactionMessage,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstructions,
compileTransaction,
getBase64EncodedWireTransaction,
} 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 = 'your-privy-app-id';
const PRIVY_APP_SECRET = 'your-privy-app-secret';
const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com';
const VAULT_ADDRESS = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // Steakhouse USDC vault
const AUTH_KEY_PRIVATE = 'your-auth-key-private';
const WALLET_ID = 'your-wallet-id';
const privy = new PrivyClient({
appId: PRIVY_APP_ID,
appSecret: PRIVY_APP_SECRET,
});
const rpc = createSolanaRpc(RPC_ENDPOINT);
```
</Step>
<Step>
### Get Wallet and Initialize Vault
Retrieve the Privy wallet and initialize the Kamino vault instance.
```typescript theme={null}
const wallet = await privy.wallets().get(WALLET_ID);
const walletAddress = wallet.address;
const vault = new KaminoVault(rpc, address(VAULT_ADDRESS));
await vault.getState();
```
</Step>
<Step>
### Check User Shares
Query the user's vault shares to determine how much can be withdrawn.
```typescript theme={null}
const userShares = await vault.getUserShares(address(walletAddress));
console.log(
`Vault shares: ${userShares.unstakedShares?.toString() || '0'} unstaked, ${
userShares.stakedShares?.toString() || '0'
} staked`
);
const totalShares = parseFloat(userShares.totalShares?.toString() || '0');
if (totalShares === 0) throw new Error('No shares to withdraw');
```
<Info>
The total shares represent the user's position in the vault. Both staked and unstaked shares are included in the withdrawal.
</Info>
</Step>
<Step>
### Build Withdrawal Instructions
Generate withdrawal instructions for all user shares using a noop signer.
```typescript theme={null}
const noopSigner = createNoopSigner(address(walletAddress));
const withdrawAmount = new Decimal(totalShares);
const bundle = await vault.withdrawIxs(noopSigner, withdrawAmount);
const withdrawInstructions = [...(bundle.withdrawIxs || [])];
if (!withdrawInstructions.length) throw new Error('No withdrawal instructions returned');
```
<Note>
A noop signer is used to build instructions without requiring the actual private key. Privy will handle signing later.
</Note>
</Step>
<Step>
### Build Transaction Message
Fetch the latest blockhash and construct the withdrawal transaction message.
```typescript theme={null}
const { value: withdrawBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send();
const withdrawTxMessage = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(noopSigner, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(withdrawBlockhash, tx),
(tx) => appendTransactionMessageInstructions(withdrawInstructions, tx)
);
```
</Step>
<Step>
### Sign Transaction with Privy
Compile the transaction, serialize it, and sign using Privy's wallet API.
```typescript theme={null}
const compiledWithdrawTx = compileTransaction(withdrawTxMessage);
const serializedWithdrawTx = getBase64EncodedWireTransaction(compiledWithdrawTx);
const withdrawSignResponse = await privy
.wallets()
.solana()
.signTransaction(WALLET_ID, {
transaction: serializedWithdrawTx,
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 withdrawSig = await rpc
.sendTransaction(withdrawSignResponse.signed_transaction as any, {
encoding: 'base64',
skipPreflight: true,
})
.send();
console.log('Withdrawal successful! Signature:', withdrawSig);
```
</Step>
<Step>
### Check USDC Balance
Query the wallet's USDC balance using Privy's balance API.
```typescript theme={null}
const balance = await privy.wallets().balance.get(WALLET_ID, {
asset: 'usdc',
chain: 'solana',
});
const usdcBalance = balance.balances[0];
console.log(`USDC Balance: ${usdcBalance.display_values.usdc}`);
```
<Check>
Your withdrawal is complete! The user's vault shares have been redeemed for USDC, and the balance is now available in their Privy wallet.
</Check>
</Step>
</Steps>
# Building with LLMs
Source: https://kamino.com/docs/build/resources/building-with-llms
Leverage Kamino documentation with AI agents and language models for faster development
<Note>
Kamino documentation is optimized for AI-powered development. Our machine-readable resources enable LLMs and AI agents to understand our APIs and build transactions on Solana.
</Note>
## Kamino AI Resources
<div>
<CardGroup>
<Card title="skill.md" icon="brain-circuit" href="https://kamino.com/docs/skill.md">
Structured capability reference with API endpoints, SDK methods, and integration workflows. Start here for agent tool use.
</Card>
<Card title="llms.txt" icon="file-lines" href="https://kamino.com/docs/llms.txt">
Curated index of all documentation pages with one-line descriptions and direct URLs.
</Card>
<Card title="llms-pages.json" icon="brackets-curly" href="https://kamino.com/docs/llms-pages.json">
Machine-readable JSON mapping of every page with title, section, URL, and keywords.
</Card>
</CardGroup>
</div>
### skill.md
The skill.md file provides a comprehensive, machine-readable reference of Kamino's capabilities across all four products: Earn, Borrow, Multiply, and Liquidity.
| Includes | Description |
| - | - |
| API endpoints | Complete REST endpoint reference for all products |
| SDK methods | TypeScript method signatures with real code examples |
| Workflows | Step-by-step operations: deposit, borrow, withdraw, repay, stake, harvest |
| Integration patterns | Earn vaults, Borrow markets, Liquidity strategies, and Farms |
| Use cases | Agent transaction building, API integration, automated DeFi strategies |
### llms.txt
A structured navigation map of Kamino's entire documentation, enabling LLMs to discover relevant pages and resources efficiently.
| Includes | Description |
| - | - |
| Page directory | All documentation pages with direct URLs |
| Tutorials | Organized by category: Earn, Borrow, Liquidity, Rewards, Oracle |
| API reference | Endpoint navigation and documentation links |
| Recipes | Code example locations and implementation guides |
### llms-pages.json
A JSON file mapping every page path to its metadata: title, URL, section, description, and keywords. Useful for programmatic discovery and filtering.
```json theme={null}
{
"/products/lending-vaults": {
"title": "Lending Vaults",
"url": "https://kamino.com/docs/products/lending-vaults",
"section": "Docs",
"description": "Single-token managed yield aggregation across Kamino's lending markets",
"keywords": ["k프로젝트로 돌아가기