# Building with LLMs Source: https://docs.kamino.com/build/agentic-finance/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. ## Kamino AI Resources > [card] [skill.md](https://docs.kamino.com/skill.md) > > Structured capability reference with API endpoints, SDK methods, and integration workflows. Start here for agent tool use. > [card] [llms.txt](https://docs.kamino.com/llms.txt) > > Curated index of all documentation pages with one-line descriptions and direct URLs. > [card] [llms-pages.json](https://docs.kamino.com/llms-pages.json) > > Machine-readable JSON mapping of every page with title, section, URL, and keywords. ### 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={"theme":"css-variables"} { "/products/lending-vaults": { "title": "Lending Vaults", "url": "https://docs.kamino.com/products/lending-vaults", "section": "Docs", "description": "Single-token managed yield aggregation across Kamino's lending markets", "keywords": ["kamino", "lending vaults", "yield", "vault shares", "auto-compounding"] } } ``` # Agent Integrations: Using OpenClaw with Kamino Source: https://docs.kamino.com/build/agentic-finance/openclaw-agent-integration Build an OpenClaw skill to enable AI agents to autonomously interact with Kamino's lending markets and yield vaults > [!TIP] > > By the end of this tutorial, you will have the following skill files configured for your agent. | File | Purpose | | - | - | | [`SKILL.md`](#skill-md) | Main skill instructions: capabilities, quick reference, and workflows | | [`references/setup.md`](#references/setup-md) | Environment setup: RPC, wallet keypair, OpenClaw config | | [`references/earn.md`](#references/earn-md) | Earn vault operations: deposit, withdraw, vault data, user positions | | [`references/borrow.md`](#references/borrow-md) | Borrow market operations: deposit, borrow, repay, withdraw, market data | | [`references/multiply.md`](#references/multiply-md) | Multiply operations: leveraged positions, flash loans, position health | | [`references/liquidity.md`](#references/liquidity-md) | Liquidity strategy operations: deposit, withdraw, strategy metrics, user PnL | | [`references/rewards.md`](#references/rewards-md) | Farm operations: stake, unstake, harvest, farm state, pending rewards | | [`references/api.md`](#references/api-md) | Complete REST API endpoint reference for all products | ## Prerequisites * Node.js 22+ * Solana wallet with SOL for transaction fees * RPC endpoint ## Skill Folder Structure **1. Create Skill Directory** Create a new directory for the Kamino skill in your OpenClaw workspace: ```bash theme={"theme":"css-variables"} mkdir -p ~/.openclaw/workspace/skills/kamino cd ~/.openclaw/workspace/skills/kamino ``` **2. Create File Structure** Create the following files in the directory: ``` kamino/ ├── SKILL.md # Main skill instructions for the agent └── references/ ├── setup.md # Environment and SDK setup ├── earn.md # Kamino Earn operations (vaults) ├── borrow.md # Kamino Borrow operations (lending) ├── multiply.md # Kamino Multiply operations (leverage) ├── liquidity.md # Kamino Liquidity operations (strategies) ├── rewards.md # Kamino Rewards operations (farms) └── api.md # Kamino API reference ``` ```bash theme={"theme":"css-variables"} mkdir -p references touch SKILL.md references/setup.md references/earn.md references/borrow.md references/multiply.md references/liquidity.md references/rewards.md references/api.md ``` **3. Get a Solana RPC Endpoint** Choose an RPC provider: * **Free**: `https://api.mainnet-beta.solana.com` (rate limited) * **Recommended**: Helius, QuickNode, or Triton (paid, production-ready) **4. Create or Use Existing Wallet Keypair** Create a new keypair if needed: ```bash theme={"theme":"css-variables"} solana-keygen new --outfile ~/solana-wallet.json ``` Or use an existing keypair file. **5. Configure OpenClaw** Add your Solana credentials to `~/.openclaw/openclaw.json`: ```json theme={"theme":"css-variables"} { "gateway": { "env": { "SOLANA_RPC_URL": "https://api.mainnet-beta.solana.com", "SOLANA_WS_URL": "wss://api.mainnet-beta.solana.com", "WALLET_KEYPAIR_PATH": "/path/to/your/solana-wallet.json" } } } ``` Replace `/path/to/your/solana-wallet.json` with the actual path to your keypair file. **6. Restart OpenClaw Gateway** After updating the configuration: ```bash theme={"theme":"css-variables"} openclaw gateway restart ``` **7. Verify Setup** Test your RPC connection: ```bash theme={"theme":"css-variables"} curl -X POST $SOLANA_RPC_URL \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"getHealth"}' ``` ### For Other AI Agents * **Claude**: Copy the SKILL.md content into your conversation or attach as a file * **Cursor**: Clone into `.cursor/skills/kamino` directory * **Custom Agents**: Reference the markdown files directly ## File Templates Copy the following templates into your skill files. ### SKILL.md The main skill file that teaches agents how to interact with Kamino: ```markdown expandable theme={"theme":"css-variables"} # Kamino Skill Interact with Kamino Finance on Solana: Earn vaults, Borrow markets, Liquidity strategies, and Rewards farms. ## Prerequisites See [setup.md](references/setup.md) for installation and configuration. Required: - Solana RPC endpoint - Wallet keypair for signing transactions - `@solana/kit` and relevant Kamino SDKs installed ## What You Can Do **Kamino Earn** - Deposit into yield-generating vaults **Kamino Borrow** - Supply collateral, borrow assets, repay loans **Kamino Multiply** - Open and manage leveraged positions **Kamino Liquidity** - Deposit into automated concentrated liquidity strategies **Kamino Rewards** - Stake, unstake, and harvest farm rewards **KSwap** - Swap between any two tokens via Kamino's swap aggregator **Oracle (Scope)** - Read token prices on-chain or via REST ## Quick Reference | Operation | Method | Reference | |-----------|--------|-----------| | Earn: Deposit | SDK or API | [earn.md](references/earn.md) | | Earn: Withdraw | SDK or API | [earn.md](references/earn.md) | | Borrow: Deposit Collateral | SDK or API | [borrow.md](references/borrow.md) | | Borrow: Borrow Assets | SDK or API | [borrow.md](references/borrow.md) | | Borrow: Repay Loan | SDK or API | [borrow.md](references/borrow.md) | | Borrow: Withdraw Collateral | SDK or API | [borrow.md](references/borrow.md) | | Multiply: Open Position | SDK | [multiply.md](references/multiply.md) | | Multiply: Monitor Health | SDK | [multiply.md](references/multiply.md) | | Multiply: Repay or Withdraw | SDK | [multiply.md](references/multiply.md) | | Liquidity: Deposit | SDK | [liquidity.md](references/liquidity.md) | | Liquidity: Withdraw | SDK | [liquidity.md](references/liquidity.md) | | Liquidity: Strategy Data | SDK or API | [liquidity.md](references/liquidity.md) | | Rewards: Stake | SDK | [rewards.md](references/rewards.md) | | Rewards: Unstake | SDK | [rewards.md](references/rewards.md) | | Rewards: Harvest | SDK | [rewards.md](references/rewards.md) | | KSwap: Swap Tokens | API | [api.md](references/api.md) | | Oracle: Read Prices | SDK or API | [api.md](references/api.md) | | Query Market Data | SDK | [borrow.md](references/borrow.md) | | Get Vault/Market Lists | API | [api.md](references/api.md) | ## Core Workflow ### For Kamino Earn: 1. Choose a vault (get list via API or use known address) 2. Deposit tokens to earn yield 3. Withdraw vault shares when needed ### For Kamino Borrow: 1. Supply collateral to a market 2. Borrow assets against your collateral 3. Monitor health factor (keep LTV below 75%) 4. Repay loans and withdraw collateral ### For Kamino Multiply: 1. Choose a strategy (LST, JLP, stablecoin, or xStocks) 2. Open a leveraged position with target leverage 3. Monitor LTV and liquidation risk 4. Adjust leverage, repay debt, or close position ### For Kamino Liquidity: 1. Choose a strategy (get list via API or use known address) 2. Deposit tokens (single-sided or two-sided) 3. Monitor share price and PnL 4. Withdraw shares when needed ### For Kamino Rewards: 1. Find the farm for your position (by stake mint or known address) 2. Stake share tokens into the farm 3. Monitor pending rewards 4. Harvest rewards or unstake and withdraw **SOL/BTC Market**: `7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF` ## Reference Files - **[setup.md](references/setup.md)** — Installation and OpenClaw configuration - **[earn.md](references/earn.md)** — Vault deposit/withdraw code examples - **[borrow.md](references/borrow.md)** — Lending market operations - **[multiply.md](references/multiply.md)** — Leveraged position operations - **[liquidity.md](references/liquidity.md)** — Liquidity strategy operations - **[rewards.md](references/rewards.md)** — Farm staking and reward harvesting - **[api.md](references/api.md)** — Complete API endpoint reference ``` ### references/setup.md Setup guide for using Kamino with OpenClaw: ```markdown expandable theme={"theme":"css-variables"} # Kamino Setup Configure OpenClaw to interact with Kamino Finance protocols on Solana. ## Prerequisites Before using this skill, you need: - OpenClaw installed (Node.js 22+) - Solana RPC endpoint (get from Helius, QuickNode, or use public endpoint) - Solana wallet keypair file for signing transactions For complete developer documentation: https://docs.kamino.com/build ## SDK Versions The SDKs use different `@solana/kit` versions, so install them in separate projects: - `@kamino-finance/klend-sdk` 13 and `@kamino-finance/kswap-sdk` 2.9.0 (Earn, Borrow, Multiply): kit 2 - `@kamino-finance/farms-sdk` 5 and `@kamino-finance/kliquidity-sdk` 16 (Rewards, Liquidity): kit 8 **SOL/BTC Market**: `7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF` ``` ### references/earn.md Kamino Earn vault operations: ````markdown expandable theme={"theme":"css-variables"} # Kamino Earn Operations Deposit into yield-generating vaults, withdraw shares, and query vault/user data. ## Dependencies ```bash npm install @solana/kit @kamino-finance/klend-sdk decimal.js ``` ## SDK Instantiation ```typescript import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault, KaminoManager, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const vault = new KaminoVault( rpc, address('VAULT_PUBKEY_HERE'), slotDuration ); const manager = new KaminoManager(rpc, slotDuration); const ledgerInstant = await getCurrentLedgerInstant(rpc); ``` ## SDK Operations | What to Do | SDK Method | Documentation | |------------|------------|---------------| | **Transactions** | | Deposit to vault | `vault.depositIxs(signer, amount, reservesMap, farmState, null)` | [Recipe](https://docs.kamino.finance/build/recipes/earn/earn-via-sdk) | | Withdraw from vault | `vault.withdrawIxs(signer, shareAmount, ledgerInstant, reservesMap, farmState, null)` | [Recipe](https://docs.kamino.finance/build/recipes/earn/earn-withdraw-via-sdk) | | **Read Vault Data** | | Get vault holdings | `vault.getVaultHoldings(ledgerInstant)` | [Data Docs](https://docs.kamino.com/build/developers/earn/data/vault-data) | | Get vault APY | `vault.getAPYs(ledgerInstant)` | [Data Docs](https://docs.kamino.com/build/developers/earn/data/vault-data) | | Get exchange rate | `vault.getExchangeRate(ledgerInstant)` | [Data Docs](https://docs.kamino.com/build/developers/earn/data/vault-data) | | Get allocations | `vault.getVaultAllocations()` | [Data Docs](https://docs.kamino.com/build/developers/earn/data/vault-data) | | Get vault overview | `manager.getVaultOverview(vault, tokenPrice, ledgerInstant, ...)` | [Data Docs](https://docs.kamino.com/build/developers/earn/data/vault-data) | | **Read User Data** | | Get user shares | `vault.getUserShares(userAddress)` | [Data Docs](https://docs.kamino.com/build/developers/earn/data/user-position-data) | | Get all positions | `manager.getUserSharesBalanceAllVaults(userAddress)` | [Data Docs](https://docs.kamino.com/build/developers/earn/data/user-position-data) | ## API Operations | What to Do | API Endpoint | Documentation | |------------|--------------|---------------| | **Transactions** | | Deposit to vault | `POST /ktx/kvault/deposit` | [Recipe](https://docs.kamino.finance/build/recipes/earn/earn-via-api) | | Withdraw from vault | `POST /ktx/kvault/withdraw` | [Recipe](https://docs.kamino.finance/build/recipes/earn/earn-withdraw-via-api) | | **Read Vault Data** | | List all vaults | `GET /kvaults/vaults` | [API Docs](https://api-docs.kamino.finance) | | Get vault details | `GET /vault/{vaultPubkey}` | [API Docs](https://api-docs.kamino.finance) | | Get vault metrics | `GET /vault/{vaultPubkey}/metrics` | [API Docs](https://api-docs.kamino.finance) | | Historical metrics | `GET /vault/{vaultPubkey}/metrics/history` | [API Docs](https://api-docs.kamino.finance) | | **Read User Data** | | Get user positions | `GET /kvaults/users/{wallet}/positions` | [API Docs](https://api-docs.kamino.finance) | | Get vault position | `GET /kvaults/users/{wallet}/vaults/{vaultPubkey}/position` | [API Docs](https://api-docs.kamino.finance) | | Get position PnL | `GET /kvaults/users/{wallet}/vaults/{vaultPubkey}/pnl` | [API Docs](https://api-docs.kamino.finance) | | Get transactions | `GET /kvaults/users/{wallet}/transactions` | [API Docs](https://api-docs.kamino.finance) | ## Important Notes - Withdrawals use **vault share amounts**, not underlying token amounts - SDK automatically handles farm unstaking if needed - API transactions use Address Lookup Tables - must use `decompileTransactionMessageFetchingLookupTables` - Historical data only available via API ## Complete Tutorial [Earn and Withdraw Tutorial](https://docs.kamino.finance/build/tutorials/earn/earn-and-withdraw) ```` ### references/borrow\.md Kamino Borrow operations (deposit collateral, borrow, repay, withdraw): ````markdown expandable theme={"theme":"css-variables"} # Kamino Borrow Operations Supply collateral, borrow assets, repay loans, withdraw collateral, and query market/user data. **SOL/BTC Market**: `7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF` ## Dependencies ```bash npm install @solana/kit @kamino-finance/klend-sdk bn.js decimal.js ``` ## SDK Instantiation ```typescript import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const ledgerInstant = await getCurrentLedgerInstant(rpc); const userAddress = address('USER_WALLET_ADDRESS'); const obligation = await market!.getObligationByWallet(userAddress, new VanillaObligation(PROGRAM_ID)); ``` ## SDK Operations | What to Do | SDK Method | Documentation | |------------|------------|---------------| | **Transactions** | | Deposit collateral | `KaminoAction.buildDepositTxns({ kaminoMarket, amount, reserveAddress, owner, obligation, useV2Ixs, scopeRefreshConfig, initUserMetadata, currentLedgerInstant })` | [Guide](https://docs.kamino.com/build/developers/borrow/operations/deposit) | | Borrow | `KaminoAction.buildBorrowTxns({ ... })` | [Guide](https://docs.kamino.com/build/developers/borrow/operations/borrow) | | Repay | `KaminoAction.buildRepayTxns({ ... })` | [Guide](https://docs.kamino.com/build/developers/borrow/operations/repay) | | Withdraw collateral | `KaminoAction.buildWithdrawTxns({ ... })` | [Guide](https://docs.kamino.com/build/developers/borrow/operations/withdraw) | | Supply for interest (cTokens) | `KaminoAction.buildDepositReserveLiquidityTxns({ ... })` | [Tutorial](https://docs.kamino.com/build/tutorials/borrow/mint-ctokens) | | Fixed-rate borrow order | `KaminoBorrowOrder.createFixedTermBorrowOrder({ ... })` + `KaminoAction.buildDepositAndSetBorrowOrderTxns({ ... })` | [Tutorial](https://docs.kamino.com/build/borrow/tutorials/fixed-rate-borrowing) | | Instructions from an action | `KaminoAction.actionToIxs(action)` | | | **Read Market Data** | | Get the variable-rate reserve for a token | `market.getExistingFloatRateReserveByMint(mint)` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/market-data) | | Get all reserves | `market.getReserves()` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/market-data) | | Get reserve kind (variable or fixed rate) | `reserve.getKind().toString()` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/market-data) | | Get total deposit / borrow TVL | `market.getTotalDepositTVL()`, `market.getTotalBorrowTVL()` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/market-data) | | Get reserve supply / borrow APY | `reserve.totalSupplyAPY(ledgerInstant)`, `reserve.totalBorrowAPY(ledgerInstant)` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/market-data) | | Get reserve utilization (0 to 1) | `reserve.calculateUtilizationRatio()` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/market-data) | | **Read User Data** | | Get user's obligation | `market.getObligationByWallet(user, new VanillaObligation(PROGRAM_ID))` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/user-position-data) | | Get all user obligations | `market.getAllUserObligations(user, ledgerInstant)` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/user-position-data) | | Get deposits / borrows | `obligation.getDeposits()`, `obligation.getBorrows()` (amounts in lamports; divide by `mintFactor`) | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/user-position-data) | | Get LTV and liquidation LTV | `obligation.refreshedStats.loanToValue`, `obligation.refreshedStats.liquidationLtv` | [Data Docs](https://docs.kamino.com/build/developers/borrow/data/user-position-data) | ## API Operations | What to Do | API Endpoint | Documentation | |------------|--------------|---------------| | **Transactions** | | Deposit collateral | `POST /ktx/klend/deposit` | [Recipe](https://docs.kamino.com/build/recipes/borrow/deposit-via-api) | | Borrow assets | `POST /ktx/klend/borrow` | [Recipe](https://docs.kamino.com/build/recipes/borrow/borrow-via-api) | | Repay loan | `POST /ktx/klend/repay` | [Recipe](https://docs.kamino.com/build/recipes/borrow/repay-via-api) | | Withdraw collateral | `POST /ktx/klend/withdraw` | [Recipe](https://docs.kamino.com/build/recipes/borrow/withdraw-via-api) | | **Read Market Data** | | List all markets | `GET /v2/kamino-market` | [API Docs](https://docs.kamino.com/build/api-reference/introduction) | | Reserve metrics | `GET /kamino-market/{marketPubkey}/reserves/metrics` | [API Docs](https://docs.kamino.com/build/api-reference/introduction) | | Historical reserve APY and borrow curve | `GET /kamino-market/{marketPubkey}/reserves/{reservePubkey}/metrics/history` | [API Docs](https://docs.kamino.com/build/api-reference/borrow/market-data/market-reserve-metrics-history) | | **Read User Data** | | Get user obligations | `GET /kamino-market/{marketPubkey}/users/{userPubkey}/obligations` | [API Docs](https://docs.kamino.com/build/api-reference/introduction) | | Get user transactions | `GET /v2/kamino-market/{marketPubkey}/users/{userPubkey}/transactions` | [API Docs](https://docs.kamino.com/build/api-reference/introduction) | ## Important Notes - **Reserve address, not mint**: a token can have several reserves (one variable-rate plus fixed-rate ones). Actions take `reserveAddress`; use `getExistingFloatRateReserveByMint(mint)` for the variable-rate one. - **Ledger instant**: actions, APYs, and obligation lookups take `await getCurrentLedgerInstant(rpc)`, not a slot. - **Slot duration**: load the market with `getMedianSlotDurationInMsFromLastEpochs()`. A hard-coded 400 ms shows fixed-rate APYs at about half their real value. - **First deposit**: pass `initUserMetadata: { skipInitialization: false, skipLutCreation: true }` so account setup fits in one transaction; without it the deposit fails with `0x17a3`. - **Full repay or withdraw**: pass `new BN(U64_MAX)` as the amount. - **Health checks**: verify LTV against liquidation LTV before borrowing or withdrawing collateral. - **API transactions** use lookup tables; decompile with `decompileTransactionMessageFetchingLookupTables`. ## Complete Tutorials - [Deposit and Borrow Tutorial](https://docs.kamino.com/build/tutorials/borrow/deposit-and-borrow) - [Repay and Withdraw Tutorial](https://docs.kamino.com/build/tutorials/borrow/repay-and-withdraw) - [Fixed-Rate Borrowing](https://docs.kamino.com/build/borrow/tutorials/fixed-rate-borrowing) ```` ### references/multiply.md Kamino Multiply leveraged position operations: ````markdown expandable theme={"theme":"css-variables"} # Kamino Multiply Operations Open leveraged positions, monitor health, repay, withdraw, and shrink positions. ## Dependencies ```bash npm install @solana/kit @kamino-finance/klend-sdk @kamino-finance/kswap-sdk@2.9.0 @kamino-finance/scope-sdk @solana-program/address-lookup-table bn.js decimal.js ``` ## SDK Instantiation ```typescript import { createSolanaRpc, createSolanaRpcSubscriptions, address } from '@solana/kit'; import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; import { KswapSdk } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const marketPubkey = address('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); const scope = new Scope('mainnet-beta', rpc); ``` ## SDK Operations | What to Do | SDK Method | Documentation | |------------|------------|---------------| | **Transactions** | | Open or add to a leveraged position | `getDepositWithLeverageIxs({ ... })` | [Guide](https://docs.kamino.com/build/developers/multiply/operations/deposit-xstocks) | | Repay debt by selling collateral | `getRepayWithCollIxs({ ... })` | [Guide](https://docs.kamino.com/build/developers/multiply/operations/repay-collateral) | | Repay debt from the wallet | `KaminoAction.buildRepayTxns({ ... })` with the `MultiplyObligation` | [Guide](https://docs.kamino.com/build/developers/multiply/operations/repay-xstocks) | | Withdraw collateral | `KaminoAction.buildWithdrawTxns({ ... })` with the `MultiplyObligation` | [Guide](https://docs.kamino.com/build/developers/multiply/operations/withdraw-xstocks) | | Shrink the position, keep leverage | `getWithdrawWithLeverageIxs({ ... })` | [Guide](https://docs.kamino.com/build/developers/multiply/operations/deleverage-xstocks) | | Flash loan | `getFlashLoanInstructions({ ... })` | [Guide](https://docs.kamino.com/build/developers/multiply/flash-loans) | | Swap routes | `kswap.getAllRoutes(params, await loadRouterContext(rpc, tokenIn, tokenOut))` | [Guide](https://docs.kamino.com/build/developers/multiply/operations/deposit-xstocks) | | **Read Position Data** | | Get multiply positions | `market.getUserObligationsByTag(ObligationTypeTag.Multiply, userAddress, ledgerInstant)` | [Guide](https://docs.kamino.com/build/developers/multiply/data/health-metrics) | | Get position LTV / liquidation LTV | `obligation.refreshedStats.loanToValue`, `obligation.refreshedStats.liquidationLtv` | [Guide](https://docs.kamino.com/build/developers/multiply/data/health-metrics) | | Get leverage and net value | `obligation.refreshedStats.leverage`, `obligation.refreshedStats.netAccountValue` | [Guide](https://docs.kamino.com/build/developers/multiply/data/health-metrics) | | Get position amounts (token units) | `obligation.getDepositAmountByReserve(collReserve)`, `obligation.getBorrowAmountByReserve(debtReserve)` | [Guide](https://docs.kamino.com/build/developers/multiply/operations/deleverage-xstocks) | ## Important Notes - Use kswap-sdk 2.9.0: the last version on `@solana/kit` 2, which klend-sdk 13 uses. - The quoter's `priceAInB` must be the mid price (`amountOut / amountIn` in token units), before slippage; the SDK applies slippage itself. - `kswap.getBestRoute` currently returns no routes; use `getAllRoutes`. - The leverage functions return one candidate transaction per swap route. Compress each with lookup tables from `POST /luts/find-minimal` (one request per candidate) and send the best-output one that fits the size limit. - The leverage functions expect the wallet's user metadata to exist; create it first for a new wallet. - `getWithdrawWithLeverageIxs` keeps the position's LTV; to lower leverage, repay debt. - Flash loan repay includes a small fee; the wallet must hold it in the borrowed token. - Leveraged combo operations are TypeScript SDK only. ## Complete Guides - [Flash Loans](https://docs.kamino.com/build/developers/multiply/flash-loans) - [Open Position (xStocks)](https://docs.kamino.com/build/developers/multiply/operations/deposit-xstocks) - [Repay with Collateral](https://docs.kamino.com/build/developers/multiply/operations/repay-collateral) - [Monitor Position Health](https://docs.kamino.com/build/developers/multiply/data/health-metrics) ```` ### references/liquidity.md Kamino Liquidity strategy operations: ````markdown expandable theme={"theme":"css-variables"} # Kamino Liquidity Operations Deposit into automated concentrated liquidity strategies, withdraw shares, and query strategy/user data. ## Dependencies ```bash npm install @solana/kit @kamino-finance/kliquidity-sdk decimal.js ``` ## SDK Instantiation ```typescript 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); ``` ## SDK Operations | What to Do | SDK Method | Documentation | |------------|------------|---------------| | **Transactions** | | Single-sided deposit | `kamino.singleSidedDepositTokenB(strategy, amount, signer, slippageBps)` | [Guide](https://docs.kamino.finance/build/developers/liquidity/operations/deposit) | | Two-sided deposit | `kamino.deposit(strategyWithAddress, amountA, amountB, signer)` | [Guide](https://docs.kamino.finance/build/developers/liquidity/operations/deposit) | | Withdraw all shares | `kamino.withdrawAllShares(strategyWithAddress, signer)` | [Guide](https://docs.kamino.finance/build/developers/liquidity/operations/withdraw) | | **Read Strategy Data** | | Get all strategies | `kamino.getAllStrategiesWithFilters(filters)` | [Guide](https://docs.kamino.finance/build/developers/liquidity/data/strategy) | | Get share price and balances | `kamino.getStrategyShareData(strategyAddress)` | [Guide](https://docs.kamino.finance/build/developers/liquidity/data/strategy) | | Get share price only | `kamino.getStrategySharePrice(strategyAddress)` | [Guide](https://docs.kamino.finance/build/developers/liquidity/data/strategy) | | **Read User Data** | | Get user positions | `kamino.getUserPositions(walletAddress)` | [Guide](https://docs.kamino.finance/build/developers/liquidity/data/user-position) | ## API Operations | What to Do | API Endpoint | Documentation | |------------|--------------|---------------| | **Read Strategy Data** | | List all strategies | `GET /strategies?status=LIVE` | [API Ref](https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategies-list) | | Get strategy metrics | `GET /strategies/{pubkey}/metrics` | [API Ref](https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategy-metrics) | | Historical metrics | `GET /v2/strategies/{pubkey}/history` | [API Ref](https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategy-metrics-history) | | Total TVL | `GET /strategies/tvl` | [API Ref](https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategies-tvl) | | Fees and rewards | `GET /strategies/fees-and-rewards?period=24h` | [API Ref](https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategies-fees-and-rewards) | | **Read User Data** | | User PnL | `GET /v2/strategies/{pubkey}/shareholders/{wallet}/pnl` | [API Ref](https://docs.kamino.com/build/api-reference/liquidity/user-data/user-pnl) | | User transactions | `GET /v2/shareholders/{wallet}/transactions` | [API Ref](https://docs.kamino.com/build/api-reference/liquidity/user-data/user-transactions) | ## Important Notes - Single-sided deposit auto-swaps half the input via the SDK's built-in swap router - Withdrawals return both Token A and Token B proportionally - Use `POST /luts/find-minimal` for address lookup table resolution on deposits and withdrawals - Historical data only available via API ## Complete Guide - [Deposit Guide](https://docs.kamino.finance/build/developers/liquidity/operations/deposit) - [Withdraw Guide](https://docs.kamino.finance/build/developers/liquidity/operations/withdraw) ```` ### references/rewards.md Kamino Rewards farm operations: ````markdown expandable theme={"theme":"css-variables"} # Kamino Rewards Operations Stake into farms, unstake, harvest rewards, and query farm/user data. ## Dependencies ```bash npm install @solana/kit @kamino-finance/farms-sdk decimal.js ``` ## SDK Instantiation ```typescript import { createSolanaRpc, address } from '@solana/kit'; import { Farms, fetchFarmState } from '@kamino-finance/farms-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const farms = new Farms(rpc); ``` ## SDK Operations | What to Do | SDK Method | Documentation | |------------|------------|---------------| | **Transactions** | | Stake tokens | `farms.stakeIx(...)` | [Guide](https://docs.kamino.finance/build/developers/rewards/operations/stake) | | Unstake tokens | `farms.unstakeIx(...)` | [Guide](https://docs.kamino.finance/build/developers/rewards/operations/unstake) | | Withdraw unstaked | `farms.withdrawUnstakedDepositIx(...)` | [Guide](https://docs.kamino.finance/build/developers/rewards/operations/withdraw-unstaked) | | Harvest all rewards | `farms.claimForUserForFarmAllRewardsIx(...)` | [Guide](https://docs.kamino.finance/build/developers/rewards/operations/harvest) | | **Read Farm Data** | | Get farm state | `fetchFarmState(rpc, farmAddress)` (fields are `bigint`) | [Guide](https://docs.kamino.finance/build/developers/rewards/data/farm-state) | | Batch-load farms | `farms.getAllFarmStatesByPubkeys(addresses)` | [Guide](https://docs.kamino.finance/build/developers/rewards/data/farm-state) | | Find farms by mint | `farms.getFarmsForMint(stakeMint)` | [Guide](https://docs.kamino.finance/build/developers/rewards/data/farm-state) | | Get incentive APY | `farms.getRewardsAPYForStrategy(strategyAddress)` | [Guide](https://docs.kamino.finance/build/developers/rewards/data/farm-state) | | **Read User Data** | | Get all user positions | `farms.getAllFarmsForUser(walletAddress, now)` | [Guide](https://docs.kamino.finance/build/developers/rewards/data/user-position) | | Get pending rewards | `farms.getUserPendingRewards(userState, farmState, now, oraclePrices)` | [Guide](https://docs.kamino.finance/build/developers/rewards/data/user-position) | | Get lockup status | `farms.getLockupDurationAndExpiry(farm, user, now)` | [Guide](https://docs.kamino.finance/build/developers/rewards/data/user-position) | ## API Operations | What to Do | API Endpoint | Documentation | |------------|--------------|---------------| | Farm transactions | `GET /farms/{farmPubkey}/transactions` | [API Ref](https://docs.kamino.com/build/api-reference/rewards/farm-transactions) | | Farm management history | `GET /farms/{farmPubkey}/management-history` | [API Ref](https://docs.kamino.com/build/api-reference/rewards/farm-management-history) | | User farm transactions | `GET /farms/users/{pubkey}/transactions` | [API Ref](https://docs.kamino.com/build/api-reference/rewards/user-transactions) | | Oracle prices (for reward valuation) | `GET /oracles/prices` | [API Ref](https://docs.kamino.com/build/api-reference/oracle/oracle-prices) | ## Important Notes - **Delegated farms** (klend reserve farms, kvault farms) have no stake mint; a delegate authority stakes on behalf of users - **Non-delegated farms** own their stake token; use `getFarmsForMint` to discover them - Unstaking triggers a **withdrawal cooldown** before tokens can be withdrawn - Reward valuation requires oracle prices from `GET /oracles/prices?source=scope` - Farm operations are SDK-only; there are no transaction-building API endpoints for farms ## Complete Guide - [Farm State Guide](https://docs.kamino.finance/build/developers/rewards/data/farm-state) - [User Position Guide](https://docs.kamino.finance/build/developers/rewards/data/user-position) - [Stake Guide](https://docs.kamino.finance/build/developers/rewards/operations/stake) - [Harvest Guide](https://docs.kamino.finance/build/developers/rewards/operations/harvest) ```` ### references/api.md Kamino REST API endpoints: ```markdown expandable theme={"theme":"css-variables"} # Kamino API Reference Quick reference for Kamino Finance REST API. ## Base URL `https://api.kamino.finance` No API key required for public endpoints. ## Complete Documentation - Full API Reference: https://docs.kamino.com/build/api-reference/introduction - OpenAPI Specification: https://api-docs.kamino.finance ## Key Endpoints **Kamino Earn:** - `POST /ktx/kvault/deposit` - Deposit to vault - `POST /ktx/kvault/withdraw` - Withdraw from vault - `GET /kvaults/vaults` - List all vaults - `GET /kvaults/users/{walletAddress}/positions` - User positions **Kamino Borrow:** - `POST /ktx/klend/deposit` - Deposit collateral - `POST /ktx/klend/borrow` - Borrow assets - `POST /ktx/klend/repay` - Repay loan - `POST /ktx/klend/withdraw` - Withdraw collateral - `GET /v2/kamino-market` - List all markets - `GET /kamino-market/{marketPubkey}/users/{userPubkey}/obligations` - User obligations **Kamino Multiply:** - Multiply operations are SDK-only (no API transaction endpoints) - Monitor positions via `GET /kamino-market/{marketPubkey}/users/{userPubkey}/obligations` **Kamino Liquidity:** - `GET /strategies?status=LIVE` - List all strategies - `GET /strategies/{pubkey}/metrics` - Strategy metrics - `GET /v2/strategies/{pubkey}/history` - Historical metrics - `GET /strategies/tvl` - Total TVL - `GET /v2/strategies/{pubkey}/shareholders/{wallet}/pnl` - User PnL - `GET /v2/shareholders/{wallet}/transactions` - User transactions **Kamino Rewards (Farms):** - `GET /farms/{farmPubkey}/transactions` - Farm transactions - `GET /farms/{farmPubkey}/management-history` - Farm management history - `GET /farms/users/{pubkey}/transactions` - User farm transactions **Oracle:** - `GET /oracles/prices` - Oracle prices with timestamp and staleness - `GET /prices` - Token USD prices by mint **KSwap (Token Swaps):** - `GET /kswap/swap/` - Get best route and transaction for swapping between two tokens **Utilities:** - `POST /luts/find-minimal` - Find minimal Address Lookup Tables ## Important Notes - All transaction endpoints return base64-encoded transactions - Transactions use Address Lookup Tables and require `decompileTransactionMessageFetchingLookupTables` - Client must decode, sign with fresh blockhash, and submit transactions - Farm operations (stake, unstake, harvest) are SDK-only with no API transaction endpoints ``` ## Usage Examples Once installed, your agent can execute commands like: * "Deposit 100 USDC into the SOL-USDC vault" * "Check my current lending positions on Kamino" * "Withdraw 50% of my vault shares" * "Supply 1000 USDC to the lending market" * "What's the APY on the SOL-USDC vault?" * "Deposit into the KMNO/USDC liquidity strategy" * "What are my pending farm rewards?" * "Harvest all rewards from my staked positions" * "Swap 1 SOL to USDC" * "Get the current SOL price from the oracle" For detailed code examples, see the Kamino documentation links in the reference files. # Get airdrop metrics Source: https://docs.kamino.com/build/airdrop/get-airdrop-metrics /kamino-api.json get /v2/airdrop/metrics Fetches aggregated airdrop metrics and metadata for a specific points source. # Get user airdrop allocations Source: https://docs.kamino.com/build/airdrop/get-user-airdrop-allocations /kamino-api.json get /v2/airdrop/users/{pubkey}/allocations Fetches airdrop allocation data for a specific user and source (Seasons...) # Get transaction to borrow liquidity from a klend reserve Source: https://docs.kamino.com/build/api-reference/borrow/actions/borrow/klend-borrow ktx-api.json POST /ktx/klend/borrow Borrow liquidity from the specified Kamino Lend market reserve # Get instructions to borrow liquidity from a klend reserve Source: https://docs.kamino.com/build/api-reference/borrow/actions/borrow/klend-borrow-instructions ktx-api.json POST /ktx/klend/borrow-instructions Instructions to borrow liquidity from the specified Kamino Lend market reserve. Additionally includes lookup tables to use to compress transaction size # Get transaction to deposit into a klend reserve Source: https://docs.kamino.com/build/api-reference/borrow/actions/deposit/klend-deposit ktx-api.json POST /ktx/klend/deposit Deposit tokens into the specified Kamino Lend market reserve. An optional `memo` is added to the transaction as an SPL memo instruction. # Get instructions to deposit into a klend reserve Source: https://docs.kamino.com/build/api-reference/borrow/actions/deposit/klend-deposit-instructions ktx-api.json POST /ktx/klend/deposit-instructions Instructions to deposit tokens into the specified Kamino Lend market reserve. Additionally includes lookup tables to use to compress transaction size # Get transaction to repay debt of a klend reserve Source: https://docs.kamino.com/build/api-reference/borrow/actions/repay/klend-repay ktx-api.json POST /ktx/klend/repay Repay a debt position for the specified Kamino Lend market reserve # Get instructions to repay debt of a klend reserve Source: https://docs.kamino.com/build/api-reference/borrow/actions/repay/klend-repay-instructions ktx-api.json POST /ktx/klend/repay-instructions Instructions to repay a debt position for the specified Kamino Lend market reserve. Additionally includes lookup tables to use to compress transaction size # Get transaction to withdraw from a klend reserve Source: https://docs.kamino.com/build/api-reference/borrow/actions/withdraw/klend-withdraw ktx-api.json POST /ktx/klend/withdraw Withdraw tokens from the specified Kamino Lend market reserve # Get instructions to withdraw from a klend reserve Source: https://docs.kamino.com/build/api-reference/borrow/actions/withdraw/klend-withdraw-instructions ktx-api.json POST /ktx/klend/withdraw-instructions Instructions to withdraw tokens from the specified Kamino Lend market reserve. Additionally includes lookup tables to use to compress transaction size # Get Kamino Market config Source: https://docs.kamino.com/build/api-reference/borrow/market-data/market-detail kamino-api.json GET /v2/kamino-market/{pubkey} Get configuration for a specific Kamino Lending market by market address. Optionally filter by program ID. # Get metrics for leverage/multiply vaults Source: https://docs.kamino.com/build/api-reference/borrow/market-data/market-leverage-metrics kamino-api.json GET /kamino-market/{pubkey}/leverage/metrics Get aggregated metrics for all leverage and multiply positions in a Kamino Lending market, including average leverage, total borrowed, total deposited, and number of obligations. # Get KLend reserve history Source: https://docs.kamino.com/build/api-reference/borrow/market-data/market-reserve-metrics-history kamino-api.json GET /kamino-market/{marketPubkey}/reserves/{reservePubkey}/metrics/history Get historical metrics for a specific reserve in a Kamino Lending market over a specified time range with configurable frequency (hour or day). Without a frequency, ranges shorter than 32 days are hourly and longer ranges are daily. APYs, amounts and capped available liquidity are means of raw snapshots in each UTC bucket. Other metrics retain the last snapshot. # Get KLend market reserves account data Source: https://docs.kamino.com/build/api-reference/borrow/market-data/market-reserves-account-data kamino-api.json GET /kamino-market/reserves/account-data Fetch reserve account data for given Klend markets. Returns base64-encoded account data for all reserves in the specified markets. # Get metrics for market reserves Source: https://docs.kamino.com/build/api-reference/borrow/market-data/market-reserves-metrics kamino-api.json GET /kamino-market/{pubkey}/reserves/metrics Get current metrics for all reserves in a Kamino Lending market, including APY, TVL, borrow/supply amounts, and LTV ratios. # Get all Kamino Markets config Source: https://docs.kamino.com/build/api-reference/borrow/market-data/markets-list kamino-api.json GET /v2/kamino-market Get all Kamino Lending markets configuration for a specific program ID. This is the V2 endpoint that allows filtering by program ID instead of cluster. # Get KLend reward history Source: https://docs.kamino.com/build/api-reference/borrow/rewards/rewards-history kamino-api.json GET /klend/{depositReservePubkey}/{borrowReservePubkey}/rewards/history Fetches historical KLend reward metrics for a specific deposit and borrow reserve pair # Get KLend rewards Source: https://docs.kamino.com/build/api-reference/borrow/rewards/rewards-list kamino-api.json GET /klend/rewards Fetches all active KLend reward metrics for a specific points source # Get information about a loan (obligation) Source: https://docs.kamino.com/build/api-reference/borrow/user-and-loans-data/loan-detail kamino-api.json GET /klend/loans/{pubkey} Fetches information about a loan # Get KLend obligation history Source: https://docs.kamino.com/build/api-reference/borrow/user-and-loans-data/obligation-metrics-history kamino-api.json GET /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/metrics/history Get historical metrics for a specific obligation in a Kamino Lending market. This V2 endpoint supports using stake rate for obligation value calculation when `useStakeRateForObligation` is true. Points are hourly for ranges shorter than 32 days and daily otherwise. Hourly data is kept for 34 days, so ranges starting more than 33 days ago are returned daily. # Get profit and loss for an obligation Source: https://docs.kamino.com/build/api-reference/borrow/user-and-loans-data/obligation-pnl kamino-api.json GET /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/pnl Get profit and loss (PnL) for a specific obligation. For xSOL pairs, `useStakeRate` can be set to true to calculate the PnL using the stake rate. # Get all user obligations Source: https://docs.kamino.com/build/api-reference/borrow/user-and-loans-data/user-obligations kamino-api.json GET /kamino-market/{marketPubkey}/users/{userPubkey}/obligations Get all obligations (loans) for a specific user wallet in a Kamino Lending market. # Get user KLend rewards Source: https://docs.kamino.com/build/api-reference/borrow/user-and-loans-data/user-rewards kamino-api.json GET /klend/users/{pubkey}/rewards Fetches KLend reward data for a specific user and points source # Distributor codes Source: https://docs.kamino.com/build/api-reference/distributors A distributor is a third party that directs deposit flow into Kamino Earn vaults or Kamino Lend reserves. Deposits and withdrawals are attributed to a distributor by a 5-character code carried in the SPL Memo instruction of the transaction. ## Generating codes ### Getting credentials Registering codes and reading their analytics require API credentials. The Kamino team issues a username and password on request. These are sent as HTTP basic auth on the calls below. ### Registering a code Each code is registered under a unique name of 1 to 64 characters. The name should describe the purpose of the code, as the distributor is responsible for maintaining the mapping from name to code. ```bash theme={"theme":"css-variables"} curl -u ':' \ -H 'Content-Type: application/json' \ -d '{"name": "Example Wallet - mobile app"}' \ https://api.kamino.finance/distributors ``` ```json theme={"theme":"css-variables"} { "code": "abcde" } ``` The code is active immediately. A name that already exists returns `409`. ## Tagging transactions The code is passed as the `memo` field of the deposit and withdraw endpoints. For Kamino Earn: [`POST /ktx/kvault/deposit`](/build/api-reference/earn/actions/deposit/kvault-deposit), [`POST /ktx/kvault/deposit-instructions`](/build/api-reference/earn/actions/deposit/kvault-deposit-instructions), [`POST /ktx/kvault/withdraw`](/build/api-reference/earn/actions/withdraw/kvault-withdraw) or [`POST /ktx/kvault/withdraw-instructions`](/build/api-reference/earn/actions/withdraw/kvault-withdraw-instructions): ```json theme={"theme":"css-variables"} { "wallet": "", "kvault": "", "amount": "0.1234", "memo": "abcde" } ``` For Kamino Lend: [`POST /ktx/klend/deposit`](/build/api-reference/borrow/actions/deposit/klend-deposit) or [`POST /ktx/klend/deposit-instructions`](/build/api-reference/borrow/actions/deposit/klend-deposit-instructions): ```json theme={"theme":"css-variables"} { "wallet": "", "market": "", "reserve": "", "amount": "0.1234", "memo": "abcde" } ``` When the transaction is built manually, an SPL Memo instruction whose data is the code must be included in the same transaction as the deposit or withdraw instruction. * The memo must be exactly the code. Matching is case-insensitive. * Use one code per transaction. * The `memo` field accepts up to 64 UTF-8 bytes. Longer values return `400`. * Codes use the alphabet `23456789abcdefghjkmnpqrstuvwxyz`, so `0`, `1`, `o`, `l` and `i` never appear. ## Analytics Four endpoints report the deposits and withdrawals attributed to distributor codes. They are private: send the same basic auth credentials used to register codes, or the call returns `401`. They cover Kamino Earn vaults only; tagged Kamino Lend transactions are not reported yet. | Endpoint | Scope | | - | - | | [`GET /kvaults/vaults/{pubkey}/distributor-transactions`](/build/api-reference/earn/distributors/vault-distributor-transactions) | every tagged transaction on one vault, across all codes | | [`GET /kvaults/distributors/{code}/transactions`](/build/api-reference/earn/distributors/distributor-transactions) | every transaction tagged with one code, across all vaults | | [`GET /kvaults/distributors/{code}/vaults/{vault}/transactions`](/build/api-reference/earn/distributors/distributor-vault-transactions) | every transaction tagged with one code on one vault | | [`GET /kvaults/distributors/{code}/wallets`](/build/api-reference/earn/distributors/distributor-wallets) | per-wallet totals for one code, split by token and direction | Rules that apply to all four: * Each flow has a `type`: `deposit` for the `deposit` and `buy` instructions, `withdraw` for the `withdraw`, `withdrawFromAvailable`, `sell` and `redeemInKind` instructions. Admin and crank instructions are never counted, even when their transaction carries a code. * `type` is an optional query parameter. `type=deposit` or `type=withdraw` returns only that direction; omitted, both are returned. * `start` and `end` are optional query parameters, given as ISO 8601 strings or epoch milliseconds, and either can be given on its own. A missing `start` means the beginning of history and a missing `end` means now. `start` is inclusive and `end` is exclusive, and `start` must be before `end` once the missing one is filled in, so an `end` before 1970 or a `start` in the future returns `400`. * On the three code-based endpoints the code is matched case-insensitively, and an unregistered code returns `404`. * Responses are cached for 60 seconds. All four endpoints page with a cursor. `limit` accepts 1 to 1000 and defaults to 100. When more rows remain, the response carries a `paginationToken`; the last page has none. Pass it back unchanged on the next call together with the same `start`, `end` and `type`. The transaction endpoints return the newest rows first. On the wallets endpoint the token also pins the `start`, `end` and `type` the first page aggregated over, filling in an omitted bound at the moment of the first page, so later pages total the same set of transactions even while new ones arrive. A wallets token sent with a different `start`, `end` or `type` returns `400`. ```bash theme={"theme":"css-variables"} curl -u ':' \ 'https://api.kamino.finance/kvaults/distributors/abcde/transactions?start=2026-01-01T00:00:00Z&end=2026-02-01T00:00:00Z&limit=2' ``` ```json theme={"theme":"css-variables"} { "result": [ { "createdOn": "2026-01-20T14:03:11.000Z", "tx": "", "code": "abcde", "type": "withdraw", "instruction": "withdraw", "wallet": "", "vault": "", "tokenMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "tokenSymbol": "USDC", "amount": "2500" }, { "createdOn": "2026-01-18T09:41:57.000Z", "tx": "", "code": "abcde", "type": "deposit", "instruction": "deposit", "wallet": "", "vault": "", "tokenMint": "So11111111111111111111111111111111111111112", "tokenSymbol": "SOL", "amount": "10.5" } ], "paginationToken": "eyJjcmVhdGVkT24iOiIyMDI2LTAxLTE4VDA5OjQxOjU3LjAwMFoiLCJsYXN0SWQiOiI0MjE3In0=" } ``` The three transaction endpoints return one row per instruction, not per transaction, so a transaction with several tagged vault instructions gives one row each. `amount` is a decimal string in the underlying token, not in vault shares, and is always positive; the `type` gives the direction. For `redeemInKind`, which pays out cTokens of a reserve, the cTokens are converted to the underlying token at the reserve exchange rate at that time. `instruction` is the Kamino Earn vault instruction that moved the tokens. `tokenSymbol` is `null` when the token is not known to Kamino. The wallets endpoint aggregates the same transactions by wallet, ordered by wallet address. Each wallet lists one entry per token and direction, with the total amount moved. A wallet that both deposited and withdrew a token gets two entries for it, one with `type` `deposit` and one with `type` `withdraw`; the two are never netted. The `type` query parameter restricts the totals to one direction. ```bash theme={"theme":"css-variables"} curl -u ':' \ 'https://api.kamino.finance/kvaults/distributors/abcde/wallets?start=2026-01-01T00:00:00Z&end=2026-02-01T00:00:00Z' ``` ```json theme={"theme":"css-variables"} { "result": [ { "wallet": "", "tokens": [ { "tokenMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "tokenSymbol": "USDC", "type": "deposit", "amount": "4000" }, { "tokenMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "tokenSymbol": "USDC", "type": "withdraw", "amount": "2500" }, { "tokenMint": "So11111111111111111111111111111111111111112", "tokenSymbol": "SOL", "type": "deposit", "amount": "10.5" } ] } ] } ``` # Get transaction to deposit into a kvault Source: https://docs.kamino.com/build/api-reference/earn/actions/deposit/kvault-deposit ktx-api.json POST /ktx/kvault/deposit Deposit tokens into a specified Kamino Earn Vault. An optional `memo` is added to the transaction as an SPL memo instruction. # Get instructions to deposit into a kvault Source: https://docs.kamino.com/build/api-reference/earn/actions/deposit/kvault-deposit-instructions ktx-api.json POST /ktx/kvault/deposit-instructions Instructions to deposit tokens into a specified Kamino Earn Vault. Additionally includes lookup tables to use to compress transaction size. An optional `memo` is added as an SPL memo instruction. # Get transaction to withdraw from a kvault Source: https://docs.kamino.com/build/api-reference/earn/actions/withdraw/kvault-withdraw ktx-api.json POST /ktx/kvault/withdraw Withdraw tokens from a specified Kamino Earn Vault. An optional `memo` is added as an SPL memo instruction. # Get instructions to withdraw from a kvault Source: https://docs.kamino.com/build/api-reference/earn/actions/withdraw/kvault-withdraw-instructions ktx-api.json POST /ktx/kvault/withdraw-instructions Instructions to withdraw tokens from a specified Kamino Earn Vault. Includes lookup tables for transaction compression. An optional `memo` is added as an SPL memo instruction. # Get transactions for a distributor code Source: https://docs.kamino.com/build/api-reference/earn/distributors/distributor-transactions kamino-api.json GET /kvaults/distributors/{code}/transactions Cursor-paginated list of deposits and withdrawals, across every Kamino Earn vault, whose transaction carried this distributor code, newest first. One row per instruction. Private (authorized) API access only, please add a basic auth header to your request. # Get transactions for a distributor code in a vault Source: https://docs.kamino.com/build/api-reference/earn/distributors/distributor-vault-transactions kamino-api.json GET /kvaults/distributors/{code}/vaults/{vault}/transactions Cursor-paginated list of deposits into and withdrawals out of one Kamino Earn vault whose transaction carried this distributor code, newest first. One row per instruction. Private (authorized) API access only, please add a basic auth header to your request. # Get wallet totals for a distributor code Source: https://docs.kamino.com/build/api-reference/earn/distributors/distributor-wallets kamino-api.json GET /kvaults/distributors/{code}/wallets For each wallet that transacted under this distributor code in the range: the total amount per token and direction, deposits and withdrawals as separate lines. Private (authorized) API access only, please add a basic auth header to your request. # Get distributor transactions of a vault Source: https://docs.kamino.com/build/api-reference/earn/distributors/vault-distributor-transactions kamino-api.json GET /kvaults/vaults/{pubkey}/distributor-transactions Cursor-paginated list of deposits into and withdrawals out of a Kamino Earn vault whose transaction carried a distributor code, newest first. One row per instruction, so a transaction with several gives several rows. Private (authorized) API access only, please add a basic auth header to your request. # Get historical user metrics for all KVault positions Source: https://docs.kamino.com/build/api-reference/earn/user-data/user-metrics-history kamino-api.json GET /kvaults/users/{pubkey}/metrics/history Get historical timeseries of total usd/sol/interest/apy for all user Kamino Earn Vault positions # Get all user KVault positions Source: https://docs.kamino.com/build/api-reference/earn/user-data/user-positions kamino-api.json GET /kvaults/users/{pubkey}/positions Get a list of user positions for each Kamino Earn Vault the user has currently deposited into. Returns staked and unstaked shares. # Get user KVault transactions Source: https://docs.kamino.com/build/api-reference/earn/user-data/user-transactions kamino-api.json GET /kvaults/users/{pubkey}/transactions Get all Kamino Earn Vault transactions for a given user # Get historical user metrics for a single KVault Source: https://docs.kamino.com/build/api-reference/earn/user-data/user-vault-metrics-history kamino-api.json GET /kvaults/users/{userPubkey}/vaults/{vaultPubkey}/metrics/history Get historical timeseries for one vault position. Automatic selection picks minute rows for ranges up to 2 days, hourly rows for ranges under 32 days, and daily rows otherwise, returning finer rows for positions younger than those windows, measured from the first resampled bucket. frequency=minute is limited to ranges of at most 32 days. frequency=day&view=chart returns only UTC daily bucket timestamps, USD balances and cumulative USD interest. The newest daily bucket may be partial; use the summary endpoint for the latest balance. Open-ended histories can be up to five minutes plus processing time old. # Get user KVault PnL Source: https://docs.kamino.com/build/api-reference/earn/user-data/user-vault-pnl kamino-api.json GET /kvaults/users/{userPubkey}/vaults/{vaultPubkey}/pnl Get current PnL and cost basis of user vault position # Get user KVault PnL history Source: https://docs.kamino.com/build/api-reference/earn/user-data/user-vault-pnl-history kamino-api.json GET /kvaults/users/{userPubkey}/vaults/{vaultPubkey}/pnl/history Get PnL and cost basis history of user vault position # Get user position for a specific KVault Source: https://docs.kamino.com/build/api-reference/earn/user-data/user-vault-position kamino-api.json GET /kvaults/users/{userPubkey}/positions/{vaultPubkey} Get a single user position for a Kamino Earn Vault the user currently has currently deposited into. Returns staked and unstaked shares. # Get historical KVault allocation volume Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vault-allocation-history kamino-api.json GET /kvaults/vaults/{pubkey}/allocation-volume/history Get historical Kamino Earn Vault allocation volume for a given vault and date range (max 1 year) # Get KVault by address Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vault-detail kamino-api.json GET /kvaults/vaults/{pubkey} Get a single Kamino Earn Vault by the KVault account address # Get current KVault metrics Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vault-metrics kamino-api.json GET /kvaults/vaults/{pubkey}/metrics Get current Kamino Earn Vault metrics for a given vault # Get historical KVault metrics Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vault-metrics-history kamino-api.json GET /kvaults/vaults/{pubkey}/metrics/history Get historical Kamino Earn Vault metrics for a given vault, between an optional range of dates # Get icon for KVault token Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vault-mint-image kamino-api.json GET /kvaults/mints/{pubkey}/metadata/image.svg Get the SVG icon for a given Kamino Earn Vault receipt token mint # Get metadata for KVault token Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vault-mint-metadata kamino-api.json GET /kvaults/mints/{pubkey}/metadata Get metadata for a given Kamino Earn Vault receipt token mint # Get all kvaults Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vaults-list kamino-api.json GET /kvaults/vaults Get Kamino Earn Vaults. Omit type for all on-chain vaults. Use live or privateCredit for CDN-listed vaults. # Get all KVault season rewards Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vaults-rewards kamino-api.json GET /kvaults/rewards Get all active season points rewards for each Kamino Earn Vault # Get summary of the KVault program earnings Source: https://docs.kamino.com/build/api-reference/earn/vault-data/vaults-summary kamino-api.json GET /kvaults/summary Get an aggregated all-time summary of all Kamino Earn Vault rewards and interest earned, in SOL and USD # Kamino API Source: https://docs.kamino.com/build/api-reference/introduction Access comprehensive data for Kamino Earn vaults, lending markets, user positions, and transaction endpoints to seamlessly integrate yield strategies and borrowing functionality into your applications. ## Base URL All Kamino API requests use the following base URL: ```bash theme={"theme":"css-variables"} https://api.kamino.finance ``` ## Distributor codes Third parties that direct deposits into Kamino can tag their deposits and withdrawals with a distributor code and read back the attributed flow. See [Distributor codes](/build/api-reference/distributors). # Swap Source: https://docs.kamino.com/build/api-reference/kswap/swap kswap-api.json GET /kswap/swap/ Get the best route and a pre-built transaction for swapping between two tokens on Solana via Kamino's swap aggregator. The response includes the serialized transaction, expected output amount, minimum output after slippage, and which router was selected. Get the best route and transaction for swapping between two tokens on Solana via Kamino's swap aggregator. ## Example **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, pipe, getTransactionDecoder, getCompiledTransactionMessageDecoder, decompileTransactionMessageFetchingLookupTables, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, addSignersToTransactionMessage, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, isTransactionWithinSizeLimit, } from '@solana/kit'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer'; ``` **Step 2** ### Configure and Initialize ```typescript theme={"theme":"css-variables"} 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 signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); ``` **Step 3** ### Fetch Swap Transaction Call the KSwap API to get the best route and a pre-built transaction. This example swaps 1 SOL to USDC with 50bps max slippage. ```typescript theme={"theme":"css-variables"} const SOL = 'So11111111111111111111111111111111111111112'; const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; const params = new URLSearchParams({ tokenIn: SOL, tokenOut: USDC, amountIn: '1000000000', // 1 SOL in lamports maxSlippageBps: '50', wallet: signer.address, }); const res = await fetch(`${API_BASE_URL}/kswap/swap/?${params}`); const { data } = await res.json(); console.log(`Router: ${data.routerType}, Expected out: ${data.expectedAmountOut}`); const encodedTransaction = data.transaction; ``` **Step 4** ### Decode, Sign, and Send Decode the base64 transaction, sign it locally, and submit to the network. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); 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) ); if (!isTransactionWithinSizeLimit(signedTransaction)) { throw new Error('Transaction exceeds size limit'); } const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Swap successful! Signature:', signature); ``` # Get strategy fees and rewards Source: https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategies-fees-and-rewards kamino-extra-api.json GET /strategies/fees-and-rewards Get fees and rewards earned across all strategies over a chosen time period. # Get all strategies Source: https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategies-list kamino-extra-api.json GET /strategies Get all Kamino Liquidity strategies with addresses, pool metadata, and status. # Get total strategy TVL Source: https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategies-tvl kamino-extra-api.json GET /strategies/tvl Get aggregate total value locked across all live Kamino Liquidity strategies. # Get strategy metrics Source: https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategy-metrics kamino-extra-api.json GET /strategies/{pubkey}/metrics Get real-time metrics for a specific strategy including share price, TVL, APY breakdown, and token balances. # Get strategy historical metrics Source: https://docs.kamino.com/build/api-reference/liquidity/strategy-data/strategy-metrics-history kamino-extra-api.json GET /v2/strategies/{pubkey}/history Get time-series data for a strategy including share price, TVL, fees, rewards, and token prices. # Get user fees and rewards Source: https://docs.kamino.com/build/api-reference/liquidity/user-data/user-fees-and-rewards kamino-extra-api.json GET /strategies/{strategyPubkey}/shareholders/{walletPubkey}/fees-and-rewards Get cumulative fees and rewards earned by a user in a specific strategy. # Get user PnL Source: https://docs.kamino.com/build/api-reference/liquidity/user-data/user-pnl kamino-extra-api.json GET /v2/strategies/{strategyPubkey}/shareholders/{walletPubkey}/pnl Get current profit and loss for a user position in a specific strategy. # Get user PnL history Source: https://docs.kamino.com/build/api-reference/liquidity/user-data/user-pnl-history kamino-extra-api.json GET /v2/strategies/{strategyPubkey}/shareholders/{walletPubkey}/pnl/history Get time-series PnL snapshots for a user position in a specific strategy. # Get user rewards history Source: https://docs.kamino.com/build/api-reference/liquidity/user-data/user-rewards-history kamino-extra-api.json GET /strategies/shareholders/{walletPubkey}/rewards/history Get historical rewards earned by a wallet across all Kamino Liquidity strategies. # Get user transactions Source: https://docs.kamino.com/build/api-reference/liquidity/user-data/user-transactions kamino-extra-api.json GET /v2/shareholders/{walletPubkey}/transactions Get deposit, withdrawal, and claim transaction history for a wallet across all strategies. # Find Lookup Tables for addresses Source: https://docs.kamino.com/build/api-reference/luts/find-minimal kamino-api.json POST /luts/find-minimal Finds the smallest set of Lookup Table (LUT) addresses that together cover all the provided Solana addresses. Optionally verifies active LUTs on-chain. # Get managed LUTs for a product Source: https://docs.kamino.com/build/api-reference/luts/managed kamino-api.json GET /luts/managed Returns active lookup table addresses associated with a given product identifier address. # Get managed LUTs for multiple products Source: https://docs.kamino.com/build/api-reference/luts/managed-batch kamino-api.json GET /luts/managed/batch Returns active lookup table addresses for multiple product identifier addresses in a single request. # Get managed LUTs by product type Source: https://docs.kamino.com/build/api-reference/luts/managed-product-type kamino-api.json GET /luts/managed/product-type/{productType} Returns all active lookup table addresses grouped by product for a given product type. # Register a new vault with its on-chain LUT Source: https://docs.kamino.com/build/api-reference/luts/new-vault kamino-api.json POST /luts/managed/new-vault Verifies the vault and LUT exist on-chain, then registers the vault product and LUT entry. Private (authorized) API access only, please add a basic auth header to your request. # Get oracle prices Source: https://docs.kamino.com/build/api-reference/oracle/oracle-prices kamino-api.json GET /oracles/prices Fetches all oracle prices for all public Klend Market assets # Get token prices Source: https://docs.kamino.com/build/api-reference/oracle/token-prices kamino-extra-api.json GET /prices Get the USD price for tokens tracked by Kamino, keyed by mint address and token symbol. # Get token price history Source: https://docs.kamino.com/build/api-reference/oracle/token-prices-history kamino-extra-api.json GET /prices/history Get the historical USD price for a token tracked by Kamino. Returns an array of `[price, timestamp]` pairs ordered oldest to newest, where `price` is the USD price as a string and `timestamp` is a Unix time in seconds. # Get pending farm rewards for a wallet Source: https://docs.kamino.com/build/api-reference/portfolio/portfolio-rewards kamino-api.json GET /portfolio/{pubkey}/rewards Returns pending farm reward source rows across Kamino products. USD reward totals are composed on the client from price data. # Get portfolio source data for a wallet Source: https://docs.kamino.com/build/api-reference/portfolio/portfolio-source-data kamino-api.json GET /portfolio/{pubkey} Returns source position rows across Kamino products (lending, multiply, leverage, liquidity, earn, private credit, staking). Portfolio totals, counts, fees, historical PnL, and display-only rollups are intentionally left to client composition or their dedicated endpoints. After a transaction, pass minSlot to read a portfolio that includes it. # Get farm management history Source: https://docs.kamino.com/build/api-reference/rewards/farm-management-history kamino-api.json GET /farms/{farmPubkey}/management-history Get management instructions for a specific farm (with pagination). # Get farm transactions Source: https://docs.kamino.com/build/api-reference/rewards/farm-transactions kamino-api.json GET /farms/{farmPubkey}/transactions Get transactions for a specific farm (with pagination). # Get user farm transactions Source: https://docs.kamino.com/build/api-reference/rewards/user-transactions kamino-api.json GET /farms/users/{pubkey}/transactions Get all farms program transactions for a given user (with pagination). # Get tokens Source: https://docs.kamino.com/build/api-reference/tokens/token-list kamino-extra-api.json GET /tokens-api/tokens Get metadata and market data for tokens known to Kamino. Returns mint address, symbol, name, decimals, logo, verification status, 24-hour trading volume, and market cap. Without filters the endpoint returns the top 20 tokens by trading volume. # Borrow Overview Source: https://docs.kamino.com/build/borrow/index Bring borrowing, lending, and leverage to your users with Kamino Borrow Overview Borrow &\ Lend ==== Bring borrowing, lending, and leverage to your users with Kamino. [Developer guide](/build/developers/borrow) \$2.3BMarket size \$900M+Active borrows 18+Audits Start here ## How Borrowing Works Users deposit assets as collateral, borrow against them, and repay to unlock their collateral. 01 ### Deposit Supply collateral to open a position. 02 ### Borrow Borrow assets up to your collateral's limit. 03 ### Repay Repay with interest to unlock collateral. ## Start with Your Goal [Offer borrowing in your app Let users borrow against their assets at variable or fixed rates. Explore borrowing](/build/borrow/tutorials/deposit-and-borrow) [Offer leveraged positions Give users leverage on the assets they already hold, including xStocks. Explore Multiply](/build/borrow/multiply/leverage-concepts) [Generate revenue from a market Launch a lending market with the assets and terms you choose. Plan your market](/build/borrow/plan-your-market) ## Choose Your Tools Pick the right tools for building with Borrow or operating a market. ### Build with Borrow [REST APIRead markets and positions, and request unsigned transactions.](/build/api-reference/introduction) [TypeScript SDKBuild lending transactions and compose leveraged strategies.](/build/borrow/tutorials/deposit-and-borrow) [Rust crateBuild Rust clients and onchain integrations.](/build/borrow/tutorials/rust/deposit-and-borrow) ### Operate a Market [Create a marketSet up a lending market and its administration.](/curators/markets/creating-a-market) [Manage reservesAdd assets and tune their risk settings.](/curators/markets/reserve-management) [Fixed-rate reservesOffer borrowing at a set rate for a set term.](/curators/markets/fixed-rates/reserve-configuration) ## Build the Experience Guide users from finding liquidity to closing a position. Explore markets Show supported assets, rates, and available liquidity. [Open](/build/borrow/market-data-metrics) Deposit and borrow Build flows for adding collateral and borrowing against it. [Open](/build/borrow/tutorials/deposit-and-borrow) Open and adjust leverage Create leveraged positions and manage exposure. [Open](/build/borrow/multiply/multiply-deposit-kswap) Track position health Surface collateral, debt, and liquidation thresholds. [Open](/build/borrow/multiply/monitor-position-health) Manage borrow terms Show fixed-rate maturity and rollover settings. [Open](/build/borrow/tutorials/fixed-rate-borrowing) Repay and withdraw Reduce debt and release available collateral. [Open](/build/borrow/tutorials/repay-and-withdraw) # Market Data and Metrics Source: https://docs.kamino.com/build/borrow/market-data-metrics Learn how to access market data including supply APY, borrow APY, TVL, and utilization rates for lending reserves ## Get Market Information Retrieve market-wide TVL metrics for deposits and borrows. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > > console.log({ > totalDepositsUsd: market!.getTotalDepositTVL().toFixed(2), > totalBorrowsUsd: market!.getTotalBorrowTVL().toFixed(2), > }); > ``` > > View Code ## Get Reserve Supply and Borrow APY Fetch historical supply APY and borrow APY data for a specific reserve over time. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const marketPubkey = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; > const reservePubkey = '37Jk2zkz23vkAYBT66HM2gaqJuNg2nYLsCreQAVt5MWK'; > > const params = new URLSearchParams({ > start: '2026-10-15T00:00:00.000Z', > end: '2026-10-22T00:00:00.000Z', > frequency: 'day', > }); > > const res = await fetch( > `${API_BASE_URL}/kamino-market/${marketPubkey}/reserves/${reservePubkey}/metrics/history?${params}` > ); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > > const { history } = await res.json(); > > console.table( > history.map((item) => ({ > date: item.timestamp.slice(0, 10), > symbol: item.metrics.symbol, > supplyAPY: `${(item.metrics.supplyInterestAPY * 100).toFixed(2)}%`, > borrowAPY: `${(item.metrics.borrowInterestAPY * 100).toFixed(2)}%`, > depositTvlUsd: Number(item.metrics.depositTvl).toFixed(2), > borrowTvlUsd: Number(item.metrics.borrowTvl).toFixed(2), > })) > ); > ``` > > View Code ## Get Reserve Information Check detailed metrics for all reserves including supply APY, borrow APY, deposit TVL, borrow TVL, and utilization rates. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const reserves = market!.getReserves().map((reserve) => ({ > symbol: reserve.getTokenSymbol(), > kind: reserve.getKind().toString(), > supplyAPY: `${(reserve.totalSupplyAPY(ledgerInstant) * 100).toFixed(2)}%`, > borrowAPY: `${(reserve.totalBorrowAPY(ledgerInstant) * 100).toFixed(2)}%`, > utilization: `${(reserve.calculateUtilizationRatio() * 100).toFixed(2)}%`, > depositTvlUsd: reserve.getDepositTvl().toFixed(2), > borrowTvlUsd: reserve.getBorrowTvl().toFixed(2), > })); > > console.table(reserves); > ``` > > > [!NOTE] > > > > A token can have several reserves: one variable-rate reserve plus fixed-rate ones, so each row shows its kind. Fixed-rate APYs depend on the slot duration passed to `KaminoMarket.load`. A hard-coded value such as 400 ms shows them at about half their real rate, because mainnet slots are closer to 210 ms. > > View Code ## Get Reserve Reward History Fetches historical KLend reward metrics for a specific deposit and borrow reserve pair. > [!NOTE] > > This endpoint returns KMNO reward incentives for specific deposit and borrow reserve combinations. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const depositReservePubkey = 'd4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q'; > const borrowReservePubkey = 'D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59'; > > const params = new URLSearchParams({ > start: '2025-11-07T00:00:00.000Z', > end: '2025-11-14T23:59:59.999Z', > frequency: 'day', > }); > > const res = await fetch( > `${API_BASE_URL}/klend/${depositReservePubkey}/${borrowReservePubkey}/rewards/history?${params}` > ); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > > const rewards = await res.json(); > > console.table( > rewards.map((item) => ({ > date: item.timestamp.slice(0, 10), > rewardToken: item.rewardTokenMint, > rewardAPY: `${(item.rewardApy * 100).toFixed(2)}%`, > })) > ); > ``` > > > [!NOTE] > > > > The endpoint only returns rows for windows when the pair had KMNO incentives. Other windows return an empty array. > > View Code ## Get User Obligation Info Retrieve detailed obligation information including deposits, borrows, and health metrics. > [tab] TypeScript > > ```typescript expandable theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > VanillaObligation, > PROGRAM_ID, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const userAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligation = await market!.getObligationByWallet(userAddress, new VanillaObligation(PROGRAM_ID)); > > if (!obligation) { > console.log('No obligation found for user:', userAddress); > } > > const positions = [ > ...obligation!.getDeposits().map((position) => ({ side: 'deposit', ...position })), > ...obligation!.getBorrows().map((position) => ({ side: 'borrow', ...position })), > ]; > > console.table( > positions.map((position) => ({ > side: position.side, > symbol: market!.getReserveByAddress(position.reserveAddress)?.getTokenSymbol(), > amount: position.amount.div(position.mintFactor).toFixed(6), > valueUsd: position.marketValueRefreshed.toFixed(2), > })) > ); > > console.log({ > ltv: `${obligation!.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > liquidationLtv: `${obligation!.refreshedStats.liquidationLtv.mul(100).toFixed(2)}%`, > borrowUtilization: `${obligation!.refreshedStats.borrowUtilization.mul(100).toFixed(2)}%`, > }); > ``` > > View Code ## Get All User Obligations Retrieve all obligations for a user wallet, including different obligation types across the market. > [tab] TypeScript > > ```typescript expandable theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > ObligationTypeTag, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const userAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligations = await market!.getAllUserObligations(userAddress, await getCurrentLedgerInstant(rpc)); > > if (obligations.length === 0) { > console.log('No obligations found for wallet:', userAddress); > } > > for (const obligation of obligations) { > console.log(`\nObligation ${obligation.obligationAddress} (${ObligationTypeTag[obligation.obligationTag]})`); > console.table( > [ > ...obligation.getDeposits().map((position) => ({ side: 'deposit', ...position })), > ...obligation.getBorrows().map((position) => ({ side: 'borrow', ...position })), > ].map((position) => ({ > side: position.side, > symbol: market!.getReserveByAddress(position.reserveAddress)?.getTokenSymbol(), > amount: position.amount.div(position.mintFactor).toFixed(6), > valueUsd: position.marketValueRefreshed.toFixed(2), > })) > ); > console.log({ > ltv: `${obligation.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > liquidationLtv: `${obligation.refreshedStats.liquidationLtv.mul(100).toFixed(2)}%`, > }); > } > ``` > > View Code ## Get All Obligations by Reserve Retrieve all obligations that have deposits in a specific reserve. Useful for analyzing reserve utilization and user exposure. > [tab] TypeScript > > ```typescript expandable theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > ObligationTypeTag, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const reserveAddress = address('37Jk2zkz23vkAYBT66HM2gaqJuNg2nYLsCreQAVt5MWK'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligations = await market!.getAllObligationsByDepositedReserve( > reserveAddress, > await getCurrentLedgerInstant(rpc) > ); > > console.log(`Found ${obligations.length} obligations with deposits in this reserve`); > > console.table( > obligations.map((obligation) => ({ > obligation: obligation.obligationAddress, > type: ObligationTypeTag[obligation.obligationTag], > depositUsd: obligation.getDepositByReserve(reserveAddress)?.marketValueRefreshed.toFixed(2), > totalBorrowsUsd: obligation.refreshedStats.userTotalBorrow.toFixed(2), > ltv: `${obligation.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > })) > ); > ``` > > > [!WARNING] > > > > This reads every obligation in the market. Public RPC endpoints reject it, so use a private RPC. > > View Code ## Get User Transaction History Access all transaction history for a user's wallet across deposits, borrows, repayments, and liquidations. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const marketPubkey = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; > const userPubkey = 'EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'; > > const res = await fetch(`${API_BASE_URL}/v2/kamino-market/${marketPubkey}/users/${userPubkey}/transactions`); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > > const transactionsByObligation = await res.json(); > > for (const [obligation, transactions] of Object.entries(transactionsByObligation)) { > console.log(`\nObligation ${obligation}`); > console.table( > transactions.map((tx) => ({ > date: tx.createdOn.slice(0, 10), > type: tx.transactionName, > token: tx.liquidityToken, > amount: tx.liquidityTokenAmount, > usdValue: Number(tx.liquidityUsdValue).toFixed(2), > })) > ); > } > ``` > > > [!NOTE] > > > > Results are grouped by obligation address. A market where the wallet has no obligation returns an empty object. > > View Code # Flash Loans Source: https://docs.kamino.com/build/borrow/multiply/flash-loans Execute atomic flash loan transactions on Kamino ## Flash Loans > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > none, > assertIsTransactionWithinSizeLimit, > } from '@solana/kit'; > import { > KaminoMarket, > PROGRAM_ID, > getFlashLoanInstructions, > getAssociatedTokenAddress, > getMedianSlotDurationInMsFromLastEpochs, > } 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 2** > > ### Setup Market and Signer > > Load your keypair, initialize RPC connections, and load the Kamino market. > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Configure Flash Loan Parameters > > Set the token, the flash loan amount in lamports (1 USDC), and the wallet's token account that receives it. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const flashLoanAmount = new Decimal(1_000_000); > const usdcAta = await getAssociatedTokenAddress(usdcMint, signer.address, usdcReserve.getLiquidityTokenProgram()); > ``` > > **Step 4** > > ### Build Flash Loan Instructions > > Generate the flash borrow and flash repay instructions using the Kamino SDK. > > ```typescript theme={"theme":"css-variables"} > 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, > }); > ``` > > > [!NOTE] > > > > `borrowIxIndex: 0` says 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. > > > [!NOTE] > > > > The flash repay takes the amount plus the reserve's flash loan fee (`reserve.state.config.fees.flashLoanFeeSf`, 0.001% for USDC on the SOL/BTC Market). The wallet must already hold enough USDC in that token account to pay the fee, or the repay fails with insufficient funds. > > **Step 5** > > ### 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={"theme":"css-variables"} > const memoIx = getAddMemoInstruction({ memo: 'Hello Kamino' }); > > const allInstructions = [flashBorrowIx, memoIx, flashRepayIx]; > ``` > > **Step 6** > > ### Build and Send Transaction > > Build the transaction with a fresh blockhash and send it to the network. > > ```typescript theme={"theme":"css-variables"} > 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(allInstructions, tx) > ); > > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: false, > }); > > console.log('Flash loan successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > Your flash loan transaction is complete! The borrowed funds were used for your operations and automatically repaid within the same atomic transaction. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Fetch Reserve Data > > ```rust theme={"theme":"css-variables"} > use klend_interface::helpers; > use klend_interface::ReserveInfo; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > let reserve_data = rpc_client.get_account(&reserve_pubkey)?; > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; > ``` > > > [!NOTE] > > > > Use `ReserveInfo::from_account_data(pubkey, &data)` to construct reserve info from raw RPC account bytes. > > **Step 4** > > ### Derive Token Accounts > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > let user_token_account = get_associated_token_address(&owner, &reserve.liquidity_mint); > ``` > > **Step 5** > > ### Build Flash Loan Instructions > > ```rust theme={"theme":"css-variables"} > let (borrow_ix, repay_ix) = helpers::flash::flash_loan( > owner, > &reserve, > user_token_account, // source for repayment > user_token_account, // destination for borrowed funds > 1_000_000, // 1 USDC (6 decimals) > 0, // borrow instruction index in the transaction > None, // no referrer > ); > ``` > > > [!NOTE] > > > > The `borrow_instruction_index` parameter specifies the position of the flash borrow instruction in the final transaction. Set to `0` if it is the first instruction. > > **Step 6** > > ### Compose and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > // Insert your custom instructions between borrow and repay > let your_custom_instructions = vec![/* your logic here */]; > > let mut all_instructions = vec![borrow_ix]; > all_instructions.extend(your_custom_instructions); > all_instructions.push(repay_ix); > > let message = Message::new(&all_instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Flash loan successful! Signature: {signature}"); > ``` > > > [!NOTE] > > > > The flash borrow and repay must be in the same transaction. You can insert any number of instructions between them. # Leverage Concepts Source: https://docs.kamino.com/build/borrow/multiply/leverage-concepts Understanding how Multiply creates leveraged positions through atomic looping with flash loans ## What is Multiply? Multiply creates leveraged positions in a single atomic transaction by automating the looping process through flash loans. Instead of manually executing 8-10 separate deposit-borrow-swap cycles, Multiply collapses the entire leverage-building process into one transaction that either succeeds completely or reverts with no state changes. ### Borrow and Multiply SDK Methods | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid | | `getWithdrawWithLeverageIxs` | Deleverage and withdraw | Sell collateral to repay debt and receive remaining value in wallet | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | > [!NOTE] > > **Multiply operations** use `MultiplyObligation`. **Standard borrow operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. *** ## SDK vs API: What's Available Understanding which operations require the SDK versus the API is critical for building Multiply integrations. | Operation | SDK | API | Notes | | - | - | - | - | | **Flash Loans** | Required | Not available | Atomic transactions — SDK only | | **Multiply Deposit (with KSwap)** | Required | Not available | Leveraged positions with swap routing — SDK only | | **Standard Borrow Operations** | Available | Available | Deposit, borrow, repay, withdraw — both SDK and API | | **Position Data** | Available | Available | Read obligation data via SDK or API | | **Market Reserve Data** | Available | Available | APYs, utilization, liquidity via SDK or API | ## Flash Loans A flash loan is an uncollateralized loan that must be borrowed and fully repaid within the same transaction block. This atomic property makes flash loans risk-free for the protocol. ### Flash Loan Properties | Property | Description | | - | - | | **Collateral Required** | None — uncollateralized | | **Repayment Window** | Same transaction block | | **Failure Behavior** | Entire transaction reverts (no state changes) | | **Fee** | 0.001% per transaction | | **Risk to Protocol** | Zero — atomicity guarantees repayment or reversion | > [!NOTE] > > If a flash loan cannot be repaid — due to slippage, insufficient liquidity, or any other failure — the entire transaction reverts. No intermediate state is committed to the blockchain. *** ## Looping: Manual vs Atomic Looping is the process of repeatedly depositing collateral, borrowing against it, and reinvesting the borrowed funds to amplify exposure. The method determines risk, cost, and execution complexity. ### Comparison Table | Aspect | Manual Looping | Atomic Looping (Multiply) | | - | - | - | | **Transaction Count** | 8-10 separate transactions | 1 atomic transaction | | **Price Exposure** | Exposed to price changes between each step | No exposure — all steps execute atomically | | **Slippage Risk** | Slippage on each swap individually | Single consolidated slippage check | | **Gas Costs** | Higher — multiple transactions | Lower — single transaction | | **Execution Risk** | High — any step can fail independently | Low — all-or-nothing execution | | **Time to Complete** | Minutes (dependent on block confirmations) | Single block (\~400ms on Solana) | | **Complexity** | Requires manual coordination of steps | Fully automated | > [!WARNING] > > Manual looping exposes you to market price movements between transactions. If the collateral asset price drops or borrow rates spike mid-loop, you may end up with a worse position than intended — or fail to complete the loop entirely. *** ## The Multiply Transaction Flow Multiply executes leverage creation in a precise sequence of steps within a single atomic transaction. **1. Flash Borrow** Protocol borrows the required debt token amount (e.g., SOL) via flash loan. No collateral is required. **2. Swap to Collateral** Flash-borrowed funds are swapped into the target collateral asset (e.g., SOL → JitoSOL) using Kamino Swap (KSwap) with multi-DEX routing for optimal execution. **3. Deposit Collateral** The full collateral amount (user deposit + swapped amount) is deposited into Kamino Lend as collateral. **4. Borrow Against Collateral** With collateral deposited, the protocol borrows the debt token against the collateral position. **5. Repay Flash Loan** Borrowed funds are used to repay the flash loan plus the 0.001% fee. **6. Position Established** Net result: Leveraged position with amplified collateral exposure and outstanding debt balance recorded on Kamino Lend. > [!NOTE] > > All steps execute in a single transaction. If any step fails (slippage exceeds tolerance, insufficient liquidity, etc.), the entire transaction reverts and no position is created. *** ## eMode (Elevation Mode) eMode enables significantly higher leverage for correlated asset pairs by raising the maximum permitted LTV ratio. ### How eMode Works Standard lending markets limit LTV to protect against price divergence between collateral and debt. When both assets are highly correlated (e.g., JitoSOL and SOL), price divergence risk is minimal — both assets move together. eMode reflects this reduced risk by permitting higher LTV ratios. ### eMode Leverage Comparison | Mode | Asset Pair | Max LTV | Max Leverage | Use Case | | - | - | - | - | - | | **Standard** | SOL / USDC | 75% | 4x | Uncorrelated assets | | **eMode (Main)** | mSOL, bSOL, JupSOL / SOL | \~87% | \~7.7x | Correlated LST/SOL pairs | | **eMode (Jito)** | JitoSOL / SOL | 90% | 10x | JitoSOL-specific correlation | | **No eMode** | JLP / USDC | 67% | \~3.2x | Uncorrelated (JLP is basket of assets) | > [!WARNING] > > Higher LTV from eMode means a smaller buffer between your operating LTV and liquidation threshold. Operating near maximum eMode leverage requires continuous monitoring of the yield spread (collateral yield minus borrow rate). ### Why Correlation Matters **Correlated pairs (LST/SOL)**: When SOL price moves, both JitoSOL and SOL debt move proportionally. Your LTV ratio stays relatively stable regardless of SOL's USD price. **Uncorrelated pairs (JLP/USDC)**: JLP value fluctuates with crypto markets while USDC stays flat. Price drops in SOL/ETH/BTC directly increase your LTV, creating liquidation risk independent of borrow rates. # Monitor Position Health Source: https://docs.kamino.com/build/borrow/multiply/monitor-position-health Monitor LTV, leverage, and liquidation risk for your 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 > [tab] SDK > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication and Kamino SDK operations. > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > ObligationTypeTag, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > Initialize the RPC connection and load the xStocks market. > > ```typescript theme={"theme":"css-variables"} > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market > const walletAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Fetch Multiply Obligations > > Retrieve all multiply obligations for the wallet address using the obligation type filter. > > ```typescript theme={"theme":"css-variables"} > const obligations = await market!.getUserObligationsByTag( > ObligationTypeTag.Multiply, > walletAddress, > await getCurrentLedgerInstant(rpc) > ); > > 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. > > **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 | > | `ObligationTypeTag.MultiplyFixedRate` | 4: Multiply positions tied to specific reserves, used when a token has a fixed-rate reserve | > | `ObligationTypeTag.LendingFixedRate` | 5: Lending-only positions tied to a specific reserve | > | `ObligationTypeTag.LeverageFixedRate` | 6: Leverage positions tied to specific reserves | > > **Step 4** > > ### Read Position Health Metrics > > Access the position health statistics from each obligation's `refreshedStats`. > > ```typescript theme={"theme":"css-variables"} > console.table( > obligations.map((obligation) => { > const stats = obligation.refreshedStats; > return { > obligation: obligation.obligationAddress, > depositsUsd: stats.userTotalDeposit.toFixed(2), > borrowsUsd: stats.userTotalBorrow.toFixed(2), > netValueUsd: stats.netAccountValue.toFixed(2), > leverage: `${stats.leverage.toFixed(2)}x`, > borrowLimitUsd: stats.borrowLimit.toFixed(2), > ltv: `${stats.loanToValue.mul(100).toFixed(2)}%`, > liquidationLtv: `${stats.liquidationLtv.mul(100).toFixed(2)}%`, > }; > }) > ); > ``` > > > [!TIP] > > > > You now have access to all position health metrics including leverage, borrowing capacity, and liquidation thresholds. > [tab] API > > ```typescript theme={"theme":"css-variables"} > 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)}%`); > }); > ``` *** ## 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](/build/developers/multiply/data/concepts). # Multiply Deposit with xStocks Source: https://docs.kamino.com/build/borrow/multiply/multiply-deposit-kswap Leverage your position by borrowing and swapping to deposit more collateral A multiply deposit creates a leveraged collateral position in a single, atomic transaction by combining an initial deposit with temporary liquidity. When a multiply deposit is initiated, the protocol first temporarily borrows the debt token (for example, USDC) through a flash loan. The borrowed amount is swapped into the collateral token (for example, TSLAx) using KSwap (Kamino's token swap SDK). The resulting collateral is then deposited into Kamino Lend. With the collateral in place, the position borrows the debt token against it, and the borrowed amount is used to repay the flash loan before the transaction completes. The result is a leveraged position with increased exposure to the collateral token and an outstanding debt balance. ## Multiply Deposit with xStocks Create a leveraged position in a single atomic transaction using Klend's multiply feature and KSwap multi-route swap optimization. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, none, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, isTransactionMessageWithinSizeLimit, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, type Instruction, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoMarket, MultiplyObligation, ObligationTypeTag, PROGRAM_ID, getDepositWithLeverageIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, getUserLutAddressAndSetupIxs, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, type SwapInputs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { KswapSdk, loadRouterContext, type RouteOutput } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; import BN from 'bn.js'; import Decimal from 'decimal.js'; ``` > [!NOTE] > > Use `@kamino-finance/kswap-sdk` 2.9.0. It's the last version on `@solana/kit` 2, which `@kamino-finance/klend-sdk` 13 uses; 3.x moved to kit 8. **Step 2** ### Load Configuration and Initialize SDKs ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const DEPOSIT_AMOUNT = new Decimal(10); const TARGET_LEVERAGE = new Decimal(2); const SLIPPAGE_BPS = 50; const MAX_COMPUTE_UNITS = 1_400_000; const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const collReserve = market!.getExistingFloatRateReserveByMint(collMint); const debtReserve = market!.getExistingFloatRateReserveByMint(debtMint); const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); const scope = new Scope('mainnet-beta', rpc); ``` **Step 3** ### Set Up a New Wallet The leverage functions expect the wallet's Kamino user metadata to exist. A wallet that has never used Kamino sends one setup transaction first. ```typescript theme={"theme":"css-variables"} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); const [, userMetadata] = await market!.getUserMetadata(signer.address); if (!userMetadata) { const [, setupInstructions] = await getUserLutAddressAndSetupIxs(market!, signer, none(), false); const { value: setupBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const setupTransaction = await signTransactionMessageWithSigners( pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(setupBlockhash, tx), (tx) => appendTransactionMessageInstructions(setupInstructions.flat(), tx) ) ); await sendAndConfirm(setupTransaction, { commitment: 'confirmed', skipPreflight: true }); } ``` **Step 4** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. It's `null` until the first deposit creates it. ```typescript theme={"theme":"css-variables"} const obligationAddress = await new MultiplyObligation(collMint, debtMint, PROGRAM_ID).toPda(marketPubkey, signer.address); const obligation = await market!.getObligationByAddress(obligationAddress); ``` **Step 5** ### Get Scope Price Refresh Instructions ```typescript theme={"theme":"css-variables"} const scopeRefreshIx = await getScopeRefreshIxForObligationAndReserves( market!, collReserve, debtReserve, obligation ?? undefined, { scope, scopeConfigurations: await scope.getAllConfigurations() } ); ``` **Step 6** ### Define the Swap Helpers The SDK asks for swaps through two callbacks: a quoter that prices the swap and a swapper that returns its instructions. Both use every KSwap route, sorted by output. ```typescript theme={"theme":"css-variables"} async function getRoutes(inputs: SwapInputs) { const { routes } = await kswap.getAllRoutes( { executor: signer.address, tokenIn: inputs.inputMint, tokenOut: inputs.outputMint, amount: new BN(inputs.inputAmountLamports.floor().toString()), maxSlippageBps: SLIPPAGE_BPS, swapType: 'exactIn', wrapAndUnwrapSol: false, }, await loadRouterContext(rpc, inputs.inputMint, inputs.outputMint) ); if (routes.length === 0) { console.log('No KSwap route found for', inputs.inputMint, '->', inputs.outputMint); } return routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); } function midPrice(route: RouteOutput) { const amounts = route.amountsExactIn!; const amountIn = new Decimal(amounts.amountIn.toString()).div(new Decimal(10).pow(route.inputTokenDecimals!)); const amountOut = new Decimal(amounts.amountOut.toString()).div(new Decimal(10).pow(route.outputTokenDecimals!)); return amountOut.div(amountIn); } const quoter = async (inputs: SwapInputs) => { const [bestRoute] = await getRoutes(inputs); return { priceAInB: midPrice(bestRoute), quoteResponse: bestRoute }; }; const swapper = async (inputs: SwapInputs) => (await getRoutes(inputs)).map((route) => { const routeIxs = route.instructions!; return { preActionIxs: [], swapIxs: [ ...routeIxs.createInAtaIxs, ...routeIxs.wrapSolIxs, ...routeIxs.swapIxs, ...routeIxs.unwrapSolIxs, ...routeIxs.createOutAtaIxs, ], lookupTables: route.lookupTableAccounts ?? [], quote: { priceAInB: midPrice(route), quoteResponse: route }, }; }); ``` > [!WARNING] > > `priceAInB` must be the mid price (`amountOut / amountIn`, each in token units), before slippage. The SDK applies `slippagePct` itself, so a guaranteed or minimum-out price counts slippage twice and sizes the position wrong. `getBestRoute` currently returns no routes, so use `getAllRoutes`, which in kswap-sdk 2.9.0 takes the router context as a second argument. **Step 7** ### Build the Leverage Routes The SDK builds one candidate transaction per swap route: flash borrow USDC, swap it to TSLAx, deposit, borrow USDC, repay the flash loan. ```typescript theme={"theme":"css-variables"} const routes = await getDepositWithLeverageIxs({ owner: signer, kaminoMarket: market!, debtReserveAddress: debtReserve.address, collReserveAddress: collReserve.address, depositAmount: DEPOSIT_AMOUNT, priceDebtToColl: debtReserve.getOracleMarketPrice().div(collReserve.getOracleMarketPrice()), slippagePct: new Decimal(SLIPPAGE_BPS / 100), obligation, referrer: none(), currentLedgerInstant: await getCurrentLedgerInstant(rpc), targetLeverage: TARGET_LEVERAGE, selectedTokenMint: debtMint, obligationTypeTagOverride: ObligationTypeTag.Multiply, scopeRefreshIx, budgetAndPriorityFeeIxs: getComputeBudgetAndPriorityFeeIxs(MAX_COMPUTE_UNITS), quoteBufferBps: new Decimal(0), quoter, swapper, useV2Ixs: true, }); ``` > [!NOTE] > > `selectedTokenMint` is the token you deposit: the debt token (USDC) here, or the collateral token. `quoteBufferBps` inflates only the amount used for the quote; 0 quotes the exact swap amount and leaves price moves to the slippage setting. **Step 8** ### Fetch Lookup Tables Fetch Kamino's lookup tables for each candidate transaction, one request per candidate. ```typescript theme={"theme":"css-variables"} async function getKaminoLookupTables(instructions: Instruction[]) { const addresses = [ ...new Set(instructions.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), ]; const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addresses }), }); if (!lutResponse.ok) { console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); } const { lutAddresses } = await lutResponse.json(); return fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); } ``` > [!NOTE] > > `/luts/find-minimal` takes one transaction's worth of addresses (between 64 and 128), so a single request for all candidates is rejected. **Step 9** ### Pick the Route That Fits Compress each candidate with its route's lookup tables and Kamino's, then take the best-output one that fits in a transaction. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const candidates = await Promise.all( routes.map(async (route) => { const lookupTables = [...route.lookupTables, ...(await getKaminoLookupTables(route.ixs))]; const lookupTableAddresses: Record = Object.fromEntries( lookupTables.map((lut) => [lut.address, lut.data.addresses]) ); return pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(route.ixs, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) ); }) ); const transactionMessage = candidates.find((candidate) => isTransactionMessageWithinSizeLimit(candidate)); if (!transactionMessage) { console.log(`None of the ${candidates.length} swap routes fit in one transaction`); } ``` > [!NOTE] > > The best-output route often has too many accounts to fit, even compressed: in testing only one or two of five to ten routes did. The slippage setting covers the gap between the best route's quote and the one sent. **Step 10** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage!); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Multiply deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The 2x TSLAx position is open: TSLAx collateral with a USDC debt, created in one transaction. ## Transaction Flow > [accordion] View Transaction Flow Diagram > > ```mermaid theme={"theme":"css-variables"} > graph TD > A[Load Market & SDKs] --> B[Set Up New Wallet] > B --> C[Load Multiply Obligation] > C --> D[Refresh Scope Prices] > D --> E[Build One Candidate per Swap Route] > E --> F[Compress with Lookup Tables] > F --> G[Pick Best Route That Fits] > G --> J[Sign & Send Transaction] > > J --> K{Transaction Success?} > K -->|Yes| L[Leveraged Position Created] > K -->|No| M[Transaction Reverts] > ``` ## Asset Flow > [accordion] 2x Leveraged TSLAx Position: Step-by-Step > > **1. Initial State** > > * Wallet: 10 USDC > * Position: None > > **2. Flash Borrow** > > * Flash loan: 10 USDC (temporary) > * Available: 20 USDC total > > **3. Swap & Deposit** > > * Swap 20 USDC to TSLAx via KSwap > * Deposit TSLAx as collateral > > **4. Borrow & Repay** > > * Borrow 10 USDC against collateral > * Repay 10 USDC flash loan > > **5. Final Position** > > * Collateral: TSLAx (\$20 value) > * Debt: 10 USDC > * Net Equity: 10 USDC > * Leverage: 2x ## Key Concepts > [accordion] Flash Loans > > Flash loans are uncollateralized loans that must be borrowed and repaid within the same transaction. They enable: > > * **Zero upfront capital**: Borrow large amounts without collateral > * **Atomic execution**: All operations succeed or fail together > * **Leverage creation**: Bootstrap leveraged positions in one transaction > * **Risk-free**: Transaction reverts if flash loan cannot be repaid > [accordion] Multiply Obligation Type > > The `MultiplyObligation` is a specialized obligation type that: > > * **Defines position type**: Multiply vs Leverage vs Vanilla > * **Derives unique address**: Via PDA using collateral/debt mints > * **Supports multiple positions**: Create different obligations with same tokens using ID parameter > * **Creates new obligation**: When none exists (indicated by `obligation: null`) > [accordion] KSwap Multi-Route Optimization > > KSwap provides optimal swap execution through: > > * **Multi-DEX routing**: Tests routes across Jupiter, OKX, dFlow, and other DEX aggregators > * **Route choice**: Sorted by output; the best-output route that fits in one transaction is sent > * **Slippage protection**: Each route enforces a minimum output within the slippage setting > * **Automatic ATA creation**: Handles token account creation and SOL wrapping/unwrapping ### Borrow and Multiply SDK Methods | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid | | `getWithdrawWithLeverageIxs` | Shrink the position and withdraw | Take value out while keeping the position's LTV; leverage stays the same | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | > [!NOTE] > > **Multiply operations** use `MultiplyObligation`. **Vanilla operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. ## Related Resources > [card] [Deposit and Borrow](/build/tutorials/borrow/deposit-and-borrow) > > Learn basic deposit and borrow operations > [card] [Market Data](/build/developers/borrow/data/market-data) > > Read market metrics and reserve data > [card] [KSwap SDK](https://www.npmjs.com/package/@kamino-finance/kswap-sdk) > > Multi-DEX swap routing SDK > [card] [Scope SDK](https://github.com/Kamino-Finance/scope-sdk) > > Oracle price aggregation SDK # Plan Your Market Source: https://docs.kamino.com/build/borrow/plan-your-market Understand the decisions a curator makes when designing and operating a Kamino lending market A Kamino lending market brings together a curated set of assets that users can supply and borrow. The curator chooses those assets and sets the parameters that govern how the market operates. Each market is isolated, so its exposure remains separate from other Kamino lending markets. ![Kamino curators markets list](https://mintcdn.com/kamino-3d73a151/Kr04J8Tty1aPhdQ2/images/curators/markets/markets-list.webp?fit=max\&auto=format\&n=Kr04J8Tty1aPhdQ2\&q=85\&s=3a827f2f1e7031eacd8de6cbb1a0c1a5) By the end of this guide Curators should understand: * What a Kamino lending market does * What to consider when choosing assets for a market * The relationship between risk settings and evolving market conditions * The ownership and emergency roles within a market * When to expand market liquidity as lending and borrowing activity grows *** ## A Market in One Example Planning a market starts with understanding how all its core components work together. Consider a market with SOL and USDC reserves, which will be used throughout this guide. Each reserve has its own configuration that determines whether users can supply or borrow the asset and whether it can be used as collateral. ![Lending market flow: supply, borrow, price fall, liquidation](https://mintcdn.com/kamino-3d73a151/08Y-TFxV_VC5bdgE/images/curators/markets/market-lending-flow.webp?fit=max\&auto=format\&n=08Y-TFxV_VC5bdgE\&q=85\&s=6930595d8d514a35fa8d6a1748021995) Lenders supply USDC to the market and earn interest when that USDC is borrowed. A borrower can access that liquidity by depositing SOL as **collateral** and borrowing USDC against it. Suppose a borrower deposits 100 SOL worth \$20,000 and borrows \$12,000 USDC. The position has an **LTV of 60%**: \$12,000 of debt against \$20,000 of collateral. If the SOL reserve has a maximum LTV of 70%, the borrower could borrow up to \$14,000. ![100 SOL collateral, \$12,000 USDC borrowed, 60% LTV with remaining capacity](https://mintcdn.com/kamino-3d73a151/08Y-TFxV_VC5bdgE/images/curators/markets/market-ltv-breakdown.webp?fit=max\&auto=format\&n=08Y-TFxV_VC5bdgE\&q=85\&s=0c0c0b9338b55fa1867179b233f1d694) The position remains healthy until it reaches the **liquidation threshold**. At a threshold of 75%, the \$12,000 debt becomes eligible for liquidation when the value of the SOL collateral falls to \$16,000, or \$160 per SOL. A **liquidator** can then repay part of the borrower's debt in exchange for some of their SOL collateral. To make liquidation worthwhile, the liquidator receives slightly more collateral than the value of the debt they repay. This difference is the **liquidation bonus**. With an 8% liquidation bonus, a liquidator who repays \$1,000 of USDC debt receives \$1,080 worth of SOL. The **close factor** determines how much of the borrower's debt can be repaid in a single liquidation. With a 20% close factor, a position with \$12,000 of outstanding debt can have up to **\$2,400 repaid in one liquidation**. The **oracle** provides the prices used to value the borrower's SOL collateral and USDC debt. As those prices change, the position's LTV changes with them, which determines when the position reaches the liquidation threshold. **Caps** limit how large the market can grow. A deposit cap limits how much SOL can be supplied to the reserve, while a borrow cap limits how much USDC can be borrowed from it. If the value of SOL falls too quickly for the position to be liquidated in time, the collateral may no longer be worth enough to repay the debt. The remaining shortfall becomes **bad debt**, reducing the amount USDC lenders can withdraw from the reserve. Knowledge Check A curator should be able to: * Understand how collateral price movements influence borrowing capacity. * Understand how curator settings determine when a position becomes eligible for liquidation. *** ## Who Participates in a Lending Market A market can support three main types of users: lenders, borrowers, and loopers. Each interacts with the market differently and introduces a different kind of demand and risk. **Lending.** Lenders supply assets such as USDC to earn interest. They provide the liquidity borrowers use, and their main risk is that losses in the reserve can reduce the amount they are able to withdraw. **Borrowing.** Borrowers deposit collateral and borrow another asset against it. They create demand for the liquidity supplied by lenders, and they take on liquidation risk if the value of their collateral falls too far. **Looping.** Loopers deposit SOL, borrow USDC against it, use that USDC to buy more SOL, and repeat. This lets them increase their exposure beyond what their starting capital would normally allow. Because each loop involves buying more SOL, sufficient market liquidity is needed for positions to open efficiently. If the collateral also earns staking yield, that yield applies to the larger position as well. Kamino Multiply automates the repeated borrow-and-buy loop in a single transaction. In a SOL/USDC market dominated by loopers, many users may be borrowing USDC to buy more SOL. As more of the supplied USDC is borrowed, utilisation rises, meaning a larger share of the USDC in the reserve is already in use and less remains available. Kamino's risk controls are designed to keep this exposure within manageable bounds. If SOL falls sharply, many looped positions may need to unwind around the same time. Loopers may sell SOL to repay USDC, while liquidators may also sell SOL received from unhealthy positions. This concentrates activity around the same assets and is one reason curators need to consider available liquidity when configuring a looping-heavy market. Knowledge Check A curator should be able to: * Identify what lenders, borrowers, and loopers do. * Understand how each participant affects the market. *** ## What Curators Should Consider Before Launch Before launch, a curator needs to understand how much risk the market can safely support and configure it around those limits. ### Risk Lenders and borrowers take on different risks. In the SOL/USDC example, lenders supply USDC to earn interest and do not depend on SOL increasing in value. The borrower deposits SOL as collateral instead of selling it, so they continue to benefit if SOL rises but also bear the loss if SOL falls. If the collateral loses value, the position moves closer to its health limit, the point where its collateral is no longer sufficient relative to its debt. That does not mean USDC lenders are completely insulated from the risk of SOL's price falling. Their protection depends on the borrower's collateral remaining sufficient to cover the outstanding debt. Kamino uses a buffer between the maximum LTV and the health limit so positions have room to absorb price movement before liquidation is required. If the position reaches that limit, liquidation is designed to reduce the debt while the collateral can still cover it. If a shortfall still remains, it becomes bad debt in the USDC reserve and can reduce the amount lenders are able to withdraw. Worth checking * Who is lending and who is borrowing. * What borrowers are using the borrowed asset for. * Whether many borrowers are exposed to the same underlying trade. * Who would ultimately absorb a loss if collateral no longer covers the debt. > [card] [Risk parameters](/curators/markets/risk-parameters) > > LTV, thresholds, IR curves, and caps for each reserve. > [card] [Market risk](/risk/market-risk) > > Measured risk data across Kamino markets. ### Liquidity and Volatility A position can only be closed safely if there is enough market liquidity to sell the collateral without moving its price too far. **Liquidity** measures how much the price changes when collateral is sold, and curators need to look at that price impact at the sizes a liquidation may actually need to execute. Available liquidity helps determine how large positions the market can safely support. Reserve caps and liquidation parameters should be set so collateral can be sold at expected liquidation sizes without price impact overwhelming the liquidation bonus. **Volatility** measures how quickly the collateral price can move. More volatile assets need more room between the maximum LTV and the health limit so a position has time to be liquidated before the collateral value falls too far. Worth checking * Whether the collateral asset has enough market liquidity to be sold without significant price impact. * How sharply the collateral asset has moved during previous periods of volatility. * Whether that liquidity depends on incentives, and how much would remain if those incentives ended. * Whether the proposed reserve caps are appropriate for the collateral asset's available market liquidity. > [!TIP] > > Use the [KRAF risk dashboard ↗](https://risk.kamino.finance/) to review liquidity and volatility data for the collateral asset when setting reserve parameters. > [card] [Volatility](/risk/market-risk/volatility) > > Measured volatility data. > [card] [Liquidity](/risk/market-risk/liquidity) > > On-chain liquidity analysis. > [card] [KRAF dashboard](https://risk.kamino.finance/) > > Live risk dashboard. ### Token and Oracle Risk Before adding an asset to a market, a curator needs to understand both **the risks of the token itself** and **how its value will be determined onchain**. A token can introduce risks through its minting, transfer, or administrative controls, while the oracle determines the price Kamino uses to value collateral and debt. **The token.** If new tokens can still be created, the curator needs to understand who controls that authority and how securely it is managed. If minting were abused, someone could create a large amount of the token, deposit it as collateral, and borrow another asset against it. The debt asset's borrow cap also limits how much value can be borrowed from the market. Even if the collateral supply increases significantly, borrowing cannot exceed the cap set on the debt reserve. Curators should also review any **freeze, upgrade, or transfer controls** that could affect how the token behaves after the market is live. **The oracle.** The oracle determines the value Kamino uses for collateral and debt, so choosing the right price source is part of the market's risk design. For a liquid asset such as SOL, a market price may be appropriate. An RWA may instead rely on **Net Asset Value (NAV)**, while a **Liquid Staking Token (LST)**, which represents a staked asset plus the rewards it accrues, may use its staking exchange rate. Whichever source is used, the price needs to stay current. If an oracle updates too slowly, Kamino may be working from a value that no longer reflects the market during a fast price move. The market should also have a way to handle a price feed becoming unavailable or reporting an unexpected value. Using more than one independent price source, together with rules for stale or conflicting prices, can make the oracle setup more resilient. Worth checking * Whether the token has a **mint authority** or **freeze authority**, and who controls them. * If new tokens can still be issued, how securely the minting process is managed. * Which **price feeds** are configured for the asset, and what happens if one becomes stale or unavailable. * Whether the chosen oracle setup matches how the asset is actually valued, such as market price, NAV, or a staking exchange rate. > [card] [Asset risk](/risk/asset-risk) > > Token risk, oracle pricing, depeg analysis. > [card] [Configuring oracles](/curators/markets/configuring-oracles) > > Wire each reserve to a Scope price feed. ### Market Authority and Controls Curators should choose who holds the market owner and emergency council roles, and understand how quickly each role can make changes to the market. Changes to market and reserve settings made by the market owner are delayed by a timelock, giving signers time to review them and respond if a key or device has been compromised. The emergency council can act immediately, but only through a limited set of protective controls, so it can contain an incident without having full authority over the market. | Role | What it can do | How quickly it can act | | - | - | - | | **Market owner** | Can change market and reserve settings | Changes go through the owner multisig and timelock | | **Emergency council** | Can make a limited set of protective changes that restrict market activity | Can act immediately without the owner timelock | | **Proposer authority** | Can configure a reserve before its first deposit | Only applies during initial reserve setup | The emergency council cannot restore normal operation after using these controls. Reversing those protective changes requires the market owner and is subject to the owner timelock. Market changes should be protected by strong signing and approval controls. Curators should design the signing process so that no single compromised signer or device can change the market on its own. Sensitive changes can sit behind a multisig and timelock, while independent verification and external alerts help catch anything unexpected. A timelock slows down parameter changes, so reserve caps should be set conservatively to keep the market safe during that delay. If a change is needed, the curator may have to wait for the timelock to expire before new parameters take effect, while the emergency council can only take protective actions such as disabling parts of the market. Worth checking * Whether the multisig has enough independent signers and an appropriate approval threshold. * Whether signers use dedicated devices for approving market changes. * How long the owner multisig timelock is, since that delay affects how conservatively reserve caps should be set. * Whether the emergency council is configured and ready to act if needed. * Whether external alerts are in place and someone is responsible for monitoring them outside normal hours. > [card] [Transfer to multisig](/curators/markets/transfer-to-multisig) > > Move ownership from a hot wallet to Squads. > [card] [Emergency council](/curators/markets/emergency-council) > > Set up the emergency authority. > [card] [Emergency controls](/curators/markets/emergency-controls) > > Pause, freeze, and socialize loss. *** ## Assessing Market Configuration Curators should align the market's configuration with its expected risk and operating conditions. ### Setting Risk Parameters Each reserve in a market has its own configuration, and each parameter governs a different part of how that reserve behaves. | Parameter | Depends on | Sets | | - | - | - | | LTV ratio and liquidation threshold | Collateral volatility and liquidity | How much can be borrowed against the collateral and when a position becomes eligible for liquidation | | Interest rate curve | Target utilisation | The cost of borrowing as reserve utilisation changes | | Deposit and borrow caps | Available collateral liquidity and timelock constraints | How much exposure the reserve can support | | Withdrawal caps | Expected withdrawal activity | How quickly funds can leave the reserve | | Liquidation bonus | Price impact at expected liquidation sizes | The incentive available to liquidators | Reserve caps should be checked against the amount of collateral that may need to be liquidated. The collateral asset should have enough available liquidity for those liquidations to execute without price impact overwhelming the liquidation bonus. Worth checking * Whether the **LTV and liquidation threshold** leave enough room for the collateral asset's observed volatility. Use the proposed reserve parameters together with KRAF volatility data. * Whether the **expected liquidation size** can be sold without excessive price impact. Use KRAF liquidity data for the collateral asset. * Whether the **reserve caps** remain conservative enough during the owner multisig timelock. * Whether the **liquidation bonus** is sufficient relative to the expected price impact at that liquidation size. > [card] [Risk parameters](/curators/markets/risk-parameters) > > Full parameter reference and recommended values. > [card] [Withdrawal caps](/curators/markets/withdrawal-caps) > > Throttle deposits, withdrawals, and debt activity. > [card] [Liquidations](/curators/markets/liquidations) > > Close factor, bonuses, and bad-debt handling. ### Oracle Configuration Each reserve needs an oracle configuration that reflects how its asset should be valued. Kamino Lend uses Scope, Kamino's oracle aggregator, to price reserve assets. Curators choose the Scope price feed that best reflects how each asset should be valued. Curators can also configure safeguards that determine when a reserve should stop accepting an oracle price. These safeguards are disabled by default and need to be configured explicitly. | Setting | What it does | | - | - | | **Heuristic bounds** | Sets a minimum and maximum accepted price | | **TWAP divergence** | Limits how far the current price can deviate from the time-weighted average price | | **Price age** | Sets how long a price can go without updating before it is rejected | | **Block price usage** | Prevents the reserve from using its oracle price until the setting is changed | > Heuristic bounds are manually configured minimum and maximum prices that an oracle price is allowed to fall within. They do not protect against unlimited minting because an increase in token supply may not change the reported oracle price. Reserve caps provide a separate limit on how much exposure the market can take on. Worth checking * Whether a suitable **Scope price feed** exists for the reserve asset. * Whether the **heuristic bounds** allow plausible price movement while still rejecting clearly erroneous values. * Whether the **TWAP divergence limit** can catch an unusual gap between the current price and its recent average, and whether the **price age limit** rejects a feed that has stopped updating. * Whether `block_price_usage` has been tested before launch by the authority responsible for using it. > [card] [Configuring oracles](/curators/markets/configuring-oracles) > > Wire each reserve to a Scope price feed with TWAP guards. > [card] [Scope oracle types](/curators/markets/scope-oracle-types) > > Composition types for fixed-income, multi-source, and LST assets. *** ## Steps to Taking the Market Live Curators bring a market live through a defined sequence of setup steps. **1. Create the market** Create the lending market. This initializes the `LendingMarket` account that will contain the market's reserves and configuration. See [Creating a market](/curators/markets/creating-a-market). ![Create Market modal](https://mintcdn.com/kamino-3d73a151/_kBsgfUkJCUTJS4M/images/curators/markets/create-market-modal.webp?fit=max\&auto=format\&n=_kBsgfUkJCUTJS4M\&q=85\&s=cf7d7a7c69c53911be939cc5c239edaf) **2. Add reserves** Add the reserves the market will support. One reserve per token mint per market. Typically, one reserve is added for the collateral asset and another for the asset users borrow. See [Adding reserves](/curators/markets/adding-reserves). **3. Make the seed deposit** Make the initial deposit into each reserve. A reserve must receive its first deposit before its configuration can be updated. **4. Set risk parameters** Set the reserve risk parameters for each reserve. See [Risk parameters](/curators/markets/risk-parameters). **5. Configure the oracle** Connect each reserve to its Scope price feed. See [Configuring oracles](/curators/markets/configuring-oracles). **6. Transfer ownership to the multisig** Transfer market ownership from the setup wallet to the owner multisig. See [Transfer to multisig](/curators/markets/transfer-to-multisig). **7. Set the emergency council** Assign the emergency council for the market. See [Emergency council](/curators/markets/emergency-council). **8. Turn on alerting** Turn on external alerting for the market. Host it separately from the curator's own systems so a compromise cannot disable the alerts. **9. Open with initial reserve caps** Open the market with lower initial reserve caps. These limits control how much can be deposited into and borrowed from each reserve, and can be raised gradually as the market begins operating. **Liquidator coverage.** Liquidations are permissionless, so a new market is not guaranteed active liquidator coverage. Curators should confirm coverage before the market goes live. Liquidator tooling is open source, so curators can run their own if needed. **Collateral liquidity.** If the market is intended to support looping, there needs to be enough liquidity to buy the collateral asset. Liquidations also require enough liquidity to sell it. Curators should confirm that liquidity is available before the market goes live and again before raising reserve caps. Curators should increase reserve caps gradually after the market goes live. Each increase should follow a waiting period and be based on how the reserves are performing. > [card] [Lifecycle](/curators/markets/lifecycle) > > The full path from create to operate. > [card] [Quickstart](/curators/markets/quickstart) > > Stand up a working market on staging in \~10 minutes. > [card] [Market settings](/curators/markets/market-settings) > > Market-level parameters and flags. *** ## Managing the Live Market Once the market is live, curators can evaluate how each reserve is performing and decide when its configuration needs to change. ### Monitor and Adjust Curators should monitor live reserve conditions to see whether the assumptions behind the configuration still hold. What to watch * **Utilisation.** Watch whether reserve utilisation is approaching the point on the interest rate curve where borrowing rates begin rising sharply. If utilisation stays too high, most of the reserve liquidity is already borrowed, leaving less available for withdrawals. * **Concentration.** Watch how much of the reserve's borrowing is concentrated in its largest positions. If one position represents a large share of the borrow cap, a single liquidation could be much larger than expected and place more pressure on available collateral liquidity. * **Oracle health.** Watch for stale price updates or unusual differences between the current oracle price and its **time-weighted average price (TWAP)**. If borrowing stops unexpectedly, check whether an oracle safeguard has been triggered. * **Liquidity.** Recheck how much of the collateral asset can be bought or sold without significant price impact. If that liquidity is incentive-driven, watch for changes as incentives decline or end. Curators should define when each monitored condition requires action, so changes in reserve performance have a clear response. Reserve cap increases are configuration changes, so they must be approved through the same authority and timelock used for other reserve updates. > [card] [Market data](/curators/markets/market-data) > > Query reserve and market state. > [card] [Reserve management](/curators/markets/reserve-management) > > Edit reserve configurations after launch. ### Incident Response In each case the first move stops the exposure growing. The cause gets dealt with after. **Price feed wrong or stale** \ **Signal:** divergence alert, staleness alert, or a price that does not match other venues. \ **First move:** `block_price_usage` on the affected reserve. Emergency council, no timelock. **Collateral token compromised** \ **Signal:** unexpected change in supply, public disclosure, or a mint from an authority believed revoked. \ **First move:** borrow cap to 0 and LTV to 0. Emergency council. **Position underwater, nobody liquidating** \ **Signal:** a position above its liquidation threshold that just sits there. \ **First move:** measure the gap at real fill prices. If the bonus no longer covers impact, raise it (owner action, waits on timelock). `socialize_loss` comes last. **Signer compromised** \ **Signal:** a proposal nobody created, or an approval from an unexpected signer. \ **First move:** market emergency mode or borrowing disabled. Emergency council. Then rotate the multisig. > [!WARNING] > > Alerting should run outside the curator's own hosting. A compromise that reaches the curator's systems would otherwise switch off the alerts reporting it. The incident contact at Kamino should be agreed before launch. > [card] [Emergency controls](/curators/markets/emergency-controls) > > Full reference for pause, freeze, and loss socialization. > [card] [Emergency council](/curators/markets/emergency-council) > > What the council can and cannot do. *** ## Worked Example This worked example shows how a curator can turn market observations into a market configuration. Using the SOL/USDC market, it shows how those conditions shape reserve settings and how the resulting configuration can be tested before exposure is increased. The figures are illustrative and are not Kamino recommendations. ### Measured Inputs The curator starts with existing information about the market before choosing any reserve parameters. For SOL, the most important starting point is its liquidity and volatility under real trading conditions. | Input | Example | | - | -: | | SOL price | \$200 | | Price impact on a \$2m sale | 0.4% | | Price impact on a \$10m sale | 1.6% | | Price impact on a \$25m sale | 4.5% | | 30-day annualised volatility | 60% | | Largest single-day fall over 12 months | 18% | ### Market Setup Inputs The worked example also assumes the reserve already has a suitable Scope price feed and that the market's authority roles have been configured. | Input | Example | | - | - | | Oracle | Scope SOL/USD entry with TWAP available | | Market owner | 3-of-5 multisig with a 12-hour timelock | | Emergency council | 2-of-4, no timelock | | Mint authority | None; SOL is the native asset | ### Initial Configuration The first question is how much room to leave between borrowing and liquidation. With SOL moving about 3.2% on an average day in this example, a 70% LTV and 77% liquidation threshold leave a seven-point buffer before a position becomes liquidatable. Next, the curator can focus on how borrowing costs should change as the USDC reserve fills. The borrow-rate curve keeps rates relatively low through 80% utilisation, then increases them more aggressively as available liquidity becomes tighter. | Utilisation | Borrow rate | | - | -: | | 0% | 0.5% | | 80% | 6% | | 95% | 25% | | 100% | 150% | New borrowing is blocked at 90% utilisation, after the borrow rate has already begun rising more sharply. This gives the interest-rate curve a chance to slow borrowing before the reserve reaches its hard limit. ### Exposure Limits The curator can then decide how much SOL exposure the reserve should allow. SOL is used only as collateral, so its borrow limit is set to 0. The deposit limit is set to 10,000 SOL, which caps how much SOL can enter the reserve. For the USDC reserve, the curator can set how much USDC can be borrowed across the market. In this example, the borrow limit is set to \$5 million. Because that limit is shared by all borrowers, it does not cap the size of an individual position. The curator therefore needs to test what happens if a large share of that debt becomes concentrated in one position. ### Liquidation Capacity Before choosing the liquidation bonus, it helps to revisit what happens during a liquidation. A liquidator repays part of the borrower's USDC debt and receives SOL collateral in return. The liquidation bonus means the liquidator receives slightly more SOL than the value of the USDC they repaid. If a borrower held \$5 million of USDC debt, a 20% close factor would allow up to \$1 million of that debt to be repaid in one liquidation. With a 5% bonus, the liquidator would receive about \$1.05 million worth of SOL. The liquidator may sell that SOL on an external market to recover the USDC used to repay the debt. Selling a large amount of SOL can move its market price, which is why the curator needs to compare the expected liquidation size with SOL's available trading liquidity. ### Withdrawal Limits Withdrawal caps control how quickly users can remove liquidity from a reserve. They do not limit how much collateral a liquidator can receive or sell during a liquidation. In this example, the SOL withdrawal cap is set to 5,000 SOL over 24 hours, while the USDC withdrawal cap is set to \$2 million over the same period. The USDC debt withdrawal cap controls how quickly new borrowing can increase. In this example, it is set to \$1 million over 24 hours, so even if the reserve is still below its overall \$5 million borrow limit, debt cannot grow faster than that rate. ### Liquidation Bonus The liquidation bonus compensates the liquidator for the cost and risk of closing the position. If a liquidator repays \$1 million of USDC debt with a 5% bonus, they receive about \$1.05 million worth of SOL. If selling that SOL causes less than 0.4% price impact, only a small part of the 5% bonus is lost during the sale. The remaining value helps cover transaction costs and provides the liquidator's incentive to execute the liquidation. The minimum bonus is set to 2%, so a liquidator is still rewarded when a position has only just crossed the liquidation threshold. As the position becomes less healthy, the bonus can increase toward the 5% maximum. ![Dynamic liquidation bonus as LTV increases](https://mintcdn.com/kamino-3d73a151/08Y-TFxV_VC5bdgE/images/curators/markets/liquidation-bonus-curve.webp?fit=max\&auto=format\&n=08Y-TFxV_VC5bdgE\&q=85\&s=f983da6e3fd936dacc6be0b12a01b3f9) ### Stress Check and Revision The curator should then test how the position holds up during a sharp fall in SOL. In the measured period, SOL fell as much as 18% in a single day, so the example uses that move as a stress case. Assume a position has \$100 of SOL collateral and \$77 of USDC debt at the liquidation threshold. If the full \$77 of debt had to be repaid through liquidation, a 5% bonus would require liquidators to receive \$80.85 worth of SOL collateral. That leaves \$19.15 of the original \$100 collateral value. An 18% fall in SOL would almost wipe out that remaining cushion, leaving only about \$1.15 of value before the position no longer has enough collateral to comfortably cover the debt and liquidation bonus. To create more room, the example lowers the liquidation threshold from 77% to 75%. With \$100 of collateral, that means liquidation begins at \$75 of debt instead of \$77, so the position is acted on earlier and more collateral value remains available to absorb further price movement. The LTV is then reduced to 68% to preserve the same seven-point gap between borrowing and liquidation. ### Oracle Configuration Next, the curator can configure how the SOL reserve is priced. The reserve uses a Scope SOL/USD feed, with safeguards that determine when that price should no longer be trusted. | Setting | Example | | - | - | | Price feed | Scope SOL/USD | | `max_age_price_seconds` | 60 | | `max_age_twap_seconds` | 240 | | `max_twap_divergence_bps` | 500 | | Heuristic lower bound | \$5 | | Heuristic upper bound | \$2,000 | The price age limits reject updates that have become stale, while the TWAP divergence limit rejects a current price that has moved too far from its recent average. The heuristic bounds provide an additional check against clearly invalid SOL prices. ### First Cap Increase After the market has operated without incident and SOL liquidity has been remeasured, the curator increases the USDC borrow limit from \$5 million to \$10 million. *** ## Pre-launch Checklist Before opening the market, confirm that the setup is complete and each configuration choice has been verified. ### Market Readiness * [ ] The intended lending and borrowing activity is clear. * [ ] Price impact has been measured at the expected liquidation size. * [ ] The collateral asset's largest recent price moves have been reviewed. * [ ] Token authorities have been checked, including mint and freeze authority where applicable. * [ ] The debt reserve's borrow cap limits the market's exposure if collateral supply increases unexpectedly. * [ ] Liquidator coverage has been confirmed before launch. * [ ] If market liquidity depends on an issuer, the expected liquidity commitment has been confirmed. ### Authority and Controls * [ ] The owner multisig is configured with the intended signer threshold. * [ ] The owner timelock is set to the intended duration. * [ ] The emergency council is configured and able to act without the owner timelock. * [ ] External alerting is active. * [ ] An incident contact at Kamino has been agreed. * [ ] The signing process has been tested before launch. ### Reserve Configuration * [ ] The gap between LTV and the liquidation threshold covers the collateral asset's observed volatility. * [ ] The utilisation block sits above the interest-rate curve kink. * [ ] Deposit and borrow caps are set to the intended launch size. * [ ] The expected liquidation size can be sold without excessive price impact. * [ ] Withdrawal caps are set on both reserves. * [ ] The maximum liquidation bonus is above the expected price impact at the liquidation size. * [ ] The minimum liquidation bonus is below the maximum. * [ ] The liquidation threshold still leaves enough collateral value after the maximum bonus is applied. ### Oracle Configuration * [ ] A suitable Scope price feed exists for each reserve asset. * [ ] Price age limits are configured. * [ ] TWAP divergence limits are configured. * [ ] Heuristic price bounds are configured. * [ ] The oracle setup has been tested before launch. * [ ] `block_price_usage` has been tested by the authority that would use it during an incident. ### Launch Checklist * [ ] The full market setup sequence has been rehearsed on staging. * [ ] The seed deposit has been made before any reserve configuration write. * [ ] Market ownership has been transferred to the multisig. * [ ] Growth criteria have been written down before opening the market. * [ ] Every signer has reviewed the incident response process. # Deposit and Borrow Source: https://docs.kamino.com/build/borrow/tutorials/deposit-and-borrow Deposit collateral and borrow assets against it ## Deposit Collateral Deposit assets as collateral to enable borrowing. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Build Deposit Instructions Deposit USDC as collateral into the wallet's borrow position. ```typescript theme={"theme":"css-variables"} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); const depositAction = await KaminoAction.buildDepositTxns({ kaminoMarket: market!, amount: new BN(3_000_000), reserveAddress: usdcReserve.address, owner: signer, obligation: new VanillaObligation(PROGRAM_ID), useV2Ixs: true, scopeRefreshConfig: undefined, initUserMetadata: { skipInitialization: false, skipLutCreation: true }, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!NOTE] > > A market can hold several reserves for the same token: one variable-rate reserve plus [fixed-rate](/build/borrow/tutorials/fixed-rate-borrowing) reserves. Actions take a reserve address, and `getExistingFloatRateReserveByMint()` returns the variable-rate one. `skipLutCreation: true` keeps a first deposit, including user account setup, in one transaction; without it the deposit fails with `0x17a3`. **Step 4** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(depositAction), tx) ); ``` **Step 5** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The collateral is deposited and the borrow position is ready. ## Borrow Assets Borrow assets against your deposited collateral. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Load the Obligation Load the wallet's borrow position so the SDK refreshes every reserve it uses. ```typescript theme={"theme":"css-variables"} const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!obligation) { console.log('No borrow position found for', signer.address); } ``` **Step 4** ### Build Borrow Instructions Borrow USDT from its variable-rate reserve against the collateral. ```typescript theme={"theme":"css-variables"} const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); const usdtReserve = market!.getExistingFloatRateReserveByMint(usdtMint); const borrowAction = await KaminoAction.buildBorrowTxns({ kaminoMarket: market!, amount: new BN(1_000_000), reserveAddress: usdtReserve.address, owner: signer, obligation: obligation!, useV2Ixs: true, scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!NOTE] > > The borrow must keep the position under its borrow limit, or the program rejects it. **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(borrowAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Borrow successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The USDT is in the wallet and the debt is recorded in the borrow position. # Fixed-Rate Borrowing Source: https://docs.kamino.com/build/borrow/tutorials/fixed-rate-borrowing Deposit collateral and place a fixed-term borrow order to borrow at a fixed rate Borrow at a fixed rate for a fixed term by depositing collateral and placing a borrow order in one transaction. Vaults fill the order from fixed-rate reserves, and the borrowed tokens go straight to your wallet. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoMarket, KaminoAction, KaminoBorrowOrder, VanillaObligation, PROGRAM_ID, SECONDS_PER_DAY, getAssociatedTokenAddress, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Signer and Initialize Market ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); const currentLedgerInstant = await getCurrentLedgerInstant(rpc); ``` **Step 3** ### Create the Borrow Order Define the loan: the token to borrow, the amount, the minimum term, how long the order stays open, and the highest rate you accept. ```typescript theme={"theme":"css-variables"} const solMint = address('So11111111111111111111111111111111111111112'); const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const borrowOrder = KaminoBorrowOrder.createFixedTermBorrowOrder({ debtMint: usdcMint, amount: new BN(5_000_000), destination: await getAssociatedTokenAddress(usdcMint, signer.address), termSeconds: new BN(30 * SECONDS_PER_DAY), expirySeconds: new BN(SECONDS_PER_DAY), maxRateBps: 500, enableAutoRolloverOnFilledBorrows: true, currentLedgerInstant, }); ``` > [!NOTE] > > `maxRateBps` caps the reserve's configured rate, not the APY. Fixed-rate reserves accrue interest per slot and mainnet slots are faster than the 500 ms the program assumes, so the APY a borrower pays is higher than the configured rate. `totalBorrowAPYFixedRate()` on the reserve returns it. `enableAutoRolloverOnFilledBorrows` rolls the loan into a new term at the end of the current one when liquidity allows. > [!WARNING] > > Each market sets a minimum order value (\$2 on the SOL/BTC Market); smaller orders are rejected with `BorrowOrderValueTooSmall`. Open orders count toward your LTV as if they were filled, and must stay at least 5% below max LTV. **Step 4** ### Build Deposit and Order Instructions Deposit SOL as collateral and place the order in the same transaction. ```typescript theme={"theme":"css-variables"} const solReserve = market!.getExistingFloatRateReserveByMint(solMint); const borrowOrderAction = await KaminoAction.buildDepositAndSetBorrowOrderTxns({ kaminoMarket: market!, amount: new BN(200_000_000), reserveAddress: solReserve.address, owner: signer, obligation: new VanillaObligation(PROGRAM_ID), borrowOrder, orderIdx: 0, useV2Ixs: true, scopeRefreshConfig: undefined, initUserMetadata: { skipInitialization: false, skipLutCreation: true }, currentLedgerInstant, }); const instructions = KaminoAction.actionToIxs(borrowOrderAction); ``` > [!NOTE] > > An obligation holds up to three borrow orders; `orderIdx` picks the slot to write. Fixed-rate borrowing uses the same `VanillaObligation` as variable-rate borrowing. **Step 5** ### Fetch Lookup Tables ```typescript theme={"theme":"css-variables"} const addresses = [ ...new Set(instructions.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), ]; const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addresses }), }); if (!lutResponse.ok) { console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); } const { lutAddresses } = await lutResponse.json(); const lookupTables = await fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); const lookupTableAddresses = Object.fromEntries(lookupTables.map((lut) => [lut.address, lut.data.addresses])); ``` **Step 6** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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, lookupTableAddresses) ); ``` **Step 7** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Borrow order placed! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > Once confirmed, your SOL is deposited and the borrow order is open. It fills automatically, in one or more parts, while it's open. Interest starts on each part when it fills, and the USDC goes straight to your wallet. # Repay and Withdraw Source: https://docs.kamino.com/build/borrow/tutorials/repay-and-withdraw Repay borrowed assets and withdraw your collateral ## Repay Debt Repay borrowed assets to improve your position health. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Load the Obligation Load the wallet's borrow position so the SDK refreshes every reserve it uses. ```typescript theme={"theme":"css-variables"} const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!obligation) { console.log('No borrow position found for', signer.address); } ``` **Step 4** ### Build Repay Instructions Repay part of the USDT loan from the USDT in the wallet. ```typescript theme={"theme":"css-variables"} const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); const usdtReserve = market!.getExistingFloatRateReserveByMint(usdtMint); const repayAction = await KaminoAction.buildRepayTxns({ kaminoMarket: market!, amount: new BN(1_000_000), reserveAddress: usdtReserve.address, owner: signer, obligation: obligation!, useV2Ixs: true, scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!TIP] > > To repay the whole loan including accrued interest, pass `new BN(U64_MAX)` as the amount (`U64_MAX` is exported by the SDK). The program repays the exact debt, so no dust is left. **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(repayAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Repay successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The debt in the borrow position is reduced. ## Withdraw Collateral Withdraw collateral from your obligation. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Load the Obligation Load the wallet's borrow position so the SDK refreshes every reserve it uses. ```typescript theme={"theme":"css-variables"} const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!obligation) { console.log('No borrow position found for', signer.address); } ``` **Step 4** ### Build Withdraw Instructions Withdraw USDC collateral from the borrow position. ```typescript theme={"theme":"css-variables"} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); const withdrawAction = await KaminoAction.buildWithdrawTxns({ kaminoMarket: market!, amount: new BN(1_000_000), reserveAddress: usdcReserve.address, owner: signer, obligation: obligation!, useV2Ixs: true, scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!TIP] > > With open borrows, the withdrawal must keep the position under its borrow limit. To withdraw all of a deposit, pass `new BN(U64_MAX)` as the amount. **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(withdrawAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Withdraw successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The collateral is back in the wallet. # Deposit and Borrow Source: https://docs.kamino.com/build/borrow/tutorials/rust/deposit-and-borrow Deposit collateral and borrow assets using the klend-interface Rust crate ## Deposit Collateral Deposit assets as collateral to enable borrowing. **Step 1** ### Add Dependencies ```toml theme={"theme":"css-variables"} [dependencies] klend-interface = "0.6.0" solana-pubkey = "2.1" solana-instruction = "2.1" solana-sdk = "~2.3" solana-client = "~2.3" spl-token = "7" spl-associated-token-account = "6" ``` > [!NOTE] > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. **Step 2** ### Set Up RPC Client ```rust theme={"theme":"css-variables"} use solana_client::rpc_client::RpcClient; use solana_sdk::signer::keypair::read_keypair_file; use solana_sdk::signer::Signer; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let signer = read_keypair_file("/path/to/your/keypair.json") .expect("Failed to read keypair file"); let owner = signer.pubkey(); ``` **Step 3** ### Build Obligation Context Derive the obligation PDA, fetch its account data along with all associated reserves, and build an `ObligationContext`. ```rust theme={"theme":"css-variables"} use klend_interface::ObligationContext; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; use std::str::FromStr; let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); // Derive the obligation PDA let (obligation_pubkey, _) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, &Pubkey::default(), &Pubkey::default(), ); // Fetch the obligation account let obligation_data = rpc_client.get_account(&obligation_pubkey)?; // Discover which reserves the obligation references let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; // Fetch all reserve accounts in one RPC call let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; // Build the context let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() .zip(reserve_accounts.iter()) .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) .collect(); let ctx = ObligationContext::from_account_data( obligation_pubkey, &obligation_data.data, &reserves )?; ``` > [!NOTE] > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. **Step 4** ### Derive Token Accounts ```rust theme={"theme":"css-variables"} use spl_associated_token_account::get_associated_token_address; // User's ATA for the deposit token (e.g. USDC) let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); let user_source_liquidity = get_associated_token_address(&owner, &liquidity_mint); ``` **Step 5** ### Build Instructions ```rust theme={"theme":"css-variables"} let instructions = ctx.deposit( owner, &reserve_pubkey, user_source_liquidity, 3_000_000, // 3 USDC (6 decimals) )?; // Returns: [refresh_reserves..., refresh_obligation, deposit_and_collateral_v2] ``` **Step 6** ### Build and Send Transaction ```rust theme={"theme":"css-variables"} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&instructions, Some(&owner)); let recent_blockhash = rpc_client.get_latest_blockhash()?; let tx = Transaction::new(&[&signer], message, recent_blockhash); let signature = rpc_client.send_and_confirm_transaction(&tx)?; println!("Deposit successful! Signature: {signature}"); ``` > [!TIP] > > The deposit is complete. Your collateral has been supplied and your borrow position is open. # Overview Source: https://docs.kamino.com/build/cli/index Command line tool to manage Kamino Lend markets, reserves, and vaults The Kamino Manager CLI is a command line tool used to create and manage Kamino lending markets, reserves, and Kamino vaults. The Kamino CLI provides: * Create and configure lending markets with reserves for different token types and custom risk parameters * Build and manage automated liquidity vaults with adjustable allocation strategies and yield optimization * Monitor performance metrics and update market or vault settings as needed > [card] [Installation & Setup](/build/cli/installation-setup) > > Install and configure the Kamino Manager CLI > [card] [Market Operations](/build/cli/market-operations) > > Create and manage Kamino lending markets and reserves > [card] [Vault Operations](/build/cli/vault-operations) > > Create and manage Kamino vaults # Install and Setup the Kamino CLI Source: https://docs.kamino.com/build/cli/installation-setup Get started with the Kamino Manager CLI The Kamino Manager CLI is a command-line tool for creating and managing Kamino lending markets, reserves, and vaults. ## Prerequisites Before installing the Kamino Manager CLI: > [!NOTE] > > Node.js, Yarn package manager, and Solana CLI tools are required to run the Kamino Manager CLI. ## Installation Follow these steps to install and configure the Kamino Manager CLI: **1. Install Node.js and Yarn** Install Node.js from [nodejs.org](https://nodejs.org/), then install Yarn package manager. ```bash theme={"theme":"css-variables"} npm install -g yarn ``` **2. Install Solana CLI** Install the Solana CLI tools to create and manage keypairs. ```bash theme={"theme":"css-variables"} sh -c "$(curl -sSfL https://release.solana.com/v1.18.18/install)" ``` > [!WARNING] > > After installation, restart the terminal to ensure the Solana CLI is available in PATH. **3. Clone and Setup Kamino Manager** Clone the Kamino SDK repository and install dependencies. ```bash theme={"theme":"css-variables"} git clone git@github.com:Kamino-Finance/klend-sdk.git cd klend-sdk yarn ``` This will install all necessary dependencies for the Kamino Manager CLI. ## Configuration After installation, configure the Kamino Manager CLI with a wallet and RPC endpoint. **1. Create Admin Keypair** Create a new keypair that will serve as the admin account for managing markets and vaults. ```bash theme={"theme":"css-variables"} solana-keygen new -o admin.json ``` > [!WARNING] > > Store the keypair file securely and never share it. This keypair will need SOL for transaction fees. > [!NOTE] > > Existing keypairs can be used instead of creating a new one. Specify the path to the existing keypair file in the configuration. **2. Configure Environment Variables** Create a `.env` file in the `klend-sdk` directory and configure the following variables: ```bash theme={"theme":"css-variables"} # Path to admin keypair file ADMIN=./admin.json # Solana RPC endpoint RPC=https://api.mainnet-beta.solana.com # Program IDs KLEND_PROGRAM_ID_MAINNET="KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD" KVAULT_PROGRAM_ID_MAINNET="KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd" KLEND_PROGRAM_ID_STAGING="SLendK7ySfcEzyaFqy93gDnD3RtrpXJcnRwb6zFHJSh" KVAULT_PROGRAM_ID_STAGING="stKvQfwRsQiKnLtMNVLHKS3exFJmZFsgfzBPWHECUYK" KVAULT_PROGRAM_ID_DEVNET="devkRngFnfp4gBc5a3LsadgbQKdPo8MSZ4prFiNSVmY" ``` > [!NOTE] > > For production use, it's recommended to use a private RPC endpoint from providers like [Helius](https://www.helius.dev). Public RPCs are rate-limited and may cause transaction failures. **3. Fund Your Admin Account** Transfer SOL to the admin account to pay for transaction fees. Get the admin account address: ```bash theme={"theme":"css-variables"} solana-keygen pubkey admin.json ``` Transfer SOL to this address from another wallet or acquire it from an exchange. ## Verify Installation Run a simple command to verify everything is set up correctly: ```bash theme={"theme":"css-variables"} yarn run kamino-manager --help ``` The help output should display available commands for managing markets and vaults. ## Next Steps The Kamino Manager CLI is now installed and ready for managing markets and vaults: > [card] [Market Operations](/build/cli/market-operations) > > Create and manage lending markets and reserves > [card] [Vault Operations](/build/cli/vault-operations) > > Create and manage Kamino vaults # Market Operations Source: https://docs.kamino.com/build/cli/market-operations kamino-manager CLI command reference for market and reserve operations A flat reference of every `kamino-manager` command that touches a Kamino lending market or reserve. For workflow guidance — when to use each command, what to set, why — see the [Curator Markets](/curators/markets) tab. > [!NOTE] > > Before running any command, complete the [Installation & Setup](/build/cli/installation-setup) guide. The CLI requires `ADMIN`, `RPC`, `KLEND_PROGRAM_ID_MAINNET`, and `KLEND_PROGRAM_ID_STAGING` in `.env`. ## Conventions ### Execution modes Every command supports `--mode `: | Mode | What it does | | - | - | | `inspect` | Prints a Solana Explorer URL where you can simulate the transaction in your browser | | `simulate` | Runs simulation server-side and prints the result | | `execute` | Signs with the admin keypair and lands the transaction | | `multisig` | Outputs a base58-encoded transaction for submission to a Squads proposal | Multisig mode requires `--multisig ` to identify the multisig. ### Network selection | Flag | Target | Program ID env var | | - | - | - | | (none) | Mainnet | `KLEND_PROGRAM_ID_MAINNET` | | `--staging` | Staging program on Solana mainnet | `KLEND_PROGRAM_ID_STAGING` | | `--devnet` | Solana devnet | (Devnet program ID resolved from env) | ## Market lifecycle ### `create-market` Initialize a new `LendingMarket` account. ```bash theme={"theme":"css-variables"} yarn kamino-manager create-market --mode execute ``` | Flag | Required | Description | | - | - | - | | `--mode` | Yes | `inspect` / `simulate` / `execute` / `multisig` | | `--multisig` | If `--mode multisig` | Pubkey of the multisig that will own the market | | `--staging` / `--devnet` | No | Network selection | ### `update-lending-market-from-config` Apply a full market config update from a JSON file. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-lending-market-from-config \ --lending-market \ --lending-market-config-path ./configs//market-.json \ --mode execute ``` | Flag | Required | Description | | - | - | - | | `--lending-market` | Yes | Market address | | `--lending-market-config-path` | Yes | Path to the JSON config file | | `--mode` | Yes | Execution mode | ### `update-lending-market-name` Focused command to rename a market. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-lending-market-name \ --lending-market \ --new-name "My Market" \ --mode execute ``` | Flag | Required | | - | - | | `--lending-market` | Yes | | `--new-name` | Yes | | `--mode` | Yes | ### `update-lending-market-owner` Promote `lending_market_owner_cached` to active owner. Final step of the two-step ownership transfer. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-lending-market-owner \ --lending-market \ --mode multisig \ --multisig ``` | Flag | Required | | - | - | | `--lending-market` | Yes | | `--mode` | Yes | | `--multisig` | If `--mode multisig` | ### `download-lending-market-config` Export the current market config to a JSON file (read-only). ```bash theme={"theme":"css-variables"} yarn kamino-manager download-lending-market-config \ --lending-market ``` Saves to `./configs//market-.json`. ### `download-lending-market-config-and-all-reserves-configs` Download the market config plus every reserve's config in a single call. ```bash theme={"theme":"css-variables"} yarn kamino-manager download-lending-market-config-and-all-reserves-configs \ --lending-market ``` ### `get-market-or-vault-admin-info` Query admin metadata (owner, cached owner, emergency council). ```bash theme={"theme":"css-variables"} yarn kamino-manager get-market-or-vault-admin-info \ --address ``` ## Reserve lifecycle ### `add-asset-to-market` Add a new reserve to a market with an initial config. ```bash theme={"theme":"css-variables"} yarn kamino-manager add-asset-to-market \ --market \ --mint \ --mint-program-id TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA \ --reserve-config-path ./configs/my_reserve_config.json \ --mode execute ``` | Flag | Required | Description | | - | - | - | | `--market` | Yes | Market address | | `--mint` | Yes | Token mint address | | `--mint-program-id` | Yes | `TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA` for SPL Token, `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb` for Token-2022 | | `--reserve-config-path` | Yes | Path to the reserve config JSON | | `--mode` | Yes | Execution mode | ### `update-reserve-config` Apply a full reserve config update from a JSON file. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-reserve-config \ --reserve \ --reserve-config-path ./configs/.json \ --mode execute ``` | Flag | Required | | - | - | | `--reserve` | Yes | | `--reserve-config-path` | Yes | | `--mode` | Yes | ### `update-reserve-config-debt-cap` Focused update of just the borrow cap. Faster to review than a full config update. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-reserve-config-debt-cap \ --reserve \ --mode multisig \ --multisig ``` | Flag | Required | | - | - | | `--reserve` | Yes | | `--mode` | Yes | | `--multisig` | If `--mode multisig` | ### `download-reserve-config` Export the current reserve config to a JSON file. ```bash theme={"theme":"css-variables"} yarn kamino-manager download-reserve-config \ --reserve \ --output ./configs/.json ``` | Flag | Required | | - | - | | `--reserve` | Yes | | `--output` | No (defaults to a path under `./configs/`) | ### `simulate-reserve-apy` Compute the live supply and borrow APY for a reserve from on-chain state. ```bash theme={"theme":"css-variables"} yarn kamino-manager simulate-reserve-apy \ --reserve ``` ## Oracles ### `get-oracle-mappings` List Scope, Pyth, and Switchboard oracle addresses for known mints. ```bash theme={"theme":"css-variables"} yarn kamino-manager get-oracle-mappings ``` Use the output to populate `tokenInfo.scopeConfiguration.priceFeed`, `tokenInfo.pythConfiguration.price`, or `tokenInfo.switchboardConfiguration.priceAggregator` in a reserve config. ## Farms ### `get-reserve-farms-apy` Reward APY for a reserve's collateral and debt farms. ```bash theme={"theme":"css-variables"} yarn kamino-manager get-reserve-farms-apy \ --reserve ``` For farm initialization, funding, and emission configuration, use the [KFarms tooling](https://github.com/Kamino-Finance/kfarms). ## Reserve config schema The reserve config JSON schema is documented at [Reserve config reference](/curators/markets/reserve-parameters). A starter file ships with klend-sdk: [ klend-sdk/configs/reserve_config_example.json](https://github.com/Kamino-Finance/klend-sdk/blob/master/configs/reserve_config_example.json) Some fields in older example files (`assetTier`, `multiplierSideBoost`, `multiplierTagBoost`) are deprecated and ignored by the program. The canonical schema is in the reference page above. ## Market config schema The market config JSON schema is documented at [Market config reference](/curators/markets/market-config-reference). ## Workflow guides These pages walk through the curator workflow that uses the commands above: > [card] [Create a market](/curators/markets/creating-a-market) > > `create-market` > [card] [Add reserves](/curators/markets/adding-reserves) > > `add-asset-to-market` > [card] [Configure oracles](/curators/markets/configuring-oracles) > > `get-oracle-mappings`, `tokenInfo` setup > [card] [Transfer to multisig](/curators/markets/transfer-to-multisig) > > `update-lending-market-from-config`, `update-lending-market-owner` > [card] [Updating reserves](/curators/markets/reserve-management) > > `update-reserve-config`, `update-reserve-config-debt-cap` > [card] [Market settings](/curators/markets/market-settings) > > `update-lending-market-from-config`, `update-lending-market-name` ## Next > [card] [Vault Operations](/build/cli/vault-operations) > > Create and manage Kamino vaults > [card] [Installation & Setup](/build/cli/installation-setup) > > Review installation and configuration # Vault Operations Source: https://docs.kamino.com/build/cli/vault-operations Create and manage Kamino vaults Use the Kamino Manager CLI to create vaults, manage reserve allocations, and configure vault parameters. > [!NOTE] > > Before starting, complete the [Installation & Setup](/build/cli/installation-setup) guide. Commands require a .env file with ADMIN (path to vault owner keypair) and RPC configured. ## Understanding CLI Modes All Kamino Manager commands support different execution modes to test and verify operations before committing them: * **inspect** - Preview the transaction without executing it * **simulate** - Test the transaction simulation on-chain * **execute** - Execute the transaction immediately * **multisig** - Generate a multisig proposal for the operation > [!NOTE] > > It's recommended to always start with `inspect` or `simulate` mode to verify transactions before running with `execute`. ## Network Selection By default, all commands run against **mainnet** and no additional flag is needed. To target a different network, pass one of the following flags: * `--staging` — Use the staging program ID * `--devnet` — Use the devnet program ID ```bash theme={"theme":"css-variables"} # Mainnet (default, no flag needed) yarn kamino-manager create-vault --mint --mode execute # Staging yarn kamino-manager create-vault --mint --mode execute --staging # Devnet yarn kamino-manager create-vault --mint --mode execute --devnet ``` > [!NOTE] > > The corresponding program IDs (`KVAULT_PROGRAM_ID_MAINNET`, `KVAULT_PROGRAM_ID_STAGING`, `KVAULT_PROGRAM_ID_DEVNET`) must be configured in your `.env` file. See the [Installation & Setup](/build/cli/installation-setup) guide. ## Create a New Vault Create a new Kamino vault to manage automated liquidity strategies. **1. Create Vault** Run the create vault command with the desired liquidity token mint. ```bash theme={"theme":"css-variables"} yarn kamino-manager create-vault --mint --mode execute ``` > [!NOTE] > > For testing purposes, add the `--staging` flag to use the staging program ID or `--devnet` to use the devnet program ID. These flags are applicable to all CLI commands. **2. Save Vault Address** After creation, save the vault address from the command output. This address is required for all subsequent vault operations. ## Manage Reserve Allocations Configure how vault assets are distributed across different lending reserves. ### Add or Update Reserve Allocation Add a new reserve to the vault or update an existing reserve's allocation parameters. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-vault-reserve-allocation \ --vault \ --reserve \ --allocation-weight \ --allocation-cap \ --mode simulate ``` **Parameters:** * `allocation-weight` - The allocation weight for this reserve; only relevant in relation to other reserve weights (proportional). If Reserve A has weight 100,000 and Reserve B has weight 50,000, Reserve A gets 2/3 of vault assets and Reserve B gets 1/3 * `allocation-cap` - The allocation cap in decimal (not lamports) for this reserve **Example:** Adding PRIME market allocation ```bash theme={"theme":"css-variables"} yarn kamino-manager update-vault-reserve-allocation \ --vault 67dqmR76uAbjX6e81A1ganKv3ou31WUMEdeWJkwVfeXy \ --reserve 9GJ9GBRwCp4pHmWrQ43L5xpc9Vykg7jnfwcFGN8FoHYu \ --allocation-weight 100000 \ --allocation-cap 18446744073709.551615 \ --mode simulate ``` > [!NOTE] > > First run with `--mode simulate` to verify the operation works as expected, then use `--mode execute` to send the transaction. ### Remove Reserve Allocation Remove a reserve from the vault's allocation strategy. ```bash theme={"theme":"css-variables"} yarn kamino-manager remove-vault-allocation \ --vault \ --reserve \ --mode simulate ``` **Example:** Removing USDC reserve from fartcoin market ```bash theme={"theme":"css-variables"} yarn kamino-manager remove-vault-allocation \ --vault 67dqmR76uAbjX6e81A1ganKv3ou31WUMEdeWJkwVfeXy \ --reserve F22tnLsbv66vEU2GZRc7coaqZsr8UcBbyp9V2kqWAiWK \ --mode simulate ``` ## Vault Ownership Management > [!NOTE] > > Transfer vault ownership to a different admin account. For production vaults, we recommend transferring ownership to a [Squads](https://squads.xyz/multisig) multisig with hardware wallet support. **1. Set Pending Admin** Update the vault's pending admin to the new owner address. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-vault-pending-admin \ --vault \ --new-admin \ --mode execute ``` **Parameters:** * `vault` - The vault address to change the pending admin for * `new-admin` - The new admin pubkey to set as pending admin (typically a multisig address) **2. Accept Ownership** The new admin must accept ownership to complete the transfer. ```bash theme={"theme":"css-variables"} yarn kamino-manager accept-ownership \ --vault \ --mode execute ``` > [!NOTE] > > This command must be run with the new admin's keypair in the ADMIN field of the .env file. ## Fee Management Configure and manage vault performance and management fees. ### Performance Fees Set the performance fee taken on generated yield. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-vault-perf-fee \ --vault \ --fee-bps \ --mode execute ``` The fee is specified in basis points (1 bps = 0.01%). ### Management Fees Set the yearly management fee for vault operations. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-vault-mgmt-fee \ --vault \ --fee-bps \ --mode execute ``` ### Withdraw Pending Fees Withdraw accumulated fees from the vault. ```bash theme={"theme":"css-variables"} yarn kamino-manager withdraw-pending-fees \ --vault \ --mode execute ``` ### Relinquish Fees The vault manager can give up pending fees (partial or full), which will be distributed to vault token holders. This is useful when pending fees grow larger than the total vault value, allowing the manager to restore the vault to a healthy state. ```bash theme={"theme":"css-variables"} yarn kamino-manager give-up-pending-fees \ --vault \ --max-amount-to-give-up \ --mode execute ``` **Parameters:** * `vault` - The vault address to give up fees for * `max-amount-to-give-up` - The amount in tokens to be given up from the pending fees ## Advanced Operations ### Multisig Management For multisig-controlled vaults, use the `--mode multisig` flag to generate Base58-encoded transactions for proposal submission. ```bash theme={"theme":"css-variables"} yarn kamino-manager update-vault-reserve-allocation \ --vault \ --reserve \ --allocation-weight \ --allocation-cap \ --mode multisig \ --multisig ``` > [!NOTE] > > We recommend using [Squads](https://squads.xyz/multisig) with a hardware wallet for multisig management. The generated transaction can be submitted as a multisig proposal through Squads. ## Next Steps > [card] [Market Operations](/build/cli/market-operations) > > Create and manage lending markets and reserves > [card] [Installation & Setup](/build/cli/installation-setup) > > Review installation and configuration # API vs SDK vs Rust Crate Source: https://docs.kamino.com/build/developers/api-vs-sdk Access data and build transactions through the API, the TypeScript SDK, or the Rust interface crate ## Overview Kamino provides three integration options: | Option | Description | | - | - | | REST API | HTTPS endpoints for data, analytics, and unsigned transactions. Language-agnostic. | | TypeScript SDK | On-chain state reads and transaction building. TS/JS only. | | Rust Interface Crate | Lightweight instruction builder for Rust clients, bots, and on-chain CPI. | ## Core Differences Comparison of API, SDK, and Rust crate capabilities. | Capability | REST API | TypeScript SDK | Rust Interface Crate | | - | - | - | - | | Data queries (vaults, reserves) | Ready-made endpoints | On-chain reads | On-chain reads (raw account parsing) | | User position tracking | Rich endpoints | Real-time account lookup | Real-time account lookup | | Historical metrics & charts | Built-in history endpoints | Not available | Not available | | Transaction building (deposit, borrow) | Unsigned transaction endpoints | Instruction builders | Instruction builders | | Vault creation | Not supported | Admin-level creation tools | Not supported | | On-chain CPI | Not applicable | Not applicable | Direct CPI from Solana programs | | Language/runtime | Any (via HTTP) | TypeScript/JavaScript only | Rust (client-side or on-chain) | ## Data & Analytics Retrieve vault, market, and historical performance data. > [accordion] Historical Performance > > **REST API** > > Fetch historical APY data for lending market reserves. > > ```typescript theme={"theme":"css-variables"} > const options = {method: 'GET'}; > fetch('https://api.kamino.finance/kamino-market/{market-id}/rates/history', options) > .then(response => response.json()) > .then(response => console.log(response)) > .catch(err => console.error(err)); > ``` > > **TypeScript SDK** > > No history tracking. Developers must persist snapshots manually if needed. ## On-Chain Transactions Build and execute deposit, borrow, repay, and withdraw operations. > [accordion] Deposit Liquidity > > **REST API**\ > Get unsigned Solana transactions to deposit liquidity into a Kamino Lend market reserve. Returns transaction that must be signed client-side. > > ```typescript theme={"theme":"css-variables"} > const depositRequest = { > wallet: 'YOUR_WALLET_ADDRESS', > market: 'DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek', > reserve: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', > amount: '1.0', // 1 USDC (decimal format, not lamports) > }; > > const res = await fetch('https://api.kamino.finance/ktx/klend/deposit', { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > body: JSON.stringify(depositRequest), > }); > > const { transaction } = await res.json(); > // Sign and send transaction client-side > ``` > > **TypeScript SDK**\ > Build and execute deposit transactions directly on-chain. > > ```typescript theme={"theme":"css-variables"} > import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; > import { createSolanaRpc, address } from '@solana/kit'; > import BN from 'bn.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const market = await KaminoMarket.load( > rpc, > address('DxXdAyU3kCjnyggvHmY5nAwg5cRbbmdyX3npfDMjjMek'), > 100 > ); > > const depositAction = await KaminoAction.buildDepositTxns( > market, > new BN(1_000_000), // 1 USDC > address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), > signer, > new VanillaObligation(PROGRAM_ID), > true > ); > // Build, sign, and send transaction > ``` > > **Rust Interface Crate**\ > Build deposit instructions from a Rust client. Ideal for bots and backend services. > > ```rust theme={"theme":"css-variables"} > use klend_interface::{helpers, pda, ReserveInfo, KLEND_PROGRAM_ID}; > use spl_associated_token_account::get_associated_token_address; > > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; > let user_source_liquidity = get_associated_token_address(&owner, &reserve.liquidity_mint); > let (collateral_mint, _) = pda::reserve_collateral_mint(&KLEND_PROGRAM_ID, &reserve_pubkey); > let user_destination_collateral = get_associated_token_address(&owner, &collateral_mint); > > let instructions = helpers::deposit::deposit( > owner, > &reserve, > user_source_liquidity, > user_destination_collateral, > 1_000_000, // 1 USDC (6 decimals) > ); > // Build and send transaction > ``` > [accordion] Deposit into an Earn Vault > > **TypeScript SDK**\ > Build a vault deposit with the SDK. > > ```typescript theme={"theme":"css-variables"} > import { KaminoManager, KaminoVault, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > import { createSolanaRpc, address } from '@solana/kit'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault(rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), slotDuration); // USDC vault > > const vaultState = await vault.getState(); > const bundle = await vault.depositIxs( > signer, > new Decimal(1.0), > await manager.loadVaultReserves(vaultState), > await manager.loadVaultFarmState(vaultState), > null > ); > ``` > > **Rust Interface Crate**\ > Build a vault deposit with the [`kvault-interface`](https://crates.io/crates/kvault-interface) crate. The helper derives the PDAs and per-reserve remaining accounts from the on-chain vault state. > > ```rust theme={"theme":"css-variables"} > use kvault_interface::{helpers, pda, VaultInfo, KVAULT_PROGRAM_ID}; > use spl_associated_token_account::get_associated_token_address; > > let vault = VaultInfo::from_account_data(vault_pubkey, &vault_data.data, &reserve_infos)?; > > let user_token_ata = get_associated_token_address(&owner, &vault.token_mint); > let (shares_mint, _) = pda::shares_mint(&KVAULT_PROGRAM_ID, &vault_pubkey); > let user_shares_ata = get_associated_token_address(&owner, &shares_mint); > > let instruction = helpers::deposit::deposit( > &vault, > owner, > user_token_ata, > user_shares_ata, > 1_000_000, // 1 USDC (6 decimals) > ); > // Build and send transaction > ``` > [accordion] Borrow & Repay > > **REST API**\ > Get unsigned transactions for borrow and repay operations. > > ```typescript theme={"theme":"css-variables"} > // Borrow > const borrowRequest = { > wallet: 'YOUR_WALLET_ADDRESS', > market: '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF', > reserve: 'D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59', > amount: '1.0', > }; > > const borrowRes = await fetch('https://api.kamino.finance/ktx/klend/borrow', { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > body: JSON.stringify(borrowRequest), > }); > > // Repay > const repayRequest = { > wallet: 'YOUR_WALLET_ADDRESS', > market: '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF', > reserve: 'D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59', > amount: '1.0', > }; > > const repayRes = await fetch('https://api.kamino.finance/ktx/klend/repay', { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > body: JSON.stringify(repayRequest), > }); > ``` > > **TypeScript SDK** \ > Build borrow and repay transactions directly. > > ```typescript theme={"theme":"css-variables"} > import { KaminoAction, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; > import BN from 'bn.js'; > > const borrowAction = await KaminoAction.buildBorrowTxns( > market, > new BN(1_000_000), > tokenMint, > signer, > new VanillaObligation(PROGRAM_ID), > true, > undefined, > 1_000_000, > true, > false > ); > ``` > > **Rust Interface Crate**\ > Build borrow instructions using `ObligationContext` which handles reserve refresh automatically. > > ```rust theme={"theme":"css-variables"} > use klend_interface::{ObligationContext, pda, KLEND_PROGRAM_ID}; > use spl_associated_token_account::get_associated_token_address; > > // Build context from on-chain obligation + its reserves > let ctx = ObligationContext::from_account_data( > obligation_pubkey, &obligation_data.data, &reserves > )?; > > let user_dest_liquidity = get_associated_token_address(&owner, &borrow_mint); > let instructions = ctx.borrow( > owner, > &reserve_pubkey, > user_dest_liquidity, > 1_000_000, // 1 USDC (6 decimals) > )?; > // Build and send transaction > ``` > [accordion] Vault Creation > > **TypeScript SDK**\\ > > ```typescript theme={"theme":"css-variables"} > const { vault: vaultSigner, initVaultIxs: instructions } = > await kaminoManager.createVaultIxs(kaminoVaultConfig); > ``` ## Recommended Usage Patterns Choose the right tool for your use case. | Use Case | Best Tool | | - | - | | Display vault list with APR & TVL | API | | Chart vault APY over 30 days | API | | Fetch a user's historical rewards | API | | Build transactions for client signing | API | | Execute transactions with full customization | SDK | | Create a new liquidity vault | SDK | | Build in non-JS backend (e.g. Python) | API | | Require zero rate limits | SDK with private RPC | | Build a Rust bot | Rust Crate | | CPI from an on-chain Solana program | Rust Crate | ## Summary Use the Kamino REST API for fast data integration, history tracking, and building unsigned transactions across any backend. Use the TypeScript SDK for advanced transaction composition, simulation, and vault creation with full on-chain control. Use the Rust interface crate for Rust-native clients, high-performance bots, and CPI from on-chain Solana programs. ## Relevant links > [card] [API Documentation](https://api-docs.kamino.com/) > > Explore REST API endpoints and response schemas > [card] [SDK Documentation](https://github.com/Kamino-Finance/klend-sdk) > > Learn how to integrate the TypeScript SDK > [card] [Lending Rust Crate](https://crates.io/crates/klend-interface) > > Lightweight Rust instruction builder for Kamino Lending clients and CPI > [card] [Vaults Rust Crate](https://crates.io/crates/kvault-interface) > > Lightweight Rust instruction builder for Kamino Vaults clients and CPI > [card] [Borrow Operations](/build/developers/borrow/operations/deposit) > > Step-by-step guides for deposit, withdraw, borrow, and repay > [card] [Earn Operations](/build/developers/earn/operations/deposit) > > Step-by-step guides for vault deposit and withdraw > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples) > > View code examples in the GitHub repository # Market Source: https://docs.kamino.com/build/developers/borrow/data/market-data ## Reading Market Data Retrieve market metrics, reserve information, and TVL data using the Kamino SDK and API. > [!NOTE] > > Historical market data is only available via the API. **Step 1** ### Get Market Info Retrieves real-time market-wide metrics including total deposits and borrows TVL across all reserves. > [!NOTE] > > Using the SDK requires a private RPC connection or the public rate-limited > [RPC endpoint](https://api.mainnet-beta.solana.com). > [tab] TypeScript > > ```typescript icon="typescript" getMarketInfo theme={"theme":"css-variables"} > import { createSolanaRpc, address } from "@solana/kit"; > import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from "@kamino-finance/klend-sdk"; > > const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com"); > const marketPubkey = address("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF"); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > > console.log({ > totalDepositsUsd: market!.getTotalDepositTVL().toFixed(2), > totalBorrowsUsd: market!.getTotalBorrowTVL().toFixed(2), > }); > ``` > > > > View Code **Step 2** ### Get Reserve Info Queries detailed information for all reserves in the market including deposit/borrow TVL, APY rates, and utilization ratios. > [tab] TypeScript > > ```typescript icon="typescript" getReserveInfo theme={"theme":"css-variables"} > import { createSolanaRpc, address } from "@solana/kit"; > import { > KaminoMarket, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from "@kamino-finance/klend-sdk"; > > const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com"); > const marketPubkey = address("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF"); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const reserves = market!.getReserves().map((reserve) => ({ > symbol: reserve.getTokenSymbol(), > kind: reserve.getKind().toString(), > supplyAPY: `${(reserve.totalSupplyAPY(ledgerInstant) * 100).toFixed(2)}%`, > borrowAPY: `${(reserve.totalBorrowAPY(ledgerInstant) * 100).toFixed(2)}%`, > utilization: `${(reserve.calculateUtilizationRatio() * 100).toFixed(2)}%`, > depositTvlUsd: reserve.getDepositTvl().toFixed(2), > borrowTvlUsd: reserve.getBorrowTvl().toFixed(2), > })); > > console.table(reserves); > ``` > > > [!NOTE] > > > > A token can have several reserves: one variable-rate reserve plus fixed-rate ones, so each row shows its kind. Fixed-rate APYs depend on the slot duration passed to `KaminoMarket.load`. A hard-coded value such as 400 ms shows them at about half their real rate, because mainnet slots are closer to 210 ms. > > > > View Code > [tab] Rust > > ```rust expandable title="get_market_and_reserves.rs" theme={"theme":"css-variables"} > use klend_interface::state::{LendingMarket, Reserve}; > use klend_interface::{from_account_data, Fraction, KLEND_PROGRAM_ID}; > use solana_account::ReadableAccount; > use solana_account_decoder_client_types::UiAccountEncoding; > use solana_client::rpc_client::RpcClient; > use solana_client::rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig}; > use solana_client::rpc_filter::{Memcmp, RpcFilterType}; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let market_pubkey = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF")?; > > let market_account = rpc_client.get_account(&market_pubkey)?; > let market = from_account_data::(&market_account.data)?; > println!("Market authority: {}", market.lending_market_owner); > > let filters = vec![ > RpcFilterType::Memcmp(Memcmp::new_raw_bytes(32, market_pubkey.to_bytes().to_vec())), > RpcFilterType::DataSize((8 + std::mem::size_of::()) as u64), > ]; > let accounts = rpc_client.get_program_accounts_with_config( > &KLEND_PROGRAM_ID, > RpcProgramAccountsConfig { > filters: Some(filters), > account_config: RpcAccountInfoConfig { > encoding: Some(UiAccountEncoding::Base64Zstd), > ..Default::default() > }, > ..Default::default() > }, > )?; > > for (pubkey, account) in &accounts { > let reserve = from_account_data::(account.data())?; > let borrowed: f64 = Fraction::from_bits(u128::from(reserve.liquidity.borrowed_amount_sf)).to_num(); > let price: f64 = Fraction::from_bits(u128::from(reserve.liquidity.market_price_sf)).to_num(); > > println!("Reserve: {pubkey}"); > println!(" Available liquidity: {}", reserve.liquidity.total_available_amount); > println!(" Borrowed amount: {borrowed:.6}"); > println!(" Market price: {price:.6}"); > println!(" Mint decimals: {}", reserve.liquidity.mint_decimals); > println!(" LTV: {}%", reserve.config.loan_to_value_pct); > println!(" Deposit limit: {}", reserve.config.deposit_limit); > println!(" Borrow limit: {}", reserve.config.borrow_limit); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/market_data.rs) **Step 3** ### Get Historical Reserve APY Fetch historical supply APY and borrow APY data for a specific reserve over time. ```typescript icon="typescript" getHistoricalReserveAPY theme={"theme":"css-variables"} const API_BASE_URL = "https://api.kamino.finance"; const marketPubkey = "7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF"; const reservePubkey = "d4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q"; const params = new URLSearchParams({ start: "2026-10-15T00:00:00.000Z", end: "2026-10-22T00:00:00.000Z", frequency: "day", }); const res = await fetch( `${API_BASE_URL}/kamino-market/${marketPubkey}/reserves/${reservePubkey}/metrics/history?${params}` ); if (!res.ok) { console.log(`Request failed: ${res.status} ${res.statusText}`); } const { history } = await res.json(); console.table( history.map((item) => ({ date: item.timestamp.slice(0, 10), symbol: item.metrics.symbol, supplyAPY: `${(item.metrics.supplyInterestAPY * 100).toFixed(2)}%`, borrowAPY: `${(item.metrics.borrowInterestAPY * 100).toFixed(2)}%`, depositTvlUsd: Number(item.metrics.depositTvl).toFixed(2), borrowTvlUsd: Number(item.metrics.borrowTvl).toFixed(2), })) ); ``` View Code ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples) # User Obligation Source: https://docs.kamino.com/build/developers/borrow/data/user-position-data ## Manage User Obligations Manage and retrieve user obligations, positions, and transaction history using the Kamino SDK and API. > [!NOTE] > > Historical obligation data is only available via the API. ### Get User Obligation Info Retrieve detailed obligation information including deposits, borrows, and health metrics. > [tab] TypeScript > > ```typescript expandable title="getUserObligation.ts" theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > VanillaObligation, > PROGRAM_ID, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const userAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligation = await market!.getObligationByWallet(userAddress, new VanillaObligation(PROGRAM_ID)); > > if (!obligation) { > console.log('No obligation found for user:', userAddress); > } > > const positions = [ > ...obligation!.getDeposits().map((position) => ({ side: 'deposit', ...position })), > ...obligation!.getBorrows().map((position) => ({ side: 'borrow', ...position })), > ]; > > console.table( > positions.map((position) => ({ > side: position.side, > symbol: market!.getReserveByAddress(position.reserveAddress)?.getTokenSymbol(), > amount: position.amount.div(position.mintFactor).toFixed(6), > valueUsd: position.marketValueRefreshed.toFixed(2), > })) > ); > > console.log({ > ltv: `${obligation!.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > liquidationLtv: `${obligation!.refreshedStats.liquidationLtv.mul(100).toFixed(2)}%`, > borrowUtilization: `${obligation!.refreshedStats.borrowUtilization.mul(100).toFixed(2)}%`, > }); > ``` > > View Code > [tab] Rust > > ```rust expandable title="get_user_obligation.rs" theme={"theme":"css-variables"} > use klend_interface::state::Obligation; > use klend_interface::{from_account_data, pda, Fraction, KLEND_PROGRAM_ID}; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let market_pubkey = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF")?; > let user_pubkey = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY")?; > > let (obligation_pubkey, _bump) = pda::obligation( > &KLEND_PROGRAM_ID, > 0, > 0, > &user_pubkey, > &market_pubkey, > &Pubkey::default(), > &Pubkey::default(), > ); > > let obligation_account = rpc_client.get_account(&obligation_pubkey)?; > let obligation = from_account_data::(&obligation_account.data)?; > println!("Obligation owner: {}", obligation.owner); > > println!("\nDeposits (Collateral):"); > for deposit in obligation.deposits.iter().filter(|d| d.deposit_reserve != Pubkey::default()) { > println!(" Reserve: {}", deposit.deposit_reserve); > println!(" Deposited amount (cTokens): {}", deposit.deposited_amount); > } > > println!("\nBorrows:"); > for borrow in obligation.borrows.iter().filter(|b| b.borrow_reserve != Pubkey::default()) { > let borrowed: f64 = Fraction::from_bits(u128::from(borrow.borrowed_amount_sf)).to_num(); > println!(" Reserve: {}", borrow.borrow_reserve); > println!(" Borrowed amount: {borrowed:.6}"); > } > > let deposited_value: f64 = Fraction::from_bits(u128::from(obligation.deposited_value_sf)).to_num(); > let allowed_borrow: f64 = Fraction::from_bits(u128::from(obligation.allowed_borrow_value_sf)).to_num(); > let unhealthy_borrow: f64 = Fraction::from_bits(u128::from(obligation.unhealthy_borrow_value_sf)).to_num(); > let borrowed_value: f64 = Fraction::from_bits(u128::from(obligation.borrow_factor_adjusted_debt_value_sf)).to_num(); > > println!("\nMetrics at the obligation's last refresh:"); > println!(" Deposited value: ${deposited_value:.2}"); > println!(" Allowed borrow value: ${allowed_borrow:.2}"); > println!(" Unhealthy borrow value: ${unhealthy_borrow:.2}"); > println!(" Current borrow value: ${borrowed_value:.2}"); > println!(" Borrowing disabled: {}", obligation.borrowing_disabled > 0); > ``` > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/user_position.rs) ### Get All User Obligations Retrieve all obligations for a user wallet, including different obligation types across the market. > [tab] TypeScript > > ```typescript expandable title="getAllUserObligations.ts" theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > ObligationTypeTag, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const userAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligations = await market!.getAllUserObligations(userAddress, await getCurrentLedgerInstant(rpc)); > > if (obligations.length === 0) { > console.log('No obligations found for wallet:', userAddress); > } > > for (const obligation of obligations) { > console.log(`\nObligation ${obligation.obligationAddress} (${ObligationTypeTag[obligation.obligationTag]})`); > console.table( > [ > ...obligation.getDeposits().map((position) => ({ side: 'deposit', ...position })), > ...obligation.getBorrows().map((position) => ({ side: 'borrow', ...position })), > ].map((position) => ({ > side: position.side, > symbol: market!.getReserveByAddress(position.reserveAddress)?.getTokenSymbol(), > amount: position.amount.div(position.mintFactor).toFixed(6), > valueUsd: position.marketValueRefreshed.toFixed(2), > })) > ); > console.log({ > ltv: `${obligation.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > liquidationLtv: `${obligation.refreshedStats.liquidationLtv.mul(100).toFixed(2)}%`, > }); > } > ``` > > View Code ### Get All Obligations by Reserve Retrieve all obligations that have deposits in a specific reserve. Useful for analyzing reserve utilization and user exposure. > [tab] TypeScript > > ```typescript expandable title="getAllObligationsByReserve.ts" theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > ObligationTypeTag, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const reserveAddress = address('37Jk2zkz23vkAYBT66HM2gaqJuNg2nYLsCreQAVt5MWK'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligations = await market!.getAllObligationsByDepositedReserve( > reserveAddress, > await getCurrentLedgerInstant(rpc) > ); > > console.log(`Found ${obligations.length} obligations with deposits in this reserve`); > > console.table( > obligations.map((obligation) => ({ > obligation: obligation.obligationAddress, > type: ObligationTypeTag[obligation.obligationTag], > depositUsd: obligation.getDepositByReserve(reserveAddress)?.marketValueRefreshed.toFixed(2), > totalBorrowsUsd: obligation.refreshedStats.userTotalBorrow.toFixed(2), > ltv: `${obligation.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > })) > ); > ``` > > > [!WARNING] > > > > This reads every obligation in the market. Public RPC endpoints reject it, so use a private RPC. > > View Code ### Get User Transaction History Access all transaction history for a user's wallet across deposits, borrows, repayments, and liquidations. > [tab] TypeScript > > ```typescript title="getTransactionHistory.ts" theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const marketPubkey = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; > const userPubkey = 'EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'; > > const res = await fetch(`${API_BASE_URL}/v2/kamino-market/${marketPubkey}/users/${userPubkey}/transactions`); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > > const transactionsByObligation = await res.json(); > > for (const [obligation, transactions] of Object.entries(transactionsByObligation)) { > console.log(`\nObligation ${obligation}`); > console.table( > transactions.map((tx) => ({ > date: tx.createdOn.slice(0, 10), > type: tx.transactionName, > token: tx.liquidityToken, > amount: tx.liquidityTokenAmount, > usdValue: Number(tx.liquidityUsdValue).toFixed(2), > })) > ); > } > ``` > > > [!NOTE] > > > > Results are grouped by obligation address. A market where the wallet has no obligation returns an empty object. > > View Code ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples) # Borrow & Lend Source: https://docs.kamino.com/build/developers/borrow/index Learn how to build with Borrow ## Overview Build lending applications on Solana using the Kamino TypeScript SDK, the Rust interface crate, or the REST API. This guide covers everything from basic setup to advanced transaction building for deposit, borrow, repay, and withdraw operations. ## Key Components of Borrow Integration > [card] Lending Operations > > Deposit collateral, borrow assets, repay debt, and withdraw - complete > lending lifecycle management. > [card] Loan Management > > LTV ratios, health factors, obligation status and position monitoring for > safe lending. > [card] Market Analytics > > APY tracking, utilization rates, reserve metrics from API and on-chain data. ## Integration Options > [card] Public API > > Access market data, borrow rates, reserve liquidity, and obligation status via REST endpoints. Language-agnostic. > [card] TypeScript SDK > > On-chain reads and transaction building for deposit, borrow, repay, and withdraw. TS/JS only. > [card] Rust Interface Crate > > Lightweight instruction builder for Rust bots and on-chain CPI. ### Deposit > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address, createNoopSigner } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import BN from 'bn.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const solMint = address('So11111111111111111111111111111111111111112'); > const owner = createNoopSigner(address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY')); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const solReserve = market!.getExistingFloatRateReserveByMint(solMint); > > const depositAction = await KaminoAction.buildDepositTxns({ > kaminoMarket: market!, > amount: new BN(10_000_000), > reserveAddress: solReserve.address, > owner, > obligation: new VanillaObligation(PROGRAM_ID), > useV2Ixs: true, > scopeRefreshConfig: undefined, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > > console.log(KaminoAction.actionToIxLabels(depositAction)); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-04-user-deposit-example/index.ts) > [tab] Rust > > ```rust theme={"theme":"css-variables"} > use klend_interface::helpers; > use klend_interface::ReserveInfo; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > use spl_associated_token_account::get_associated_token_address; > use std::str::FromStr; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > > // Fetch reserve data from the chain > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > let reserve_data = rpc_client.get_account(&reserve_pubkey)?; > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; > > // Derive user token accounts > let user_source_liquidity = get_associated_token_address(&owner, &reserve.liquidity_mint); > let (collateral_mint, _) = pda::reserve_collateral_mint(&KLEND_PROGRAM_ID, &reserve_pubkey); > let user_destination_collateral = get_associated_token_address(&owner, &collateral_mint); > > // Build deposit instructions (includes refresh_reserve automatically) > let instructions = helpers::deposit::deposit( > owner, > &reserve, > user_source_liquidity, > user_destination_collateral, > 1_000_000, // 1 USDC (6 decimals) > ); > > // Build and send > let message = Message::new(&instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Deposit successful! Signature: {signature}"); > ``` > [!NOTE] > > For the full deposit example, including transaction sending and confirmation, check out [Deposit Operations](/build/developers/borrow/operations/deposit). ### Withdraw > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address, createNoopSigner } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import BN from 'bn.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const solMint = address('So11111111111111111111111111111111111111112'); > const owner = createNoopSigner(address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY')); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const solReserve = market!.getExistingFloatRateReserveByMint(solMint); > const obligation = await market!.getObligationByWallet(owner.address, new VanillaObligation(PROGRAM_ID)); > > if (!obligation) { > console.log('No obligation found for', owner.address); > } > > const withdrawAction = await KaminoAction.buildWithdrawTxns({ > kaminoMarket: market!, > amount: new BN(5_000_000), > reserveAddress: solReserve.address, > owner, > obligation: obligation!, > useV2Ixs: true, > scopeRefreshConfig: undefined, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > > console.log(KaminoAction.actionToIxLabels(withdrawAction)); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-05-user-withdraw-example/index.ts) > [tab] Rust > > ```rust theme={"theme":"css-variables"} > use klend_interface::ObligationContext; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > use spl_associated_token_account::get_associated_token_address; > use std::str::FromStr; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > // Derive and fetch the obligation > let (obligation_pubkey, _) = pda::obligation( > &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, > &Pubkey::default(), &Pubkey::default(), > ); > let obligation_data = rpc_client.get_account(&obligation_pubkey)?; > > // Fetch all reserves referenced by the obligation > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() > .zip(reserve_accounts.iter()) > .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) > .collect(); > let ctx = ObligationContext::from_account_data( > obligation_pubkey, &obligation_data.data, &reserves > )?; > > // Derive user token account for the withdrawal token (e.g. USDC) > let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); > let user_dest_liquidity = get_associated_token_address(&owner, &liquidity_mint); > > // Build withdraw instructions (includes refresh_reserves + refresh_obligation) > let instructions = ctx.withdraw( > owner, > &reserve_pubkey, > user_dest_liquidity, > 1_000_000, // 1 USDC (6 decimals) > )?; > > // Build and send > let message = Message::new(&instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Withdrawal successful! Signature: {signature}"); > ``` > [!NOTE] > > For the full withdraw example, including transaction sending and confirmation, > check out [Withdraw Operations](/build/developers/borrow/operations/withdraw). ## Key Data Structures > [tab] TypeScript > > ##### Obligation > > ```typescript theme={"theme":"css-variables"} > class Obligation { > tag: BN; > lastUpdate: types.LastUpdate; > lendingMarket: Address; > owner: Address; > deposits: Array; > lowestReserveDepositLiquidationLtv: BN; > depositedValueSf: BN; > borrows: Array; > borrowFactorAdjustedDebtValueSf: BN; > borrowedAssetsMarketValueSf: BN; > allowedBorrowValueSf: BN; > unhealthyBorrowValueSf: BN; > paddingDeprecatedAssetTiers: Array; > elevationGroup: number; > numOfObsoleteDepositReserves: number; > hasDebt: number; > referrer: Address; > borrowingDisabled: number; > autodeleverageTargetLtvPct: number; > lowestReserveDepositMaxLtvPct: number; > numOfObsoleteBorrowReserves: number; > ownershipTransferState: number; > reserved: Array; > highestBorrowFactorPct: BN; > autodeleverageMarginCallStartedTimestamp: BN; > obligationOrders: Array; > headBorrowOrder: types.BorrowOrder; > pendingOwner: Address; > tailBorrowOrders: Array; > } > ``` > > > > [View Full TypeScript Obligation](https://github.com/Kamino-Finance/klend-sdk/blob/80f29fcda3ac954b400ceb3000999def487cff5c/src/%40codegen/klend/accounts/Obligation.ts#L145) > > **Fields** > > | Field | Type | Description | > | - | - | - | > | `tag` | `BN` | Version of the struct | > | `lastUpdate` | `types.LastUpdate` | Last update to collateral, liquidity, or their market values | > | `lendingMarket` | `Address` | Lending market address | > | `owner` | `Address` | Owner authority which can borrow liquidity | > | `deposits` | `Array` | Deposited collateral for the obligation, unique by deposit reserve address | > | `lowestReserveDepositLiquidationLtv` | `BN` | Worst LTV for the collaterals backing the loan, represented as a percentage | > | `depositedValueSf` | `BN` | Market value of deposits (scaled fraction) | > | `borrows` | `Array` | Borrowed liquidity for the obligation, unique by borrow reserve address | > | `borrowFactorAdjustedDebtValueSf` | `BN` | Risk adjusted market value of borrows/debt (scaled fraction) | > | `borrowedAssetsMarketValueSf` | `BN` | Market value of borrows - used for max_liquidatable_borrowed_amount (scaled fraction) | > | `allowedBorrowValueSf` | `BN` | The maximum borrow value at the weighted average loan to value ratio (scaled fraction) | > | `unhealthyBorrowValueSf` | `BN` | The dangerous borrow value at the weighted average liquidation threshold (scaled fraction) | > | `paddingDeprecatedAssetTiers` | `Array` | Unused; replaced the deposit and borrow asset tiers | > | `elevationGroup` | `number` | The elevation group id the obligation opted into | > | `numOfObsoleteDepositReserves` | `number` | The number of obsolete reserves the obligation has a deposit in | > | `hasDebt` | `number` | Marked = 1 if borrows array is not empty, 0 = borrows empty | > | `referrer` | `Address` | Wallet address of the referrer | > | `borrowingDisabled` | `number` | Marked = 1 if borrowing disabled, 0 = borrowing enabled | > | `autodeleverageTargetLtvPct` | `number` | A target LTV set by the risk council when marking this obligation for deleveraging | > | `lowestReserveDepositMaxLtvPct` | `number` | The lowest max LTV found amongst the collateral deposits | > | `numOfObsoleteBorrowReserves` | `number` | The number of obsolete reserves the obligation has a borrow in | > | `ownershipTransferState` | `number` | Whether an ownership transfer to `pendingOwner` is in progress | > | `reserved` | `Array` | Reserved space for future use | > | `highestBorrowFactorPct` | `BN` | The highest borrow factor percentage across all borrows | > | `autodeleverageMarginCallStartedTimestamp` | `BN` | Timestamp when risk council marked this obligation for deleveraging (zero if not applicable) | > | `obligationOrders` | `Array` | Owner-defined, liquidator-executed orders (e.g., stop-loss, take-profit) | > | `headBorrowOrder` | `types.BorrowOrder` | The obligation's first fixed-rate borrow order | > | `pendingOwner` | `Address` | New owner of a pending ownership transfer | > | `tailBorrowOrders` | `Array` | The obligation's other fixed-rate borrow orders | > [tab] JSON > > ##### Obligation > > ```json theme={"theme":"css-variables"} > { > "tag": "0", > "lastUpdate": {}, > "lendingMarket": "...", > "owner": "...", > "deposits": [], > "lowestReserveDepositLiquidationLtv": "0", > "depositedValueSf": "0", > "borrows": [], > "borrowFactorAdjustedDebtValueSf": "0", > "borrowedAssetsMarketValueSf": "0", > "allowedBorrowValueSf": "0", > "unhealthyBorrowValueSf": "0", > "depositsAssetTiers": [], > "borrowsAssetTiers": [], > "elevationGroup": 0, > "numOfObsoleteDepositReserves": 0, > "hasDebt": 0, > "referrer": "...", > "borrowingDisabled": 0, > "autodeleverageTargetLtvPct": 0, > "lowestReserveDepositMaxLtvPct": 0, > "numOfObsoleteBorrowReserves": 0, > "reserved": [], > "highestBorrowFactorPct": "0", > "autodeleverageMarginCallStartedTimestamp": "0", > "orders": [], > "padding3": [] > } > ``` > > [View Full JSON Obligation](https://github.com/Kamino-Finance/klend-sdk/blob/80f29fcda3ac954b400ceb3000999def487cff5c/src/%40codegen/klend/accounts/Obligation.ts#L81) > > **Fields** > > | Field | Type | Description | > | - | - | - | > | `tag` | `string` | Version of the struct | > | `lastUpdate` | `object` | Last update to collateral, liquidity, or their market values | > | `lendingMarket` | `string` | Lending market address | > | `owner` | `string` | Owner authority which can borrow liquidity | > | `deposits` | `array` | Deposited collateral for the obligation, unique by deposit reserve address | > | `lowestReserveDepositLiquidationLtv` | `string` | Worst LTV for the collaterals backing the loan, represented as a percentage | > | `depositedValueSf` | `string` | Market value of deposits (scaled fraction) | > | `borrows` | `array` | Borrowed liquidity for the obligation, unique by borrow reserve address | > | `borrowFactorAdjustedDebtValueSf` | `string` | Risk adjusted market value of borrows/debt (scaled fraction) | > | `borrowedAssetsMarketValueSf` | `string` | Market value of borrows - used for max_liquidatable_borrowed_amount (scaled fraction) | > | `allowedBorrowValueSf` | `string` | The maximum borrow value at the weighted average loan to value ratio (scaled fraction) | > | `unhealthyBorrowValueSf` | `string` | The dangerous borrow value at the weighted average liquidation threshold (scaled fraction) | > | `depositsAssetTiers` | `array` | The asset tier of the deposits | > | `borrowsAssetTiers` | `array` | The asset tier of the borrows | > | `elevationGroup` | `number` | The elevation group id the obligation opted into | > | `numOfObsoleteDepositReserves` | `number` | The number of obsolete reserves the obligation has a deposit in | > | `hasDebt` | `number` | Marked = 1 if borrows array is not empty, 0 = borrows empty | > | `referrer` | `string` | Wallet address of the referrer | > | `borrowingDisabled` | `number` | Marked = 1 if borrowing disabled, 0 = borrowing enabled | > | `autodeleverageTargetLtvPct` | `number` | A target LTV set by the risk council when marking this obligation for deleveraging | > | `lowestReserveDepositMaxLtvPct` | `number` | The lowest max LTV found amongst the collateral deposits | > | `numOfObsoleteBorrowReserves` | `number` | The number of obsolete reserves the obligation has a borrow in | > | `reserved` | `array` | Reserved space for future use | > | `highestBorrowFactorPct` | `string` | The highest borrow factor percentage across all borrows | > | `autodeleverageMarginCallStartedTimestamp` | `string` | Timestamp when risk council marked this obligation for deleveraging (zero if not applicable) | > | `orders` | `array` | Owner-defined, liquidator-executed orders (e.g., stop-loss, take-profit) | > [tab] Rust > > ##### Obligation > > ```rust theme={"theme":"css-variables"} > pub struct Obligation { > pub tag: u64, > pub last_update: LastUpdate, > pub lending_market: Pubkey, > pub owner: Pubkey, > pub deposits: [ObligationCollateral; 8], > pub lowest_reserve_deposit_liquidation_ltv: u64, > pub deposited_value_sf: PodU128, > pub borrows: [ObligationLiquidity; 5], > pub borrow_factor_adjusted_debt_value_sf: PodU128, > pub borrowed_assets_market_value_sf: PodU128, > pub allowed_borrow_value_sf: PodU128, > pub unhealthy_borrow_value_sf: PodU128, > pub padding_deprecated_asset_tiers: [u8; 13], > pub elevation_group: u8, > pub num_of_obsolete_deposit_reserves: u8, > pub has_debt: u8, > pub referrer: Pubkey, > pub borrowing_disabled: u8, > pub autodeleverage_target_ltv_pct: u8, > pub lowest_reserve_deposit_max_ltv_pct: u8, > pub num_of_obsolete_borrow_reserves: u8, > pub ownership_transfer_state: u8, > pub reserved: [u8; 3], > pub highest_borrow_factor_pct: u64, > pub autodeleverage_margin_call_started_timestamp: u64, > pub obligation_orders: [ObligationOrder; 2], > pub borrow_order: BorrowOrder, > pub pending_owner: Pubkey, > pub padding_3: [u64; 69], > } > ``` > > > > [View Full Rust Obligation](https://github.com/Kamino-Finance/klend/blob/5b37d7522aa070fad87f2fcf30bdf2e19d9e607a/programs/klend/src/state/obligation.rs#L23) > > **Fields** > > | Field | Type | Description | > | - | - | - | > | `tag` | `u64` | Version of the struct | > | `last_update` | `LastUpdate` | Last update to collateral, liquidity, or their market values | > | `lending_market` | `Pubkey` | Lending market address | > | `owner` | `Pubkey` | Owner authority which can borrow liquidity | > | `deposits` | `[ObligationCollateral; 8]` | Deposited collateral for the obligation, unique by deposit reserve address | > | `lowest_reserve_deposit_liquidation_ltv` | `u64` | Worst LTV for the collaterals backing the loan, represented as a percentage | > | `deposited_value_sf` | `PodU128` | Market value of deposits (scaled fraction) | > | `borrows` | `[ObligationLiquidity; 5]` | Borrowed liquidity for the obligation, unique by borrow reserve address | > | `borrow_factor_adjusted_debt_value_sf` | `PodU128` | Risk adjusted market value of borrows/debt (scaled fraction) | > | `borrowed_assets_market_value_sf` | `PodU128` | Market value of borrows (scaled fraction) | > | `allowed_borrow_value_sf` | `PodU128` | The maximum borrow value at the weighted average loan to value ratio (scaled fraction) | > | `unhealthy_borrow_value_sf` | `PodU128` | The dangerous borrow value at the weighted average liquidation threshold (scaled fraction) | > | `padding_deprecated_asset_tiers` | `[u8; 13]` | Unused; replaced the deposit and borrow asset tiers | > | `elevation_group` | `u8` | The elevation group id the obligation opted into | > | `num_of_obsolete_deposit_reserves` | `u8` | The number of obsolete reserves the obligation has a deposit in | > | `has_debt` | `u8` | 1 if the borrows array is not empty, 0 if empty | > | `referrer` | `Pubkey` | Wallet address of the referrer | > | `borrowing_disabled` | `u8` | 1 if borrowing is disabled, 0 if enabled | > | `autodeleverage_target_ltv_pct` | `u8` | A target LTV set by the risk council when marking this obligation for deleveraging | > | `lowest_reserve_deposit_max_ltv_pct` | `u8` | The lowest max LTV found amongst the collateral deposits | > | `num_of_obsolete_borrow_reserves` | `u8` | The number of obsolete reserves the obligation has a borrow in | > | `ownership_transfer_state` | `u8` | Whether an ownership transfer to `pending_owner` is in progress | > | `reserved` | `[u8; 3]` | Reserved space for future use | > | `highest_borrow_factor_pct` | `u64` | The highest borrow factor percentage across all borrows | > | `autodeleverage_margin_call_started_timestamp` | `u64` | Timestamp when risk council marked this obligation for deleveraging (zero if not applicable) | > | `obligation_orders` | `[ObligationOrder; 2]` | Owner-defined, liquidator-executed orders (e.g., stop-loss, take-profit) | > | `borrow_order` | `BorrowOrder` | The obligation's fixed-rate borrow order | > | `pending_owner` | `Pubkey` | New owner of a pending ownership transfer | > | `padding_3` | `[u64; 69]` | Reserved space for future use | ## Relevant Links > [card] [Fetch Market Data via the API](https://api-docs.kamino.com/) > > Access market metrics and performance data through REST endpoints. > [card] [Smart contract repository](https://github.com/Kamino-Finance/klend) > > Explore the on-chain program source code and documentation. > [card] [NPM SDK package](https://www.npmjs.com/package/@kamino-finance/klend-sdk) > > Install the TypeScript SDK to integrate borrowing and lending operations. > [card] [Rust Interface Crate](https://crates.io/crates/klend-interface) > > Lightweight Rust instruction builder for Kamino Lending operations. > [card] [More Borrow tutorials](/build/tutorials/borrow/index) > > Step-by-step guides for building with Kamino lending markets. # Build a Liquidation Bot with KSwap Source: https://docs.kamino.com/build/developers/borrow/liquidations/liquidation-bot Build a bot that monitors obligations, identifies profitable pairs, swaps into debt tokens via KSwap, and executes liquidations Liquidations on Kamino are permissionless. Any wallet can liquidate an unhealthy obligation and earn a bonus. Bots continuously monitor all obligations and execute when one crosses its health limit. ## Scanning for Unhealthy Positions The first step is loading every obligation in a market and checking which ones have breached their health limit. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, createSolanaRpcSubscriptions, address } from '@solana/kit'; > import { > KaminoMarket, > KaminoObligation, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **Step 2** > > ### Set Up RPC and Load Market > > ```typescript theme={"theme":"css-variables"} > const KEYPAIR_FILE = '/path/to/your/keypair.json'; > const liquidator = await parseKeypairFile(KEYPAIR_FILE); > > const rpc = createSolanaRpc('https://your-private-rpc.example.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://your-private-rpc.example.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); // SOL/BTC Market > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > > [!WARNING] > > > > Scanning reads every obligation in the market. Public RPC endpoints reject it, so use a private RPC. On the SOL/BTC Market it reads over 100,000 obligations and takes about five minutes. > > > [!NOTE] > > > > Kamino operates multiple markets (SOL/BTC, JLP, Altcoins, Prime). A production bot should scan all of them. See [Markets](/products/borrow/markets) for the full list. > > **Step 3** > > ### Scan Obligations in Batches > > An obligation is liquidatable when its LTV reaches its liquidation LTV. The scan also tracks the obligation closest to liquidation. > > ```typescript theme={"theme":"css-variables"} > const healthRatio = (obligation: KaminoObligation) => obligation.loanToValue().div(obligation.liquidationLtv()); > > const liquidatable: KaminoObligation[] = []; > let closest: KaminoObligation | undefined; > let scanned = 0; > > for await (const batch of market!.batchGetAllObligationsForMarket(await getCurrentLedgerInstant(rpc))) { > scanned += batch.length; > const withDebt = batch.filter( > (obligation) => obligation.refreshedStats.userTotalBorrow.gt(0) && obligation.liquidationLtv().gt(0) > ); > liquidatable.push(...withDebt.filter((obligation) => healthRatio(obligation).gte(1))); > closest = withDebt.reduce((a, b) => (healthRatio(b).gt(healthRatio(a!)) ? b : a), closest ?? withDebt[0]); > } > > console.log(`Scanned ${scanned} obligations, ${liquidatable.length} liquidatable`); > ``` > > > [!NOTE] > > > > `loanToValue()` and `liquidationLtv()` compute both at current prices over all deposits, the way the program checks. Don't use the obligation's stored values such as `getUnhealthyBorrowValue()`: they're from its last on-chain refresh and can mark a healthy obligation as liquidatable. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = { version = "0.6.0", features = ["solana-account"] } > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > solana-account = "2.1" > solana-account-decoder-client-types = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > reqwest = { version = "~0.12", features = ["blocking", "json"] } > serde = { version = "1", features = ["derive"] } > serde_json = "1" > bincode = "1" > base64 = "0.22" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let rpc_client = RpcClient::new("YOUR_RPC_URL"); > let market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF")?; > ``` > > > [!WARNING] > > > > Scanning obligations requires `getProgramAccounts`, which returns thousands of accounts per market. The public Solana RPC will reject these calls. Use a private RPC provider (Helius, Triton, QuickNode, etc.). > > **Step 3** > > ### Fetch All Obligations > > Fetch every obligation in the market using `get_program_accounts` with filters for the discriminator, lending market, and account size. > > ```rust theme={"theme":"css-variables"} > use klend_interface::{ > state::{Obligation, SplDiscriminate}, > KLEND_PROGRAM_ID, > }; > use solana_account::ReadableAccount; > use solana_account_decoder_client_types::UiAccountEncoding; > use solana_client::{ > rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig}, > rpc_filter::{Memcmp, RpcFilterType}, > }; > > const OBLIGATION_ACCOUNT_SIZE: u64 = 8 + std::mem::size_of::() as u64; > > let filters = vec![ > RpcFilterType::Memcmp(Memcmp::new_raw_bytes( > 0, > Obligation::SPL_DISCRIMINATOR_SLICE.to_vec(), > )), > RpcFilterType::Memcmp(Memcmp::new_raw_bytes(32, market.to_bytes().to_vec())), > RpcFilterType::DataSize(OBLIGATION_ACCOUNT_SIZE), > ]; > > let config = RpcProgramAccountsConfig { > filters: Some(filters), > account_config: RpcAccountInfoConfig { > encoding: Some(UiAccountEncoding::Base64Zstd), > ..Default::default() > }, > ..Default::default() > }; > > let accounts = rpc_client.get_program_accounts_with_config(&KLEND_PROGRAM_ID, config)?; > ``` > > > [!WARNING] > > > > Obligation accounts exceed the 128-byte limit for base58 responses. Use `Base64Zstd` encoding or the RPC will silently return zero results. > > **Step 4** > > ### Filter to Liquidatable Positions > > Parse each obligation and check `is_liquidatable()`, which returns true when borrow-factor-adjusted debt exceeds the unhealthy borrow value. > > ```rust theme={"theme":"css-variables"} > use klend_interface::Fraction; > > let mut liquidatable = Vec::new(); > > for (pubkey, account) in &accounts { > let obligation = klend_interface::from_account_data::(account.data())?; > > if obligation.has_debt == 0 { > continue; > } > > if obligation.is_liquidatable() { > let debt: f64 = Fraction::from_bits( > obligation.borrowed_assets_market_value() > ).to_num(); > > println!("Liquidatable: {pubkey} — debt: ${debt:.2}"); > liquidatable.push((*pubkey, obligation)); > } > } > > println!("Initial candidates (stale prices): {}", liquidatable.len()); > ``` > > **Step 5** > > ### Verify with Fresh Prices > > On-chain obligation values are only updated when `RefreshObligation` is called. Fetch fresh oracle prices from the Scope REST API and re-verify each candidate to avoid wasting transaction fees on false positives. > > ```rust theme={"theme":"css-variables"} > use klend_interface::state::{Reserve, from_account_data}; > use serde::Deserialize; > use std::collections::{HashMap, HashSet}; > > #[derive(Deserialize)] > struct OraclePrice { > mint: String, > price: String, > } > > // Collect all reserve pubkeys from candidates > let reserve_pubkeys: Vec = liquidatable > .iter() > .flat_map(|(_, obl)| { > obl.deposits.iter().map(|d| d.deposit_reserve) > .chain(obl.borrows.iter().map(|b| b.borrow_reserve)) > .filter(|pk| *pk != Pubkey::default()) > }) > .collect::>() > .into_iter() > .collect(); > > // Fetch reserves to map mints to prices and get borrow factors > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_pubkeys)?; > let reserve_map: HashMap = reserve_pubkeys > .iter() > .zip(reserve_accounts.iter()) > .filter_map(|(pk, acc)| { > acc.as_ref().and_then(|a| { > from_account_data::(&a.data).ok().map(|r| (*pk, *r)) > }) > }) > .collect(); > > // Fetch fresh prices from the Scope REST API > let fresh_prices: HashMap = reqwest::blocking::get( > "https://api.kamino.finance/oracles/prices", > ) > .ok() > .and_then(|r| r.json::>().ok()) > .map(|prices| prices.into_iter() > .filter_map(|p| p.price.parse::().ok().map(|v| (p.mint, v))) > .collect()) > .unwrap_or_default(); > > let mut verified = Vec::new(); > > for (pubkey, obligation) in &liquidatable { > // Re-price deposits > let mut fresh_deposited = 0.0f64; > let mut fresh_unhealthy = 0.0f64; > for deposit in &obligation.deposits { > if deposit.deposit_reserve == Pubkey::default() { continue; } > let reserve = match reserve_map.get(&deposit.deposit_reserve) { > Some(r) => r, > None => continue, > }; > let mint = reserve.liquidity.mint_pubkey; > let stale_price: f64 = Fraction::from_bits( > u128::from(reserve.liquidity.market_price_sf) > ).to_num(); > let price = fresh_prices.get(&mint.to_string()).copied().unwrap_or(stale_price); > let amount: f64 = Fraction::from_bits(deposit.deposited_amount.into()).to_num(); > let value = amount / 10f64.powi(reserve.liquidity.mint_decimals as i32) * price; > fresh_deposited += value; > fresh_unhealthy += value * reserve.liquidation_threshold_pct() as f64 / 100.0; > } > > // Re-price borrows > let mut fresh_adjusted_debt = 0.0f64; > for borrow in &obligation.borrows { > if borrow.borrow_reserve == Pubkey::default() { continue; } > let reserve = match reserve_map.get(&borrow.borrow_reserve) { > Some(r) => r, > None => continue, > }; > let mint = reserve.liquidity.mint_pubkey; > let stale_price: f64 = Fraction::from_bits( > u128::from(reserve.liquidity.market_price_sf) > ).to_num(); > let price = fresh_prices.get(&mint.to_string()).copied().unwrap_or(stale_price); > let amount: f64 = Fraction::from_bits(borrow.borrowed_amount()).to_num(); > let value = amount / 10f64.powi(reserve.liquidity.mint_decimals as i32) * price; > fresh_adjusted_debt += value * reserve.borrow_factor_pct() as f64 / 100.0; > } > > // Still liquidatable at fresh prices? > if fresh_adjusted_debt > fresh_unhealthy { > verified.push((*pubkey, *obligation)); > } > } > > println!("Verified {} out of {} candidates with fresh prices", verified.len(), liquidatable.len()); > ``` ## Picking the Most Profitable Pair An obligation can have multiple collateral deposits and multiple borrows. The liquidator must choose one debt token to repay and one collateral token to seize. The program enforces priority rules: target the lowest-threshold collateral and the highest-borrow-factor debt first. > [tab] TypeScript > > **Step 1** > > ### Choose the Obligation > > Liquidations are rare. When the scan finds none, print the closest obligation and stop before swapping anything. > > ```typescript theme={"theme":"css-variables"} > if (liquidatable.length === 0) { > console.log('Closest to liquidation:', closest?.obligationAddress, `health ratio ${closest && healthRatio(closest).toFixed(4)}`); > process.exit(0); > } > > const obligation = liquidatable[0]; > ``` > > **Step 2** > > ### Select the Target Pair > > Seize the riskiest collateral (lowest liquidation threshold) and repay the most heavily weighted debt (highest borrow factor). > > ```typescript theme={"theme":"css-variables"} > const [collateral] = obligation > .getDeposits() > .map((position) => market!.getReserveByAddress(position.reserveAddress)!) > .filter((reserve) => reserve.state.config.loanToValuePct > 0) > .sort((a, b) => a.state.config.liquidationThresholdPct - b.state.config.liquidationThresholdPct); > > const [debtPosition] = obligation > .getBorrows() > .sort( > (a, b) => > Number(market!.getReserveByAddress(b.reserveAddress)!.state.config.borrowFactorPct) - > Number(market!.getReserveByAddress(a.reserveAddress)!.state.config.borrowFactorPct) > ); > const debtReserve = market!.getReserveByAddress(debtPosition.reserveAddress)!; > ``` > [tab] Rust > > **Step 1** > > ### Fetch Reserve Data > > Collect all unique reserve pubkeys from the obligation's deposits and borrows, then fetch and parse them in one RPC call. > > ```rust theme={"theme":"css-variables"} > use klend_interface::state::{Reserve, from_account_data}; > use std::collections::HashSet; > > let active_deposits: Vec<_> = obligation > .deposits > .iter() > .filter(|d| d.deposit_reserve != Pubkey::default()) > .collect(); > > let active_borrows: Vec<_> = obligation > .borrows > .iter() > .filter(|b| b.borrow_reserve != Pubkey::default()) > .collect(); > > let reserve_pubkeys: Vec = active_deposits > .iter() > .map(|d| d.deposit_reserve) > .chain(active_borrows.iter().map(|b| b.borrow_reserve)) > .collect::>() > .into_iter() > .collect(); > > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_pubkeys)?; > > let parsed_reserves: Vec<(Pubkey, Reserve)> = reserve_pubkeys > .iter() > .zip(reserve_accounts.iter()) > .filter_map(|(pk, acc_opt)| { > let acc = acc_opt.as_ref()?; > let reserve = from_account_data::(&acc.data).ok()?; > Some((*pk, *reserve)) > }) > .collect(); > ``` > > **Step 2** > > ### Sort by Priority > > Sort deposits by `liquidation_threshold_pct` ascending (weakest collateral first) and borrows by `borrow_factor_pct` descending (riskiest debt first). > > ```rust theme={"theme":"css-variables"} > let mut deposit_pairs: Vec<(Pubkey, &Reserve)> = active_deposits > .iter() > .filter_map(|d| { > parsed_reserves > .iter() > .find(|(pk, _)| *pk == d.deposit_reserve) > .map(|(pk, r)| (*pk, r)) > }) > .collect(); > > deposit_pairs.sort_by_key(|(_, r)| r.liquidation_threshold_pct()); > > let mut borrow_pairs: Vec<(Pubkey, &Reserve)> = active_borrows > .iter() > .filter_map(|b| { > parsed_reserves > .iter() > .find(|(pk, _)| *pk == b.borrow_reserve) > .map(|(pk, r)| (*pk, r)) > }) > .collect(); > > borrow_pairs.sort_by(|(_, a), (_, b)| b.borrow_factor_pct().cmp(&a.borrow_factor_pct())); > ``` > > **Step 3** > > ### Select the Target Pair > > The first entry in each sorted list is the priority target. Collateral reserves with `loan_to_value_pct == 0` are deposit-only and cannot be seized. > > ```rust theme={"theme":"css-variables"} > let withdraw_pair = deposit_pairs > .iter() > .find(|(_, r)| r.loan_to_value_pct() > 0); > > let repay_pair = borrow_pairs.first(); > > match (withdraw_pair, repay_pair) { > (Some((coll_pk, coll_reserve)), Some((debt_pk, debt_reserve))) => { > println!("Seize collateral: {coll_pk} (mint: {})", coll_reserve.liquidity.mint_pubkey); > println!("Repay debt: {debt_pk} (mint: {})", debt_reserve.liquidity.mint_pubkey); > } > _ => println!("No valid liquidation pair found"), > } > ``` ## Executing the Liquidation Once an unhealthy obligation and target pair have been identified, build and send the liquidation transaction. > [tab] TypeScript > > **Step 1** > > ### Import Transaction Utilities > > ```typescript theme={"theme":"css-variables"} > import { > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > compressTransactionMessageUsingAddressLookupTables, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > type Address, > type Instruction, > } from '@solana/kit'; > import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; > import { KaminoAction } from '@kamino-finance/klend-sdk'; > import { KswapSdk, loadRouterContext } from '@kamino-finance/kswap-sdk'; > import BN from 'bn.js'; > import Decimal from 'decimal.js'; > ``` > > **Step 2** > > ### Calculate Repay Amount > > One liquidation can repay up to the market's close factor share of the debt. > > ```typescript theme={"theme":"css-variables"} > const SLIPPAGE_BPS = 50; > const MAX_COMPUTE_UNITS = 1_400_000; > const slippage = new Decimal(SLIPPAGE_BPS).div(10_000); > > const repayLamports = debtPosition.amount.mul(market!.state.liquidationMaxDebtCloseFactorPct).div(100).floor(); > const repayUsd = repayLamports.div(debtReserve.getMintFactor()).mul(debtReserve.getOracleMarketPrice()); > > console.log(`Liquidating ${obligation.obligationAddress}: repay ${repayUsd.toFixed(2)} USD of ${debtReserve.getTokenSymbol()}`); > ``` > > **Step 3** > > ### Size the SOL Swap > > Price the repay in SOL with the market's own oracle prices, plus slippage, and check the wallet holds it. > > ```typescript theme={"theme":"css-variables"} > const solMint = address('So11111111111111111111111111111111111111112'); > const solReserve = market!.getExistingFloatRateReserveByMint(solMint); > > const solLamports = repayUsd > .div(solReserve.getOracleMarketPrice()) > .mul(solReserve.getMintFactor()) > .mul(slippage.plus(1)) > .ceil(); > > const { value: balance } = await rpc.getBalance(liquidator.address).send(); > if (solLamports.gt(balance.toString())) { > console.log(`Not enough SOL: need ${solLamports.div(solReserve.getMintFactor())} SOL for the swap`); > process.exit(0); > } > ``` > > **Step 4** > > ### Define a Send Helper > > ```typescript theme={"theme":"css-variables"} > const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); > > async function send(instructions: Instruction[], lookupTableAddresses: Record) { > const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signedTransaction = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayerSigner(liquidator, tx), > (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), > (tx) => appendTransactionMessageInstructions(instructions, tx), > (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) > ) > ); > assertIsTransactionWithinSizeLimit(signedTransaction); > await sendAndConfirm(signedTransaction, { commitment: 'confirmed', skipPreflight: true }); > return getSignatureFromTransaction(signedTransaction); > } > ``` > > **Step 5** > > ### Swap SOL into the Debt Token via KSwap > > ```typescript theme={"theme":"css-variables"} > const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); > > const { routes } = await kswap.getAllRoutes( > { > executor: liquidator.address, > tokenIn: solMint, > tokenOut: debtPosition.mintAddress, > amount: new BN(solLamports.toFixed(0)), > maxSlippageBps: SLIPPAGE_BPS, > swapType: 'exactIn', > wrapAndUnwrapSol: true, > }, > await loadRouterContext(rpc, solMint, debtPosition.mintAddress) > ); > if (routes.length === 0) { > console.log('No KSwap route found for SOL ->', debtPosition.mintAddress); > } > > const [swapRoute] = routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); > const swapIxs = swapRoute.instructions!; > > const swapSignature = await send( > [...swapIxs.createInAtaIxs, ...swapIxs.wrapSolIxs, ...swapIxs.swapIxs, ...swapIxs.unwrapSolIxs, ...swapIxs.createOutAtaIxs], > Object.fromEntries((swapRoute.lookupTableAccounts ?? []).map((lut) => [lut.address, lut.data.addresses])) > ); > console.log('Swapped SOL into the debt token:', swapSignature); > ``` > > > [!NOTE] > > > > Use `@kamino-finance/kswap-sdk` 2.9.0, the last version on `@solana/kit` 2. The swap is exact-in so every KSwap router is available: exact-out routes currently come only from Jupiter-based routers. > > **Step 6** > > ### Calculate Minimum Collateral > > The minimum collateral to accept assumes the smallest liquidation bonus, takes off the protocol's liquidation fee, and allows for slippage. > > ```typescript theme={"theme":"css-variables"} > const collateralConfig = collateral.state.config; > > const minCollateralLamports = repayUsd > .mul(new Decimal(collateralConfig.minLiquidationBonusBps).div(10_000).plus(1)) > .mul(new Decimal(1).minus(new Decimal(collateralConfig.protocolLiquidationFeePct).div(100))) > .mul(new Decimal(1).minus(slippage)) > .div(collateral.getOracleMarketPrice()) > .mul(collateral.getMintFactor()) > .floor(); > ``` > > **Step 7** > > ### Build the Liquidation Instructions > > ```typescript theme={"theme":"css-variables"} > const liquidateAction = await KaminoAction.buildLiquidateTxns({ > kaminoMarket: market!, > amount: new BN(repayLamports.toFixed(0)), > minCollateralReceiveAmount: new BN(minCollateralLamports.toFixed(0)), > repayReserveAddress: debtReserve.address, > withdrawReserveAddress: collateral.address, > liquidator, > obligationOwner: obligation.state.owner, > obligation, > useV2Ixs: true, > extraComputeBudget: MAX_COMPUTE_UNITS, > initUserMetadata: { skipInitialization: true, skipLutCreation: true }, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > > const liquidateIxs = KaminoAction.actionToIxs(liquidateAction); > ``` > > **Step 8** > > ### Fetch Lookup Tables and Send > > ```typescript theme={"theme":"css-variables"} > const addresses = [ > ...new Set(liquidateIxs.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), > ]; > > const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > body: JSON.stringify({ addresses }), > }); > if (!lutResponse.ok) { > console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); > } > > const { lutAddresses } = await lutResponse.json(); > const lookupTables = await fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); > > const liquidationSignature = await send( > liquidateIxs, > Object.fromEntries(lookupTables.map((lut) => [lut.address, lut.data.addresses])) > ); > console.log('Liquidation executed:', liquidationSignature); > ``` > > > [!TIP] > > > > The debt is repaid and the collateral, including the liquidation bonus, is in the liquidator's wallet. > [tab] Rust > > **Step 1** > > ### Fetch Obligation and Reserves > > Use `ObligationContext` to discover all reserves referenced by the obligation, then fetch them in one RPC call. > > ```rust theme={"theme":"css-variables"} > use klend_interface::{ > helpers::refresh, > instructions::liquidate::{ > liquidate_obligation_and_redeem_reserve_collateral_v2, > LiquidateObligationAndRedeemReserveCollateralV2Accounts, > }, > pda, > state::{LendingMarket, Obligation, Reserve, from_account_data}, > Fraction, ObligationContext, ObligationInfo, ReserveInfo, KLEND_PROGRAM_ID, > }; > use solana_instruction::AccountMeta; > use solana_sdk::signer::{keypair::read_keypair_file, Signer}; > > let signer = read_keypair_file("/path/to/liquidator-keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > > let obligation_account = rpc_client.get_account(&obligation_pubkey)?; > let obligation = from_account_data::(&obligation_account.data)?; > > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation( > &obligation_account.data, > )?; > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > > let parsed_reserves: Vec<(Pubkey, Reserve)> = reserve_addrs > .iter() > .zip(reserve_accounts.iter()) > .filter_map(|(pk, acc)| { > acc.as_ref().and_then(|a| { > from_account_data::(&a.data).ok().map(|r| (*pk, *r)) > }) > }) > .collect(); > > let repay_reserve = parsed_reserves.iter() > .find(|(pk, _)| *pk == repay_reserve_pubkey) > .map(|(_, r)| r) > .expect("Repay reserve not found"); > > let withdraw_reserve = parsed_reserves.iter() > .find(|(pk, _)| *pk == withdraw_reserve_pubkey) > .map(|(_, r)| r) > .expect("Withdraw reserve not found"); > ``` > > **Step 2** > > ### Calculate Repay Amount > > Fetch the `LendingMarket` account to read the close factor, then calculate the maximum repayable amount from the borrow position. > > ```rust theme={"theme":"css-variables"} > let borrow_position = obligation.borrows.iter() > .find(|b| b.borrow_reserve == repay_reserve_pubkey) > .expect("Borrow position not found"); > > let borrowed_amount: u64 = Fraction::from_bits( > borrow_position.borrowed_amount() > ).to_num(); > > let market_account = rpc_client.get_account(&obligation.lending_market)?; > let lending_market = from_account_data::(&market_account.data)?; > > let close_factor = lending_market.liquidation_max_debt_close_factor_pct; > let repay_amount = (borrowed_amount as f64 * close_factor as f64 / 100.0) as u64; > ``` > > **Step 3** > > ### Swap into Debt Token via KSwap > > If the liquidator does not hold the debt token, swap into it using the KSwap REST API before liquidating. > > ```rust theme={"theme":"css-variables"} > use serde::Deserialize; > use solana_sdk::transaction::VersionedTransaction; > > #[derive(Deserialize)] > struct KswapResponse { data: KswapData } > > #[derive(Deserialize)] > #[serde(rename_all = "camelCase")] > struct KswapData { > transaction: String, > expected_amount_out: String, > min_amount_out: String, > } > > let liquidator_debt_ata = > spl_associated_token_account::get_associated_token_address_with_program_id( > &owner, > &repay_reserve.liquidity.mint_pubkey, > &repay_reserve.liquidity.token_program, > ); > > use spl_token::state::Account as TokenAccount; > use solana_sdk::program_pack::Pack; > > let wallet_balance = rpc_client.get_account(&liquidator_debt_ata) > .ok() > .and_then(|a| TokenAccount::unpack(&a.data).ok()) > .map(|acct| acct.amount) > .unwrap_or(0); > > if wallet_balance < repay_amount { > let wsol = Pubkey::from_str("So11111111111111111111111111111111111111112")?; > > // Calculate how much SOL to swap based on debt USD value > let debt_price: f64 = Fraction::from_bits( > u128::from(repay_reserve.liquidity.market_price_sf) > ).to_num(); > let repay_usd = repay_amount as f64 > / 10f64.powi(repay_reserve.liquidity.mint_decimals as i32) * debt_price; > let sol_price = parsed_reserves.iter() > .find(|(_, r)| r.liquidity.mint_pubkey == wsol) > .map(|(_, r)| Fraction::from_bits( > u128::from(r.liquidity.market_price_sf) > ).to_num::()) > .unwrap_or(100.0); > let sol_balance = rpc_client.get_balance(&owner)?; > let swap_amount = (repay_usd / sol_price * 1e9) as u64; > let swap_amount = swap_amount.min(sol_balance.saturating_sub(5_000_000)); > > let client = reqwest::blocking::Client::new(); > let resp = client > .get("https://api.kamino.finance/kswap/swap/") > .query(&[ > ("tokenIn", wsol.to_string()), > ("tokenOut", repay_reserve.liquidity.mint_pubkey.to_string()), > ("amountIn", swap_amount.to_string()), > ("maxSlippageBps", "50".to_string()), > ("wallet", owner.to_string()), > ("wrapAndUnwrapSol", "true".to_string()), > ]) > .send()?; > > if !resp.status().is_success() { > let status = resp.status(); > let body = resp.text().unwrap_or_default(); > return Err(format!("KSwap API error {status}: {body}").into()); > } > > let kswap: KswapResponse = resp.json()?; > > // Decode, re-sign, and send the swap transaction > use base64::Engine; > let tx_bytes = base64::engine::general_purpose::STANDARD > .decode(&kswap.data.transaction)?; > let swap_tx: VersionedTransaction = bincode::deserialize(&tx_bytes)?; > let blockhash = rpc_client.get_latest_blockhash()?; > let mut msg = swap_tx.message; > msg.set_recent_blockhash(blockhash); > let signed = VersionedTransaction::try_new(msg, &[&signer])?; > rpc_client.send_and_confirm_transaction_with_spinner(&signed)?; > } > ``` > > **Step 4** > > ### Derive Token Accounts > > Derive ATAs using the actual token programs from the reserve data. The collateral cToken mint address is read directly from the `Reserve` struct. > > ```rust theme={"theme":"css-variables"} > let user_source_liquidity = > spl_associated_token_account::get_associated_token_address_with_program_id( > &owner, > &repay_reserve.liquidity.mint_pubkey, > &repay_reserve.liquidity.token_program, > ); > > let ctoken_mint = withdraw_reserve.collateral.mint_pubkey; > let ctoken_program = rpc_client.get_account(&ctoken_mint) > .map(|a| a.owner) > .unwrap_or(spl_token::ID); > > let user_destination_collateral = > spl_associated_token_account::get_associated_token_address_with_program_id( > &owner, &ctoken_mint, &ctoken_program, > ); > > let user_destination_liquidity = > spl_associated_token_account::get_associated_token_address_with_program_id( > &owner, > &withdraw_reserve.liquidity.mint_pubkey, > &withdraw_reserve.liquidity.token_program, > ); > ``` > > **Step 5** > > ### Create Token Accounts > > Create the associated token accounts if they do not already exist. Uses `create_associated_token_account_idempotent` which is a no-op if the account is already initialized. > > ```rust theme={"theme":"css-variables"} > let ata_ixs = vec![ > spl_associated_token_account::instruction::create_associated_token_account_idempotent( > &owner, &owner, &repay_reserve.liquidity.mint_pubkey, &repay_reserve.liquidity.token_program, > ), > spl_associated_token_account::instruction::create_associated_token_account_idempotent( > &owner, &owner, &ctoken_mint, &ctoken_program, > ), > spl_associated_token_account::instruction::create_associated_token_account_idempotent( > &owner, &owner, &withdraw_reserve.liquidity.mint_pubkey, &withdraw_reserve.liquidity.token_program, > ), > ]; > > let blockhash = rpc_client.get_latest_blockhash()?; > let ata_tx = Transaction::new(&[&signer], Message::new(&ata_ixs, Some(&owner)), blockhash); > rpc_client.send_and_confirm_transaction(&ata_tx)?; > ``` > > **Step 6** > > ### Build Liquidation Instructions > > Build refresh instructions for each reserve and the obligation, then the liquidation instruction using actual addresses from the `Reserve` struct. > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let (lma, _) = pda::lending_market_authority( > &KLEND_PROGRAM_ID, &repay_reserve.lending_market, > ); > > let obligation_info = ObligationInfo::from_obligation( > obligation_pubkey, obligation, > ); > > let all_reserve_infos: Vec = parsed_reserves.iter() > .map(|(pk, r)| ReserveInfo::from_reserve(*pk, r)) > .collect(); > > // Refresh reserves and obligation > let mut instructions = Vec::new(); > for info in &all_reserve_infos { > if obligation_info.deposit_reserves.contains(&info.address) > || obligation_info.borrow_reserves.contains(&info.address) > { > instructions.push(refresh::refresh_reserve(info)); > } > } > instructions.push(refresh::refresh_obligation( > &repay_reserve.lending_market, &obligation_info, > )); > > // Remaining accounts: deposit reserves + borrow reserves > let mut remaining: Vec = Vec::new(); > for r in &obligation_info.deposit_reserves { > remaining.push(AccountMeta::new(*r, false)); > } > for r in &obligation_info.borrow_reserves { > remaining.push(AccountMeta::new(*r, false)); > } > > // Calculate slippage protection to guard against sandwich attacks. > // Without this, a malicious validator could reorder transactions > // to extract the full liquidation bonus. > const MIN_RECEIVED_SLIPPAGE_BPS: u16 = 200; // 2% > > let collateral_price: f64 = Fraction::from_bits( > u128::from(withdraw_reserve.liquidity.market_price_sf) > ).to_num(); > let collateral_decimals = withdraw_reserve.liquidity.mint_decimals; > let bonus_bps = withdraw_reserve.config.min_liquidation_bonus_bps as f64; > let protocol_fee_pct = withdraw_reserve.config.protocol_liquidation_fee_pct as f64; > > let debt_price: f64 = Fraction::from_bits( > u128::from(repay_reserve.liquidity.market_price_sf) > ).to_num(); > let repay_usd = repay_amount as f64 > / 10f64.powi(repay_reserve.liquidity.mint_decimals as i32) * debt_price; > > let min_received = if collateral_price > 0.0 { > let collateral_value = repay_usd * (1.0 + bonus_bps / 10_000.0); > let after_fee = collateral_value * (1.0 - protocol_fee_pct / 100.0); > let expected_tokens = after_fee / collateral_price > * 10f64.powi(collateral_decimals as i32); > let with_slippage = expected_tokens > * (10_000.0 - MIN_RECEIVED_SLIPPAGE_BPS as f64) / 10_000.0; > (with_slippage as u64).max(1) > } else { > 1 > }; > > // Liquidation instruction with actual reserve struct addresses > instructions.push(liquidate_obligation_and_redeem_reserve_collateral_v2( > LiquidateObligationAndRedeemReserveCollateralV2Accounts { > liquidator: owner, > obligation: obligation_pubkey, > lending_market: repay_reserve.lending_market, > lending_market_authority: lma, > repay_reserve: repay_reserve_pubkey, > repay_reserve_liquidity_mint: repay_reserve.liquidity.mint_pubkey, > repay_reserve_liquidity_supply: repay_reserve.liquidity.supply_vault, > withdraw_reserve: withdraw_reserve_pubkey, > withdraw_reserve_liquidity_mint: withdraw_reserve.liquidity.mint_pubkey, > withdraw_reserve_collateral_mint: withdraw_reserve.collateral.mint_pubkey, > withdraw_reserve_collateral_supply: withdraw_reserve.collateral.supply_vault, > withdraw_reserve_liquidity_supply: withdraw_reserve.liquidity.supply_vault, > withdraw_reserve_liquidity_fee_receiver: withdraw_reserve.liquidity.fee_vault, > user_source_liquidity, > user_destination_collateral, > user_destination_liquidity, > repay_liquidity_token_program: repay_reserve.liquidity.token_program, > withdraw_liquidity_token_program: withdraw_reserve.liquidity.token_program, > collateral_obligation_farm_user_state: None, > collateral_reserve_farm_state: None, > debt_obligation_farm_user_state: None, > debt_reserve_farm_state: None, > }, > repay_amount, > min_received, > 0, // max_allowed_ltv_override_percent (must be 0 on mainnet) > remaining, > )); > ``` > > > [!WARNING] > > > > The `helpers::liquidate::liquidate()` helper uses `ReservePdas::derive()` which does not match reserves created by older program versions. Use the actual addresses from the `Reserve` struct as shown above. > > **Step 7** > > ### Simulate and Send > > ```rust theme={"theme":"css-variables"} > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let message = Message::new(&instructions, Some(&owner)); > let tx = Transaction::new(&[&signer], message, recent_blockhash); > > // Simulate first > let sim = rpc_client.simulate_transaction(&tx)?; > if let Some(err) = sim.value.err { > println!("Simulation failed: {err}"); > return Ok(()); > } > > // Send with fresh blockhash > let fresh_blockhash = rpc_client.get_latest_blockhash()?; > let fresh_msg = Message::new(&instructions, Some(&owner)); > let fresh_tx = Transaction::new(&[&signer], fresh_msg, fresh_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&fresh_tx)?; > println!("Liquidation executed: {signature}"); > ``` # The Liquidation Engine Source: https://docs.kamino.com/build/developers/borrow/liquidations/liquidation-engine How Kamino's liquidation engine limits collateral loss for borrowers while maintaining liquidator incentives > [!NOTE] > > Liquidations are a key safeguard in a lending protocol. They protect depositor funds by reducing a borrower's debt before the collateral is no longer enough to cover it. On Kamino, a position can be liquidated once it crosses its health limit. A liquidator repays part of the borrower's debt and receives collateral worth slightly more than the amount repaid. This difference is the liquidation bonus. Kamino's liquidation engine is designed to: * Protect depositors from bad debt * Reduce unnecessary losses for borrowers * Reward liquidators for acting when a position becomes risky *** ## How Position Health Is Calculated > [!NOTE] > > Every borrower in a Kamino market has a single on-chain account called an **Obligation**. It holds up to eight collateral deposits and five borrows, and health is calculated across all of them together. Before checking whether a position can be liquidated, Kamino refreshes the Obligation using the latest oracle prices and accrued interest. It then calculates the total value of the position's collateral and debt. ### Collateral Value For each deposit, Kamino calculates its current market value and adds it to three running totals: **deposited_value** Total market value of the collateral. ```text theme={"theme":"css-variables"} deposited_value += market_value ``` **allowed_borrow_value** Maximum debt the collateral can support when opening or increasing a borrow. ```text theme={"theme":"css-variables"} allowed_borrow_value += market_value × loanToValuePct / 100 ``` **unhealthy_borrow_value** Debt limit at which the position becomes eligible for liquidation. ```text theme={"theme":"css-variables"} unhealthy_borrow_value += market_value × liquidationThresholdPct / 100 ``` For example, \$100 of collateral with a 75% LTV can support up to \$75 of borrowing. If its health limit is 80%, the position becomes eligible for liquidation when its risk-adjusted debt reaches \$80. The difference between the two limits creates a safety buffer. New borrowing stops at 75%, while liquidation begins at 80%. ### Debt Value For each borrow, Kamino calculates the outstanding debt, including accrued interest, using the latest oracle price. It adds the result to two running totals: **borrowed_assets_market_value** The actual value of the outstanding debt. ```text theme={"theme":"css-variables"} borrowed_assets_market_value += market_value ``` **borrow_factor_adjusted_debt_value** The risk-adjusted value used to measure position health and determine when liquidation begins. ```text theme={"theme":"css-variables"} borrow_factor_adjusted_debt_value += market_value × borrowFactorPct / 100 ``` The `borrowFactorPct` is always 100% or higher. For example, at 150%, every \$1 borrowed counts as \$1.50 when measuring position health. The borrower still owes \$1, but Kamino treats it as \$1.50 of debt when assessing liquidation risk. ### Liquidation Eligibility Kamino compares two values to determine whether a position can be liquidated. **Current LTV** Measures the position's risk-adjusted debt against its total collateral value. ```text theme={"theme":"css-variables"} Current LTV = borrow_factor_adjusted_debt_value / deposited_value ``` Borrow factors increase the value assigned to riskier debt. Current LTV may therefore be higher than the position's actual debt-to-collateral ratio. **Health limit** The maximum Current LTV the position can support before liquidation begins. ```text theme={"theme":"css-variables"} Health limit = unhealthy_borrow_value / deposited_value ``` Each collateral asset has its own health limit. When a position contains multiple collateral assets, Kamino calculates a blended health limit based on the value of each deposit. The gap between Current LTV and this limit is the position's safety buffer. The wider the gap, the further the position is from liquidation. A position becomes eligible for liquidation when: ```text theme={"theme":"css-variables"} Current LTV >= Health limit ``` This is equivalent to: ```text theme={"theme":"css-variables"} borrow_factor_adjusted_debt_value >= unhealthy_borrow_value ``` ### Actual LTV and the Bonus Cap Actual LTV compares the amount owed with the position's total collateral value, without applying borrow factors. ```text theme={"theme":"css-variables"} Actual LTV = borrowed_assets_market_value / deposited_value ``` The two debt values answer different questions. Risk-adjusted debt determines **when** liquidation begins, allowing Kamino to account for the risk of the borrowed asset and liquidate vulnerable positions before they approach insolvency. Actual debt determines **how much bonus can safely be paid**, because the bonus is paid from collateral and cannot exceed the collateral value remaining above the position's actual debt. This prevents the liquidation itself from pushing the position into bad debt. ## Liquidation Rounds Once a position crosses its health limit, Kamino does not liquidate the entire debt at once. The `liquidationMaxDebtCloseFactorPct` parameter caps each liquidation round to a percentage of the position's outstanding debt. If the position remains unhealthy, another liquidation round can follow. This limits how much collateral can be seized in a single transaction, helping mildly unhealthy positions return to health without unnecessary collateral loss. The cap increases to 100% only when a position approaches insolvency. > [card] liquidationMaxDebtCloseFactorPct > > Sets the maximum share of outstanding debt that can be repaid in one liquidation round. The value varies by market. > [card] insolvencyRiskUnhealthyLtvPct > > When LTV exceeds 95%, the close factor jumps to 100%. The position is close enough to bad debt that full liquidation in a single transaction is necessary. > [!NOTE] > > The close factor is configured per market and applied to each obligation. Query `GET /kamino-market/{marketPubkey}/users/{userPubkey}/obligations` to see the effective `closeFactor` for an obligation. ### A Measured Path Back to Health Consider a position with \$10,000 in collateral and \$8,100 in risk-adjusted debt. With an 80% health limit, liquidation begins at \$8,000. The position is therefore only \$100 beyond the threshold, yet a conventional 50% close factor would allow a liquidator to repay \$4,050 and seize approximately \$4,250 in collateral, including the liquidation bonus. A minor shortfall could result in the loss of a substantial share of the borrower's position. Kamino's close factor takes a more measured approach. The first liquidation round is limited to a fraction of the debt, with a proportionate amount of collateral seized. This is often enough to return a mildly unhealthy position to safety without removing significantly more collateral than the correction requires. For more severe positions, the close factor does not prevent liquidation; it divides the process into rounds. If the position remains unhealthy after the first repayment, another round can follow. Debt and collateral are reduced progressively until the position recovers or is fully resolved. This approach favors borrower protection over single-transaction efficiency. Some positions may require several liquidations, but the smaller rounds mean collateral loss is more proportionate and the market has more time to absorb the liquidated assets. ### Edge Cases: Large Liquidations and Dust Positions A single transaction clearing too much value can distort the market or be influenced by transaction ordering. A position too small to liquidate profitably can sit in the protocol indefinitely. > [card] maxLiquidatableDebtMarketValueAtOnce > > No single liquidation can exceed \$500,000 in value, limiting market impact from large forced sales. > [card] minFullLiquidationValueThreshold > > Below \$2 in debt, the close factor is bypassed and the full borrow must be cleared. ### Liquidation Priority | Parameter | Priority rule | | - | - | | `liquidationThresholdPct` | The deposit with the lowest liquidation threshold is seized first. Removing the weakest collateral improves the weighted threshold of the remaining position. | | `borrowFactorPct` | The borrow with the highest borrow factor is repaid first. Reducing the most heavily risk-adjusted debt produces the largest improvement in position health. | | `minValueSkipLiquidationLtvChecks` | Below this collateral value, priority checks are skipped so small liquidations remain economical. | Kamino prioritizes the collateral and debt that contribute most to liquidation risk. Removing collateral with the lowest liquidation threshold can improve the weighted threshold of the remaining position, while repaying debt with the highest borrow factor produces the largest reduction in risk-adjusted LTV. The Obligation stores these values as `lowest_reserve_deposit_liquidation_ltv` and `highest_borrow_factor_pct`, allowing the rules to be enforced efficiently onchain. Minimum value checks keep these constraints from making small liquidations uneconomical. Reserves with `loanToValuePct` set to zero cannot be seized. These reserves are deposit-only and are not intended to support borrowing. ### Dynamic Liquidation Bonus Liquidators repay debt using their own tokens and receive collateral worth more than the amount repaid. Unlike a static bonus that pays the same percentage regardless of severity, Kamino's bonus scales with how far a position has breached its threshold. Positions closer to insolvency offer a larger reward, directing liquidator attention to the debt that poses the greatest risk to the protocol. Each reserve configures three bonus parameters: | Parameter | Description | | - | - | | `minLiquidationBonusBps` | Floor bonus. The minimum reward, even for a position barely past its threshold. | | `maxLiquidationBonusBps` | Ceiling bonus. The maximum reward regardless of severity. | | `badDebtLiquidationBonusBps` | Near-insolvency bonus. Applied when LTV reaches 99% or higher. | ### How the Bonus Is Calculated The bonus is calculated in three operations. **1. Floor: guarantee a minimum reward** The bonus starts as the greater of the configured floor or how far the position has crossed its LTV limit. This ensures even a barely-unhealthy position offers enough incentive for a liquidator to act. ```text theme={"theme":"css-variables"} bonus = max(minLiquidationBonusBps, loanToValue() - loanToValuePct) ``` **2. Cap: limit the maximum reward** The bonus is capped by the reserve's configured maximum. For elevation group positions, `elevationGroup.maxLiquidationBonusBps` applies as an additional ceiling. ```text theme={"theme":"css-variables"} bonus = min(bonus, maxLiquidationBonusBps) ``` **3. Solvency cap: prevent the liquidation from creating bad debt** The bonus cannot exceed the gap between actual debt and collateral value. If a position's actual LTV is 98%, only 2% of collateral headroom remains, so the bonus is capped at 2% regardless of what the reserve allows. This guarantees the liquidation itself never pushes the position closer to insolvency. ```text theme={"theme":"css-variables"} bonus = min(bonus, 1.0 - noBfLoanToValue()) ``` ### Keeping the Bonus Within Collateral Limits The bonus is paid from collateral. If the bonus exceeded the remaining collateral headroom, a liquidation could remove more collateral value than the debt it repays and leave the position worse off. Consider a position at 98% LTV with a reserve that normally permits a 10% bonus. Only 2% of collateral value remains above the debt, so the solvency cap overrides the reserve config and forces the bonus down to 2%. Without this cap, the liquidator would seize more collateral than the debt they repaid, pushing the position into bad debt. The solvency cap uses LTV because a borrow factor is a risk adjustment rather than an actual liability. Real collateral headroom is determined by actual debt. ### Near-Insolvency Behavior When LTV reaches 99% or more, the engine enters a special liquidation regime: * The close factor increases to 100%, allowing the full position to be cleared. * The bonus switches to `badDebtLiquidationBonusBps`, typically around 1%. * The solvency cap continues to apply. At 99.5% LTV, for example, the maximum possible bonus is 0.5%. The available incentive approaches zero as the position moves closer to actual insolvency, which makes early execution increasingly important. If LTV exceeds 100%, the position has entered bad debt. The protocol's final recovery mechanism is `socialize_loss`, which distributes the shortfall across depositors in the affected reserve. This mechanism has never been triggered on Kamino. ### Protocol Fee A reserve can allocate part of the liquidation bonus to the protocol through `protocolLiquidationFeePct`: ```text theme={"theme":"css-variables"} protocol_fee = ceil(bonus_amount * protocolLiquidationFeePct / 100) ``` The fee is deducted from the bonus rather than added to the collateral removed from the position. If the liquidation bonus is \$100 and the protocol fee is 50%, the protocol receives \$50 and the liquidator receives \$50. The total bonus charged to the position remains \$100. Some markets set the protocol fee to zero during volatile conditions so the full bonus remains available to liquidators. *** ## Summary Kamino's liquidation engine reflects a deliberate balance between borrower protection, liquidator incentives, and protocol solvency. **1. Borrower protection over liquidator convenience** The close factor limits how much debt can be repaid in a single liquidation round. Mildly unhealthy positions can therefore return to health without surrendering a disproportionate share of their collateral. At the same time, the dynamic bonus offers only a modest reward near the health limit, where the risk is still limited. **2. Safety constraints over liquidator flexibility** The solvency cap prevents the liquidation bonus from pushing a position further toward insolvency. Collateral and debt priority rules are also enforced by the program rather than left to liquidator discretion. These constraints narrow the available liquidation paths while preserving the protocol's safety conditions. **3. Incentives that rise with risk** The dynamic bonus increases as a position deteriorates. Positions approaching insolvency become more profitable to liquidate, directing capital and attention toward the debt that presents the greatest risk without requiring centralized coordination. **4. Progressive liquidation over a single forced sale** Kamino resolves unhealthy positions through smaller liquidation rounds rather than one large intervention. A mildly unhealthy position may recover after a single round, while a more severe position can be reduced progressively. This keeps each correction more proportionate and limits the market impact of the collateral sold. *** ## Liquidation Parameter Reference Fields governing liquidation across the three on-chain data structures. ### LendingMarket **TypeScript** ```typescript theme={"theme":"css-variables"} interface LendingMarket { liquidationMaxDebtCloseFactorPct: number; // e.g. 10 insolvencyRiskUnhealthyLtvPct: number; // default 95 maxLiquidatableDebtMarketValueAtOnce: BN; // default 500,000 minFullLiquidationValueThreshold: BN; // default 2 minValueSkipLiquidationLtvChecks: BN; minValueSkipLiquidationBfChecks: BN; priceTriggeredLiquidationDisabled: number; // default 0 autodeleverageEnabled: number; individualAutodeleverageMarginCallPeriodSecs: BN; matureReserveDebtLiquidationEnabled: number; obligationBorrowDebtTermLiquidationEnabled: number; obligationOrderExecutionEnabled: number; } ``` **Rust** ```rust theme={"theme":"css-variables"} pub struct LendingMarket { pub liquidation_max_debt_close_factor_pct: u8, // e.g. 10 pub insolvency_risk_unhealthy_ltv_pct: u8, // default 95 pub max_liquidatable_debt_market_value_at_once: u64, // default 500,000 pub min_full_liquidation_value_threshold: u64, // default 2 pub min_value_skip_liquidation_ltv_checks: u64, pub min_value_skip_liquidation_bf_checks: u64, pub price_triggered_liquidation_disabled: u8, // default 0 pub autodeleverage_enabled: u8, pub individual_autodeleverage_margin_call_period_secs: u64, pub mature_reserve_debt_liquidation_enabled: u8, pub obligation_borrow_debt_term_liquidation_enabled: u8, pub obligation_order_execution_enabled: u8, } ``` **Field descriptions** | Field | Description | | - | - | | `liquidationMaxDebtCloseFactorPct` | Maximum percentage of total debt repayable in one liquidation | | `insolvencyRiskUnhealthyLtvPct` | LTV above which the close factor becomes 100% | | `maxLiquidatableDebtMarketValueAtOnce` | Maximum USD value liquidated by one instruction | | `minFullLiquidationValueThreshold` | USD value below which full liquidation is required | | `minValueSkipLiquidationLtvChecks` | Collateral value below which LTV priority checks are skipped | | `minValueSkipLiquidationBfChecks` | Borrow value below which borrow factor priority checks are skipped | | `priceTriggeredLiquidationDisabled` | Disables price-triggered liquidations | | `autodeleverageEnabled` | Enables auto-deleverage at the market level | | `individualAutodeleverageMarginCallPeriodSecs` | Grace period for individual auto-deleverage | | `matureReserveDebtLiquidationEnabled` | Enables liquidation of mature fixed-term debt | | `obligationBorrowDebtTermLiquidationEnabled` | Enables liquidation after a borrow term expires | | `obligationOrderExecutionEnabled` | Enables stop-loss and take-profit execution | ### ReserveConfig **TypeScript** ```typescript theme={"theme":"css-variables"} interface ReserveConfig { loanToValuePct: number; liquidationThresholdPct: number; minLiquidationBonusBps: number; maxLiquidationBonusBps: number; badDebtLiquidationBonusBps: number; protocolLiquidationFeePct: number; borrowFactorPct: BN; autodeleverageEnabled: number; minDeleveragingBonusBps: number; deleveragingMarginCallPeriodSecs: BN; deleveragingThresholdDecreaseBpsPerDay: BN; deleveragingBonusIncreaseBpsPerDay: BN; debtMaturityTimestamp: BN; debtTermSeconds: BN; } ``` **Rust** ```rust theme={"theme":"css-variables"} pub struct ReserveConfig { pub loan_to_value_pct: u8, pub liquidation_threshold_pct: u8, pub min_liquidation_bonus_bps: u16, pub max_liquidation_bonus_bps: u16, pub bad_debt_liquidation_bonus_bps: u16, pub protocol_liquidation_fee_pct: u8, pub borrow_factor_pct: u64, pub autodeleverage_enabled: u8, pub min_deleveraging_bonus_bps: u16, pub deleveraging_margin_call_period_secs: u64, pub deleveraging_threshold_decrease_bps_per_day: u64, pub deleveraging_bonus_increase_bps_per_day: u64, pub debt_maturity_timestamp: u64, pub debt_term_seconds: u64, } ``` **Field descriptions** | Field | Description | | - | - | | `loanToValuePct` | Maximum LTV for new borrows; zero disables use as borrowable collateral | | `liquidationThresholdPct` | LTV at which an obligation becomes liquidatable | | `minLiquidationBonusBps` | Minimum liquidator bonus in basis points | | `maxLiquidationBonusBps` | Maximum liquidator bonus in basis points | | `badDebtLiquidationBonusBps` | Bonus applied near or at bad debt | | `protocolLiquidationFeePct` | Protocol share of the bonus, from 0 to 100 | | `borrowFactorPct` | Risk multiplier applied to borrows, minimum 100 | | `autodeleverageEnabled` | Allows the reserve to participate in market-wide auto-deleverage | | `minDeleveragingBonusBps` | Starting bonus for deleverage liquidations | | `deleveragingMarginCallPeriodSecs` | Grace period before market-wide deleveraging | | `deleveragingThresholdDecreaseBpsPerDay` | Daily reduction in liquidation threshold during deleveraging | | `deleveragingBonusIncreaseBpsPerDay` | Daily increase in deleveraging bonus | | `debtMaturityTimestamp` | Time at which all borrows from the reserve become liquidatable | | `debtTermSeconds` | Per-borrow term after which the debt becomes liquidatable | ### ElevationGroup **TypeScript** ```typescript theme={"theme":"css-variables"} interface ElevationGroup { ltvPct: number; liquidationThresholdPct: number; maxLiquidationBonusBps: number; debtReserve: Address; maxReservesAsCollateral: number; } ``` **Rust** ```rust theme={"theme":"css-variables"} pub struct ElevationGroup { pub ltv_pct: u8, pub liquidation_threshold_pct: u8, pub max_liquidation_bonus_bps: u16, pub debt_reserve: Pubkey, pub max_reserves_as_collateral: u8, } ``` **Field descriptions** | Field | Description | | - | - | | `ltvPct` | Overrides reserve `loanToValuePct` for obligations in the group | | `liquidationThresholdPct` | Overrides reserve `liquidationThresholdPct` | | `maxLiquidationBonusBps` | Maximum liquidation bonus for obligations in the group | | `debtReserve` | Single debt reserve permitted in the group | | `maxReservesAsCollateral` | Maximum number of collateral reserves permitted | # Deposit with Referral Source: https://docs.kamino.com/build/developers/borrow/operations/advanced-concepts/deposit-with-referral Deposit funds with a referrer who earns commission from a user's borrowing activity ## Deposit with Referral A UserMetadata account stores the referrer information. The referrer must be included when the account is created. After it is set, the referrer cannot be changed. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > some, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > DEFAULT_PUBLIC_KEY, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import BN from 'bn.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Check the Referrer on Record > > The referrer is stored in the wallet's user metadata, created by its first Kamino deposit. If the account already exists, pass the referrer on record. > > ```typescript theme={"theme":"css-variables"} > const REFERRER = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const [, userMetadata] = await market!.getUserMetadata(signer.address); > const referrer = userMetadata ? userMetadata.referrer : REFERRER; > > if (userMetadata) { > console.log('Referrer already fixed for this wallet:', referrer === DEFAULT_PUBLIC_KEY ? 'none' : referrer); > } > ``` > > > [!WARNING] > > > > The referrer can only be set when the user metadata account is created and can't be changed after. A wallet that already used Kamino without a referral has `DEFAULT_PUBLIC_KEY` (`11111111111111111111111111111111`) on record, meaning no referrer, and can't get one. Passing a different referrer than the one on record makes the transaction fail. > > **Step 4** > > ### Build Deposit Instructions with Referrer > > Deposit USDC as collateral with the referrer attached. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const depositAction = await KaminoAction.buildDepositTxns({ > kaminoMarket: market!, > amount: new BN(1_000_000), > reserveAddress: usdcReserve.address, > owner: signer, > obligation: new VanillaObligation(PROGRAM_ID), > useV2Ixs: true, > scopeRefreshConfig: undefined, > initUserMetadata: { skipInitialization: false, skipLutCreation: true }, > referrer: some(referrer), > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(depositAction), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > The deposit with referral is complete. The referrer is linked to the account and earns a share of the interest it pays on borrows. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Initialize User with Referrer > > Create the user metadata account linked to a referrer before depositing. > > ```rust theme={"theme":"css-variables"} > use klend_interface::helpers; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let referrer = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY").unwrap(); > > // Derive the referrer's user_metadata PDA > let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer); > > // Your user's address lookup table (created during onboarding) > let user_lookup_table = Pubkey::from_str("YOUR_USER_LOOKUP_TABLE_PUBKEY").unwrap(); > > let init_ixs = helpers::lifecycle::init_user( > owner, > owner, // fee payer > user_lookup_table, > Some(referrer_user_metadata), // links to this referrer > ); > ``` > > > [!WARNING] > > > > Once a UserMetadata account has a referrer, it cannot be changed. The original referrer permanently earns commission from the user's borrowing activity. > > **Step 4** > > ### Build Obligation Context > > Derive the obligation PDA and build the context for depositing. > > ```rust theme={"theme":"css-variables"} > use klend_interface::ObligationContext; > > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > // Derive the obligation PDA > let (obligation_pubkey, _) = pda::obligation( > &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, > &Pubkey::default(), &Pubkey::default(), > ); > > // Fetch the obligation account > let obligation_data = rpc_client.get_account(&obligation_pubkey)?; > > // Discover which reserves the obligation references > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; > > // Fetch all reserve accounts in one RPC call > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > > // Build the context > let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() > .zip(reserve_accounts.iter()) > .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) > .collect(); > let ctx = ObligationContext::from_account_data( > obligation_pubkey, &obligation_data.data, &reserves > )?; > ``` > > > [!NOTE] > > > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. > > **Step 5** > > ### Build Deposit Instructions > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); > let user_source_liquidity = get_associated_token_address(&owner, &liquidity_mint); > > let deposit_ixs = ctx.deposit( > owner, > &reserve_pubkey, > user_source_liquidity, > 1_000_000, // 1 USDC > )?; > ``` > > **Step 6** > > ### Send Transactions > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > // Transaction 1: Initialize user metadata with referrer > let message = Message::new(&init_ixs, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > rpc_client.send_and_confirm_transaction(&tx)?; > > // Transaction 2: Deposit with referral > let message = Message::new(&deposit_ixs, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Deposit with referral successful! Signature: {signature}"); > ``` # Refer User Without Deposit Source: https://docs.kamino.com/build/developers/borrow/operations/advanced-concepts/refer-user-without-deposit Create UserMetadata with a referrer without requiring an initial deposit ## Refer User Without Deposit Create a UserMetadata account with a referrer without requiring an initial deposit. This allows you to link a referrer to a user before they perform any lending operations. > [!NOTE] > > The referrer must be set when the UserMetadata account is created and cannot be changed afterward. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > some, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > getUserLutAddressAndSetupIxs, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **Step 2** > > ### Initialize RPC and Load Market > > ```typescript theme={"theme":"css-variables"} > 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 REFERRER = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Check Existing User Metadata > > ```typescript theme={"theme":"css-variables"} > const [, userMetadata] = await market!.getUserMetadata(signer.address); > > if (userMetadata) { > console.log('User metadata already exists, so the referrer can no longer be set:', signer.address); > } > ``` > > **Step 4** > > ### Build User Metadata Setup Instructions > > ```typescript theme={"theme":"css-variables"} > const [, setupInstructions] = await getUserLutAddressAndSetupIxs(market!, signer, some(REFERRER), false); > ``` > > > [!NOTE] > > > > The referrer's wallet must have Kamino user metadata itself. The instructions also create the wallet's lookup table; `false` skips filling it. For a wallet that already has user metadata, the SDK returns no instructions. > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(setupInstructions.flat(), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Referrer linked! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > User metadata created. The referrer is now linked to the wallet and earns a share of the interest it pays on borrows. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Derive PDAs and Build Instruction > > Create the `init_user_metadata` instruction linking the user to a referrer without requiring a deposit. > > ```rust theme={"theme":"css-variables"} > use klend_interface::instructions::referrer::{ > init_user_metadata, > InitUserMetadataAccounts, > }; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let referrer = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY").unwrap(); > > // Derive PDAs > let (user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &owner); > let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer); > > // Your user's address lookup table (created during onboarding) > let user_lookup_table = Pubkey::from_str("YOUR_USER_LOOKUP_TABLE_PUBKEY").unwrap(); > > let ix = init_user_metadata( > InitUserMetadataAccounts { > owner, > fee_payer: owner, > user_metadata, > referrer_user_metadata: Some(referrer_user_metadata), > }, > user_lookup_table, > ); > ``` > > > [!WARNING] > > > > Once UserMetadata is created with a referrer, the referrer cannot be changed. Always check if UserMetadata exists before attempting to create it. > > **Step 4** > > ### Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&[ix], Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("UserMetadata created with referrer! Signature: {signature}"); > ``` > [accordion] When to Use This vs Deposit with Referral > > **Use this method when:** > > * You want to link a referrer to a user before they make their first deposit > * You're creating UserMetadata as a separate step from deposit operations > * You have a simpler flow that doesn't require immediate deposit > > **Use Deposit with Referral when:** > > * You want to combine UserMetadata creation and deposit in a single transaction > * The user is ready to deposit immediately > * You want to minimize the number of transactions # Referral Code Setup Source: https://docs.kamino.com/build/developers/borrow/operations/advanced-concepts/referrer-setup Set up referrer state with a unique referral code ## How Referral Codes Work Kamino's referral system allows referrers to earn commission from the borrowing activity of referred users. Each referrer creates a unique referral code that can be shared publicly without revealing a wallet address, providing a user-friendly way to distribute referral codes. \[!NOTE] In the SDK, the `shortUrl` field represents the referral code. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > PROGRAM_ID, > getInitReferrerStateAndShortUrlIxs, > getReferrerForShortUrl, > isShortUrlAvailable, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **Step 2** > > ### Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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'); > ``` > > **Step 3** > > ### Create Referrer State with Short URL > > Check the referral code is free, then create the referrer state and short URL. > > ```typescript theme={"theme":"css-variables"} > const shortUrl = 'your-referral-code'; > > if (!(await isShortUrlAvailable(rpc, shortUrl, PROGRAM_ID))) { > console.log('Referral code is invalid or already taken:', shortUrl); > } > > const initReferrerIx = await getInitReferrerStateAndShortUrlIxs({ > referrer: signer, > shortUrl, > programId: PROGRAM_ID, > }); > ``` > > > [!NOTE] > > > > The short URL must be unique, at most 32 characters, and use only ASCII letters, digits, underscore and hyphen. `isShortUrlAvailable` checks both. Each wallet gets one code. > > **Step 4** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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([initReferrerIx], tx) > ); > ``` > > **Step 5** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Referrer registered! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > **Step 6** > > ### Verify Short URL Resolution > > ```typescript theme={"theme":"css-variables"} > const referrer = await getReferrerForShortUrl(rpc, shortUrl, PROGRAM_ID); > console.log(`Code ${shortUrl} resolves to:`, referrer); > ``` > > > [!TIP] > > > > Referrer setup complete. The short URL is active and can be shared with users to establish referral relationships. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Derive PDAs and Build Instruction > > ```rust theme={"theme":"css-variables"} > use klend_interface::instructions::referrer::{ > init_referrer_state_and_short_url, > InitReferrerStateAndShortUrlAccounts, > }; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > > let referrer = signer.pubkey(); > let short_url = format!("ref-{}", std::time::SystemTime::now() > .duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()); > > // Derive required PDAs > let (referrer_state, _) = pda::referrer_state(&KLEND_PROGRAM_ID, &referrer); > let (referrer_short_url, _) = pda::short_url(&KLEND_PROGRAM_ID, &short_url); > let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer); > > let ix = init_referrer_state_and_short_url( > InitReferrerStateAndShortUrlAccounts { > referrer, > referrer_state, > referrer_short_url, > referrer_user_metadata, > }, > short_url.clone(), > ); > ``` > > > [!NOTE] > > > > The short URL must be unique, contain a maximum of 32 characters, and use only ASCII alphanumeric characters plus underscore and hyphen. > > **Step 4** > > ### Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&[ix], Some(&referrer)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Referrer setup successful! Short URL: {short_url}"); > println!("Signature: {signature}"); > ``` # Repay with Collateral using KSwap Source: https://docs.kamino.com/build/developers/borrow/operations/advanced-concepts/repay-with-collateral-kswap Reduce debt by converting collateral using flash loans in a single atomic transaction Repay with collateral reduces debt in a single atomic transaction by converting collateral into the debt token without requiring additional funds. The protocol flash borrows the debt token, repays the debt, withdraws the freed collateral, swaps it to the debt token via KSwap, and repays the flash loan, all in one transaction. ## Repay with Collateral using KSwap Reduce debt in a single transaction by converting collateral using a flash loan and KSwap. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, none, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, isTransactionMessageWithinSizeLimit, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, type Instruction, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoMarket, MultiplyObligation, PROGRAM_ID, getRepayWithCollIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, type SwapInputs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { KswapSdk, loadRouterContext, type RouteOutput } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; import BN from 'bn.js'; import Decimal from 'decimal.js'; ``` > [!NOTE] > > Use `@kamino-finance/kswap-sdk` 2.9.0. It's the last version on `@solana/kit` 2, which `@kamino-finance/klend-sdk` 13 uses; 3.x moved to kit 8. **Step 2** ### Load Configuration and Initialize SDKs ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const REPAY_AMOUNT = new Decimal(5); const SLIPPAGE_BPS = 50; const MAX_COMPUTE_UNITS = 1_400_000; const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const collReserve = market!.getExistingFloatRateReserveByMint(collMint); const debtReserve = market!.getExistingFloatRateReserveByMint(debtMint); const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); const scope = new Scope('mainnet-beta', rpc); ``` **Step 3** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. ```typescript theme={"theme":"css-variables"} const obligationAddress = await new MultiplyObligation(collMint, debtMint, PROGRAM_ID).toPda(marketPubkey, signer.address); const obligation = await market!.getObligationByAddress(obligationAddress); if (!obligation) { console.log('No Multiply position found for', signer.address); } ``` **Step 4** ### Get Scope Price Refresh Instructions ```typescript theme={"theme":"css-variables"} const scopeRefreshIx = await getScopeRefreshIxForObligationAndReserves( market!, collReserve, debtReserve, obligation!, { scope, scopeConfigurations: await scope.getAllConfigurations() } ); ``` **Step 5** ### Define the Swap Helpers The SDK asks for swaps through two callbacks: a quoter that prices the swap and a swapper that returns its instructions. Both use every KSwap route, sorted by output. ```typescript theme={"theme":"css-variables"} async function getRoutes(inputs: SwapInputs) { const { routes } = await kswap.getAllRoutes( { executor: signer.address, tokenIn: inputs.inputMint, tokenOut: inputs.outputMint, amount: new BN(inputs.inputAmountLamports.floor().toString()), maxSlippageBps: SLIPPAGE_BPS, swapType: 'exactIn', wrapAndUnwrapSol: false, }, await loadRouterContext(rpc, inputs.inputMint, inputs.outputMint) ); if (routes.length === 0) { console.log('No KSwap route found for', inputs.inputMint, '->', inputs.outputMint); } return routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); } function midPrice(route: RouteOutput) { const amounts = route.amountsExactIn!; const amountIn = new Decimal(amounts.amountIn.toString()).div(new Decimal(10).pow(route.inputTokenDecimals!)); const amountOut = new Decimal(amounts.amountOut.toString()).div(new Decimal(10).pow(route.outputTokenDecimals!)); return amountOut.div(amountIn); } const quoter = async (inputs: SwapInputs) => { const [bestRoute] = await getRoutes(inputs); return { priceAInB: midPrice(bestRoute), quoteResponse: bestRoute }; }; const swapper = async (inputs: SwapInputs) => (await getRoutes(inputs)).map((route) => { const routeIxs = route.instructions!; return { preActionIxs: [], swapIxs: [ ...routeIxs.createInAtaIxs, ...routeIxs.wrapSolIxs, ...routeIxs.swapIxs, ...routeIxs.unwrapSolIxs, ...routeIxs.createOutAtaIxs, ], lookupTables: route.lookupTableAccounts ?? [], quote: { priceAInB: midPrice(route), quoteResponse: route }, }; }); ``` > [!WARNING] > > `priceAInB` must be the mid price (`amountOut / amountIn`, each in token units), before slippage. The SDK applies `slippagePct` itself, so a guaranteed or minimum-out price counts slippage twice and sizes the position wrong. `getBestRoute` currently returns no routes, so use `getAllRoutes`, which in kswap-sdk 2.9.0 takes the router context as a second argument. **Step 6** ### Build the Repay Routes The SDK builds one candidate transaction per swap route: flash borrow, repay the debt, withdraw TSLAx, swap it to USDC, repay the flash loan. ```typescript theme={"theme":"css-variables"} const routes = await getRepayWithCollIxs({ owner: signer, kaminoMarket: market!, debtReserveAddress: debtReserve.address, collReserveAddress: collReserve.address, obligation: obligation!, referrer: none(), currentLedgerInstant: await getCurrentLedgerInstant(rpc), repayAmount: REPAY_AMOUNT, isClosingPosition: false, slippagePct: new Decimal(SLIPPAGE_BPS / 100), scopeRefreshIx, budgetAndPriorityFeeIxs: getComputeBudgetAndPriorityFeeIxs(MAX_COMPUTE_UNITS), quoter, swapper, useV2Ixs: true, }); ``` > [!NOTE] > > `slippagePct` also sizes the flash loan, so the worst-case swap fill still covers the repay. To repay all the debt and close the position, set `isClosingPosition` to `true`. **Step 7** ### Fetch Lookup Tables Fetch Kamino's lookup tables for each candidate transaction, one request per candidate. ```typescript theme={"theme":"css-variables"} async function getKaminoLookupTables(instructions: Instruction[]) { const addresses = [ ...new Set(instructions.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), ]; const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addresses }), }); if (!lutResponse.ok) { console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); } const { lutAddresses } = await lutResponse.json(); return fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); } ``` > [!NOTE] > > `/luts/find-minimal` takes one transaction's worth of addresses (between 64 and 128), so a single request for all candidates is rejected. **Step 8** ### Pick the Route That Fits Compress each candidate with its route's lookup tables and Kamino's, then take the best-output one that fits in a transaction. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const candidates = await Promise.all( routes.map(async (route) => { const lookupTables = [...route.lookupTables, ...(await getKaminoLookupTables(route.ixs))]; const lookupTableAddresses: Record = Object.fromEntries( lookupTables.map((lut) => [lut.address, lut.data.addresses]) ); return pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(route.ixs, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) ); }) ); const transactionMessage = candidates.find((candidate) => isTransactionMessageWithinSizeLimit(candidate)); if (!transactionMessage) { console.log(`None of the ${candidates.length} swap routes fit in one transaction`); } ``` > [!NOTE] > > The best-output route often has too many accounts to fit, even compressed: in testing only one or two of five to ten routes did. The slippage setting covers the gap between the best route's quote and the one sent. **Step 9** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage!); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Repay with collateral successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The debt is reduced by selling TSLAx collateral, with no USDC needed in the wallet. # Withdraw Referrer Fees Source: https://docs.kamino.com/build/developers/borrow/operations/advanced-concepts/withdraw-referrer-fees Withdraw accumulated referral fees from borrowing activity ## Withdraw Referrer Fees > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Check Accumulated Fees > > Fees accrue per reserve, in that reserve's token. Amounts are in lamports, so divide by the reserve's mint factor. > > ```typescript theme={"theme":"css-variables"} > const allFees = await market!.getAllReferrerFeesCumulative(signer.address); > > console.table( > [...allFees.entries()].map(([reserveAddress, fees]) => { > const reserve = market!.getReserveByAddress(reserveAddress); > return { > symbol: reserve?.getTokenSymbol(), > lifetimeFees: reserve ? fees.div(reserve.getMintFactor()).toFixed(6) : fees.toFixed(0), > }; > }) > ); > > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > const unclaimedFees = await market!.getReferrerFeesUnclaimedForReserve(signer.address, usdcReserve); > > console.log('Unclaimed USDC fees:', unclaimedFees.div(usdcReserve.getMintFactor()).toFixed(6)); > if (unclaimedFees.isZero()) { > console.log('No USDC referrer fees to withdraw for', signer.address); > } > ``` > > **Step 4** > > ### Build Withdraw Instructions > > Withdraw the unclaimed USDC fees to the wallet. > > ```typescript theme={"theme":"css-variables"} > const withdrawFeesAction = await KaminoAction.buildWithdrawReferrerFeeTxns({ > owner: signer, > reserveAddress: usdcReserve.address, > kaminoMarket: market!, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > > [!NOTE] > > > > A wallet that has never earned fees in the reserve has no referrer token state for it, and the withdrawal fails with `AccountOwnedByWrongProgram` (3007). > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(withdrawFeesAction), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Referrer fees withdrawn! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > Fee withdrawal complete. The accumulated referral fees have been transferred to the referrer wallet. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Derive PDAs and Build Instruction > > ```rust theme={"theme":"css-variables"} > use klend_interface::instructions::referrer::{ > withdraw_referrer_fees, > WithdrawReferrerFeesAccounts, > }; > use klend_interface::pda::{self, ReservePdas}; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > use spl_associated_token_account::get_associated_token_address; > > let referrer = signer.pubkey(); > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > let reserve_liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); > > // Derive PDAs > let (referrer_token_state, _) = pda::referrer_token_state( > &KLEND_PROGRAM_ID, &referrer, &reserve_pubkey > ); > let (lending_market_authority, _) = pda::lending_market_authority( > &KLEND_PROGRAM_ID, &lending_market > ); > let reserve_pdas = ReservePdas::derive(&KLEND_PROGRAM_ID, &reserve_pubkey); > > // Derive referrer's ATA for the reserve liquidity mint > let referrer_token_account = get_associated_token_address(&referrer, &reserve_liquidity_mint); > > let ix = withdraw_referrer_fees(WithdrawReferrerFeesAccounts { > referrer, > referrer_token_state, > reserve: reserve_pubkey, > reserve_liquidity_mint, > reserve_supply_liquidity: reserve_pdas.liquidity_supply_vault, > referrer_token_account, > lending_market, > lending_market_authority, > token_program: spl_token::ID, > }); > ``` > > **Step 4** > > ### Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&[ix], Some(&referrer)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Withdraw fees successful! Signature: {signature}"); > ``` # Borrow Source: https://docs.kamino.com/build/developers/borrow/operations/borrow Borrow assets against collateral Borrow assets against your collateral in Kamino lending markets. The SDK handles transaction building, instruction creation, and obligation management for borrowing operations. ## Borrow Borrow assets against your collateral. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import BN from 'bn.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Load the Obligation > > Load the wallet's borrow position so the SDK refreshes every reserve it uses. > > ```typescript theme={"theme":"css-variables"} > const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); > > if (!obligation) { > console.log('No borrow position found for', signer.address); > } > ``` > > **Step 4** > > ### Build Borrow Instructions > > Borrow USDT from its variable-rate reserve against the collateral in the position. > > ```typescript theme={"theme":"css-variables"} > const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); > const usdtReserve = market!.getExistingFloatRateReserveByMint(usdtMint); > > const borrowAction = await KaminoAction.buildBorrowTxns({ > kaminoMarket: market!, > amount: new BN(1_000_000), > reserveAddress: usdtReserve.address, > owner: signer, > obligation: obligation!, > useV2Ixs: true, > scopeRefreshConfig: undefined, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > > [!NOTE] > > > > The borrow must keep the position under its borrow limit, or the program rejects it. Fixed-rate loans go through borrow orders instead: see [Fixed-Rate Borrowing](/build/borrow/tutorials/fixed-rate-borrowing). > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(borrowAction), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Borrow successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > The borrow is complete. The USDT is in the wallet and the debt is recorded in the borrow position. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Build Obligation Context > > The obligation must already have deposited collateral before you can borrow. > > ```rust theme={"theme":"css-variables"} > use klend_interface::ObligationContext; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let borrow_reserve_pubkey = Pubkey::from_str("FBSyPnxtHKLBZ4UeeUyAnbtFuAmTHLtso9YtsqRDRWpM").unwrap(); > > // Derive the obligation PDA > let (obligation_pubkey, _) = pda::obligation( > &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, > &Pubkey::default(), &Pubkey::default(), > ); > > // Fetch the obligation account > let obligation_data = rpc_client.get_account(&obligation_pubkey)?; > > // Discover which reserves the obligation references > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; > > // Fetch all reserve accounts in one RPC call > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > > // Build the context > let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() > .zip(reserve_accounts.iter()) > .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) > .collect(); > let ctx = ObligationContext::from_account_data( > obligation_pubkey, &obligation_data.data, &reserves > )?; > ``` > > > [!WARNING] > > > > You must have an existing obligation with deposited collateral before you can borrow. > > > [!NOTE] > > > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. > > **Step 4** > > ### Derive Token Accounts > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > // User's ATA for the borrow token (e.g. USDT) > let borrow_liquidity_mint = Pubkey::from_str("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB").unwrap(); > let user_dest_liquidity = get_associated_token_address(&owner, &borrow_liquidity_mint); > ``` > > **Step 5** > > ### Build Instructions > > ```rust theme={"theme":"css-variables"} > let instructions = ctx.borrow( > owner, > &borrow_reserve_pubkey, > user_dest_liquidity, > 1_000_000, // 1 USDT (6 decimals) > )?; > // Returns: [refresh_reserves..., refresh_obligation, borrow_obligation_liquidity_v2] > ``` > > **Step 6** > > ### Build and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Borrow successful! Signature: {signature}"); > ``` > > > [!NOTE] > > > > Borrowing increases your debt and LTV ratio. Monitor your position to avoid liquidation risk. > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/borrow.rs) > [tab] Rust (CPI) > > > [!NOTE] > > > > This example shows how an **on-chain Anchor program** can CPI into Kamino Lending using `klend-interface` instruction builders. A PDA authority owns the vaults and obligation, and signs all CPI calls via `invoke_signed`. The full flow: init obligation → deposit collateral (Token A) → borrow (Token B). > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > anchor-lang = "0.30" > anchor-spl = "0.30" > solana-program = "2.1" > ``` > > **Step 2** > > ### Define PDA Authority and Handler > > ```rust theme={"theme":"css-variables"} > use anchor_lang::prelude::*; > use klend_interface::{ > instructions::{borrow, deposit, obligation}, > pda as klend_pda, > types::InitObligationArgs, > KLEND_PROGRAM_ID, > }; > > declare_id!("YourProgram1111111111111111111111111111111111"); > > const AUTHORITY_SEED: &[u8] = b"authority"; > > #[program] > pub mod cpi_example { > use super::*; > > pub fn deposit_and_borrow( > ctx: Context, > deposit_amount: u64, > borrow_amount: u64, > ) -> Result<()> { > let lending_market_key = ctx.accounts.lending_market.key(); > let authority_seeds: &[&[u8]] = &[ > AUTHORITY_SEED, > lending_market_key.as_ref(), > &[ctx.bumps.authority], > ]; > ``` > > **Step 3** > > ### Init Obligation (skip if already initialized) > > ```rust theme={"theme":"css-variables"} > let init_ix = obligation::init_obligation( > obligation::InitObligationAccounts { > obligation_owner: ctx.accounts.authority.key(), > fee_payer: ctx.accounts.payer.key(), > obligation: ctx.accounts.obligation.key(), > lending_market: ctx.accounts.lending_market.key(), > seed1_account: ctx.accounts.system_program.key(), > seed2_account: ctx.accounts.system_program.key(), > owner_user_metadata: ctx.accounts.owner_user_metadata.key(), > }, > InitObligationArgs { tag: 0, id: 0 }, > ); > > solana_program::program::invoke_signed( > &init_ix, > &[ > ctx.accounts.authority.to_account_info(), > ctx.accounts.payer.to_account_info(), > ctx.accounts.obligation.to_account_info(), > ctx.accounts.lending_market.to_account_info(), > ctx.accounts.system_program.to_account_info(), > ctx.accounts.system_program.to_account_info(), > ctx.accounts.owner_user_metadata.to_account_info(), > ctx.accounts.rent.to_account_info(), > ctx.accounts.system_program.to_account_info(), > ], > &[authority_seeds], > )?; > ``` > > **Step 4** > > ### Deposit Token A as Collateral > > ```rust theme={"theme":"css-variables"} > let deposit_ix = > deposit::deposit_reserve_liquidity_and_obligation_collateral_v2( > deposit::DepositReserveLiquidityAndObligationCollateralV2Accounts { > owner: ctx.accounts.authority.key(), > obligation: ctx.accounts.obligation.key(), > lending_market: ctx.accounts.lending_market.key(), > lending_market_authority: ctx.accounts.lending_market_authority.key(), > reserve: ctx.accounts.deposit_reserve.key(), > reserve_liquidity_mint: ctx.accounts.deposit_reserve_liquidity_mint.key(), > reserve_liquidity_supply: ctx.accounts.deposit_reserve_liquidity_supply.key(), > reserve_collateral_mint: ctx.accounts.deposit_reserve_collateral_mint.key(), > reserve_destination_deposit_collateral: ctx > .accounts > .deposit_reserve_collateral_supply > .key(), > user_source_liquidity: ctx.accounts.vault_a.key(), > placeholder_user_destination_collateral: None, > liquidity_token_program: ctx.accounts.token_program.key(), > obligation_farm_user_state: None, > reserve_farm_state: None, > }, > deposit_amount, > ); > > solana_program::program::invoke_signed( > &deposit_ix, > &[ > ctx.accounts.authority.to_account_info(), > ctx.accounts.obligation.to_account_info(), > ctx.accounts.lending_market.to_account_info(), > ctx.accounts.lending_market_authority.to_account_info(), > ctx.accounts.deposit_reserve.to_account_info(), > ctx.accounts.deposit_reserve_liquidity_mint.to_account_info(), > ctx.accounts.deposit_reserve_liquidity_supply.to_account_info(), > ctx.accounts.deposit_reserve_collateral_mint.to_account_info(), > ctx.accounts.deposit_reserve_collateral_supply.to_account_info(), > ctx.accounts.vault_a.to_account_info(), > ctx.accounts.klend_program.to_account_info(), > ctx.accounts.token_program.to_account_info(), > ctx.accounts.token_program.to_account_info(), > ctx.accounts.instructions_sysvar.to_account_info(), > ctx.accounts.klend_program.to_account_info(), > ctx.accounts.klend_program.to_account_info(), > ctx.accounts.farms_program.to_account_info(), > ], > &[authority_seeds], > )?; > ``` > > **Step 5** > > ### Borrow Token B > > The `remaining_accounts` must include the deposit reserve so Klend can verify collateral. > > ```rust theme={"theme":"css-variables"} > let remaining = vec![AccountMeta { > pubkey: ctx.accounts.deposit_reserve.key(), > is_signer: false, > is_writable: true, > }]; > > let borrow_ix = borrow::borrow_obligation_liquidity_v2( > borrow::BorrowObligationLiquidityV2Accounts { > owner: ctx.accounts.authority.key(), > obligation: ctx.accounts.obligation.key(), > lending_market: ctx.accounts.lending_market.key(), > lending_market_authority: ctx.accounts.lending_market_authority.key(), > borrow_reserve: ctx.accounts.borrow_reserve.key(), > borrow_reserve_liquidity_mint: ctx > .accounts > .borrow_reserve_liquidity_mint > .key(), > reserve_source_liquidity: ctx > .accounts > .borrow_reserve_liquidity_supply > .key(), > borrow_reserve_liquidity_fee_receiver: ctx > .accounts > .borrow_reserve_fee_receiver > .key(), > user_destination_liquidity: ctx.accounts.vault_b.key(), > referrer_token_state: None, > token_program: ctx.accounts.token_program.key(), > obligation_farm_user_state: None, > reserve_farm_state: None, > }, > borrow_amount, > remaining, > ); > > solana_program::program::invoke_signed( > &borrow_ix, > &[ > ctx.accounts.authority.to_account_info(), > ctx.accounts.obligation.to_account_info(), > ctx.accounts.lending_market.to_account_info(), > ctx.accounts.lending_market_authority.to_account_info(), > ctx.accounts.borrow_reserve.to_account_info(), > ctx.accounts.borrow_reserve_liquidity_mint.to_account_info(), > ctx.accounts.borrow_reserve_liquidity_supply.to_account_info(), > ctx.accounts.borrow_reserve_fee_receiver.to_account_info(), > ctx.accounts.vault_b.to_account_info(), > ctx.accounts.klend_program.to_account_info(), > ctx.accounts.token_program.to_account_info(), > ctx.accounts.instructions_sysvar.to_account_info(), > ctx.accounts.klend_program.to_account_info(), > ctx.accounts.klend_program.to_account_info(), > ctx.accounts.farms_program.to_account_info(), > ctx.accounts.deposit_reserve.to_account_info(), > ], > &[authority_seeds], > )?; > > Ok(()) > } > } > ``` > > **Step 6** > > ### Account Validation Struct > > ```rust expandable title="DepositAndBorrow accounts" theme={"theme":"css-variables"} > #[derive(Accounts)] > pub struct DepositAndBorrow<'info> { > /// PDA authority that owns the vaults and the Klend obligation. > #[account( > seeds = [AUTHORITY_SEED, lending_market.key().as_ref()], > bump, > )] > pub authority: SystemAccount<'info>, > > /// Token A vault — holds the collateral token, owned by `authority`. > #[account(mut, token::authority = authority)] > pub vault_a: Account<'info, TokenAccount>, > > /// Token B vault — receives the borrowed token, owned by `authority`. > #[account(mut, token::authority = authority)] > pub vault_b: Account<'info, TokenAccount>, > > /// Fee payer for obligation init. > #[account(mut)] > pub payer: Signer<'info>, > > // -- Klend accounts -- > /// CHECK: Klend lending market account. > pub lending_market: UncheckedAccount<'info>, > /// CHECK: Klend lending market authority PDA. > pub lending_market_authority: UncheckedAccount<'info>, > /// CHECK: Obligation PDA owned by `authority`. > #[account(mut)] > pub obligation: UncheckedAccount<'info>, > /// CHECK: User metadata PDA for `authority`. > pub owner_user_metadata: UncheckedAccount<'info>, > > // -- Deposit reserve (Token A) -- > /// CHECK: Klend reserve for Token A. > #[account(mut)] > pub deposit_reserve: UncheckedAccount<'info>, > /// CHECK: Token A mint. > pub deposit_reserve_liquidity_mint: UncheckedAccount<'info>, > /// CHECK: Reserve's Token A supply vault. > #[account(mut)] > pub deposit_reserve_liquidity_supply: UncheckedAccount<'info>, > /// CHECK: Reserve's cToken mint. > #[account(mut)] > pub deposit_reserve_collateral_mint: UncheckedAccount<'info>, > /// CHECK: Reserve's cToken supply vault. > #[account(mut)] > pub deposit_reserve_collateral_supply: UncheckedAccount<'info>, > > // -- Borrow reserve (Token B) -- > /// CHECK: Klend reserve for Token B. > #[account(mut)] > pub borrow_reserve: UncheckedAccount<'info>, > /// CHECK: Token B mint. > pub borrow_reserve_liquidity_mint: UncheckedAccount<'info>, > /// CHECK: Borrow reserve's Token B supply vault. > #[account(mut)] > pub borrow_reserve_liquidity_supply: UncheckedAccount<'info>, > /// CHECK: Borrow reserve's fee receiver vault. > #[account(mut)] > pub borrow_reserve_fee_receiver: UncheckedAccount<'info>, > > // -- Programs and sysvars -- > /// CHECK: The Klend program. > #[account(address = KLEND_PROGRAM_ID)] > pub klend_program: UncheckedAccount<'info>, > /// CHECK: Kamino Farms program. > pub farms_program: UncheckedAccount<'info>, > pub token_program: Program<'info, Token>, > pub system_program: Program<'info, System>, > pub rent: Sysvar<'info, Rent>, > /// CHECK: Sysvar instructions (required by Klend). > #[account(address = solana_program::sysvar::instructions::ID)] > pub instructions_sysvar: UncheckedAccount<'info>, > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/docs/cpi_deposit_and_borrow.rs) > [accordion] What Happens When You Borrow? > > 1. USDT is withdrawn from the reserve pool and sent to your wallet > 2. Your borrow amount increases in your obligation > 3. You start accruing interest on the borrowed amount > 4. Your loan-to-value (LTV) ratio increases > 5. Your available borrowing capacity decreases > [accordion] How Much Can You Borrow? > > **Your maximum borrow amount depends on:** > > 1. Your collateral value > > 2. Loan-to-Value (LTV) ratio > > 3. Current borrows > > 4. Reserve liquidity > [accordion] Interest and Repayment > > **Interest:** > > * Accrues continuously based on the reserve's borrow APY > * Compounds over time > * Varies based on reserve utilization > > **Repayment:** > > * You must repay borrowed amount + accrued interest > * Repay anytime to reduce debt and improve your position health > [accordion] LTV > > **Keep LTV well below maximum:** > > * Monitor your position regularly > * Repay borrows or add collateral if LTV increases > * Be aware of price volatility # Deposit Source: https://docs.kamino.com/build/developers/borrow/operations/deposit Deposit assets as collateral or liquidity Deposit assets as collateral or supply liquidity into Kamino lending reserves. The SDK handles transaction building, instruction creation, and obligation management for deposit operations. ## Deposit for Lending Supply liquidity to the reserve and earn interest. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import BN from 'bn.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Build Deposit Instructions > > Supply USDC to the reserve. The wallet receives the reserve's cTokens, which grow in value as borrowers pay interest. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const depositAction = await KaminoAction.buildDepositReserveLiquidityTxns({ > kaminoMarket: market!, > amount: new BN(1_000_000), > reserveAddress: usdcReserve.address, > owner: signer, > obligation: new VanillaObligation(PROGRAM_ID), > scopeRefreshConfig: undefined, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > > [!NOTE] > > > > This doesn't open a borrow position, so the `obligation` prop is required by the type but unused. A market can hold several reserves for the same token, so actions take a reserve address: `getExistingFloatRateReserveByMint` returns the variable-rate one. Redeem the cTokens with [Redeem cTokens](/build/tutorials/borrow/redeem-ctokens). > > **Step 4** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(depositAction), tx) > ); > ``` > > **Step 5** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > The deposit is complete. The USDC is supplied to the reserve and earning interest. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Fetch Reserve Data > > Fetch the reserve account from the chain and construct `ReserveInfo` from its raw bytes. > > ```rust theme={"theme":"css-variables"} > use klend_interface::helpers; > use klend_interface::ReserveInfo; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > let reserve_data = rpc_client.get_account(&reserve_pubkey)?; > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; > ``` > > > [!NOTE] > > > > Use `ReserveInfo::from_account_data(pubkey, &data)` to construct reserve info from raw RPC account bytes. > > **Step 4** > > ### Derive Token Accounts > > Derive the user's associated token accounts for the liquidity mint and collateral mint. > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > // User's ATA for the deposit token (e.g. USDC) > let user_source_liquidity = get_associated_token_address(&owner, &reserve.liquidity_mint); > > // Derive the collateral mint PDA, then the user's ATA for it > let (collateral_mint, _) = pda::reserve_collateral_mint(&KLEND_PROGRAM_ID, &reserve_pubkey); > let user_destination_collateral = get_associated_token_address(&owner, &collateral_mint); > ``` > > **Step 5** > > ### Build Instructions > > ```rust theme={"theme":"css-variables"} > let instructions = helpers::deposit::deposit( > owner, > &reserve, > user_source_liquidity, // user's USDC token account > user_destination_collateral, // user's cToken account > 1_000_000, // 1 USDC (6 decimals) > ); > // Returns: [refresh_reserve, deposit_reserve_liquidity] > ``` > > **Step 6** > > ### Build and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Deposit successful! Signature: {signature}"); > ``` > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/deposit_lending.rs) ## Deposit for Borrowing Deposit USDC as collateral to borrow other assets. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import BN from 'bn.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Build Deposit Instructions > > Deposit USDC as collateral into the wallet's borrow position. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const depositAction = await KaminoAction.buildDepositTxns({ > kaminoMarket: market!, > amount: new BN(3_000_000), > reserveAddress: usdcReserve.address, > owner: signer, > obligation: new VanillaObligation(PROGRAM_ID), > useV2Ixs: true, > scopeRefreshConfig: undefined, > initUserMetadata: { skipInitialization: false, skipLutCreation: true }, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > > [!NOTE] > > > > A first deposit also creates the wallet's user metadata and obligation accounts. `skipLutCreation: true` keeps that setup in the same transaction. Without it, the SDK also creates a user lookup table, which only activates a slot later, and the deposit fails with `0x17a3`. > > **Step 4** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(depositAction), tx) > ); > ``` > > **Step 5** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > The deposit is complete. The collateral is now deposited and can be used for borrowing other assets. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Build Obligation Context > > Derive the obligation PDA, fetch its account data along with all associated reserves, and build an `ObligationContext`. > > ```rust theme={"theme":"css-variables"} > use klend_interface::ObligationContext; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > // Derive the obligation PDA > let (obligation_pubkey, _) = pda::obligation( > &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, > &Pubkey::default(), &Pubkey::default(), > ); > > // Fetch the obligation account > let obligation_data = rpc_client.get_account(&obligation_pubkey)?; > > // Discover which reserves the obligation references > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; > > // Fetch all reserve accounts in one RPC call > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > > // Build the context > let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() > .zip(reserve_accounts.iter()) > .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) > .collect(); > let ctx = ObligationContext::from_account_data( > obligation_pubkey, &obligation_data.data, &reserves > )?; > ``` > > > [!NOTE] > > > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. > > **Step 4** > > ### Derive Token Accounts > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > // User's ATA for the deposit token (e.g. USDC) > let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); > let user_source_liquidity = get_associated_token_address(&owner, &liquidity_mint); > ``` > > **Step 5** > > ### Build Instructions > > ```rust theme={"theme":"css-variables"} > let instructions = ctx.deposit( > owner, > &reserve_pubkey, > user_source_liquidity, > 3_000_000, // 3 USDC (6 decimals) > )?; > // Returns: [refresh_reserves..., refresh_obligation, deposit_and_collateral_v2] > ``` > > **Step 6** > > ### Build and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Deposit successful! Signature: {signature}"); > ``` > > > [!TIP] > > > > The deposit is complete. Your collateral has been supplied and your borrow position is open. > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/deposit_borrowing.rs) # Repay Source: https://docs.kamino.com/build/developers/borrow/operations/repay Repay borrowed assets Return borrowed assets to reduce or close positions. The SDK handles transaction building, instruction creation for debt repayment. ## Repay Return borrowed assets into the reserve. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import BN from 'bn.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Load the Obligation > > Load the wallet's borrow position so the SDK refreshes every reserve it uses. > > ```typescript theme={"theme":"css-variables"} > const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); > > if (!obligation) { > console.log('No borrow position found for', signer.address); > } > ``` > > **Step 4** > > ### Build Repay Instructions > > Repay part of the USDT loan from the USDT in the wallet. > > ```typescript theme={"theme":"css-variables"} > const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); > const usdtReserve = market!.getExistingFloatRateReserveByMint(usdtMint); > > const repayAction = await KaminoAction.buildRepayTxns({ > kaminoMarket: market!, > amount: new BN(500_000), > reserveAddress: usdtReserve.address, > owner: signer, > obligation: obligation!, > useV2Ixs: true, > scopeRefreshConfig: undefined, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > > [!TIP] > > > > To repay the whole loan including accrued interest, pass `new BN(U64_MAX)` as the amount (`U64_MAX` is exported by the SDK). The program repays the exact debt, so no dust is left. > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(repayAction), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Repay successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > The repayment is complete. The debt in the borrow position is reduced. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Build Obligation Context > > ```rust theme={"theme":"css-variables"} > use klend_interface::ObligationContext; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let repay_reserve_pubkey = Pubkey::from_str("FBSyPnxtHKLBZ4UeeUyAnbtFuAmTHLtso9YtsqRDRWpM").unwrap(); > > // Derive the obligation PDA > let (obligation_pubkey, _) = pda::obligation( > &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, > &Pubkey::default(), &Pubkey::default(), > ); > > // Fetch the obligation account > let obligation_data = rpc_client.get_account(&obligation_pubkey)?; > > // Discover which reserves the obligation references > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; > > // Fetch all reserve accounts in one RPC call > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > > // Build the context > let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() > .zip(reserve_accounts.iter()) > .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) > .collect(); > let ctx = ObligationContext::from_account_data( > obligation_pubkey, &obligation_data.data, &reserves > )?; > ``` > > > [!NOTE] > > > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. > > **Step 4** > > ### Derive Token Accounts > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > // User's ATA for the repay token (e.g. USDT) > let repay_liquidity_mint = Pubkey::from_str("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB").unwrap(); > let user_source_liquidity = get_associated_token_address(&owner, &repay_liquidity_mint); > ``` > > **Step 5** > > ### Build Instructions > > ```rust theme={"theme":"css-variables"} > let instructions = ctx.repay( > owner, > &repay_reserve_pubkey, > user_source_liquidity, > 1_000_000, // 1 USDT (6 decimals) > )?; > // Returns: [refresh_reserves..., refresh_obligation, repay_obligation_liquidity_v2] > ``` > > **Step 6** > > ### Build and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Repay successful! Signature: {signature}"); > ``` > > > [!NOTE] > > > > Repaying reduces your debt and improves your loan-to-value (LTV) ratio, making your position healthier and reducing liquidation risk. > > > [!TIP] > > > > The repay is complete. Your debt has been reduced. > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/repay.rs) > [accordion] What Happens When You Repay? > > 1. Assets are transferred from your wallet to the reserve pool > 2. Your borrow amount decreases in your obligation > 3. You stop paying interest on the repaid amount > 4. Your loan-to-value (LTV) ratio decreases (healthier position) > 5. Your available borrowing capacity increases > [accordion] Repayment and Interest > > **Repay some of your debt to improve your LTV:** > > * Repaying entire borrowed amount + accrued interest eliminates debt > * Full repayment allows you to withdraw all collateral > * You must repay the principal + accrued interest > * Interest accrues continuously # Withdraw Source: https://docs.kamino.com/build/developers/borrow/operations/withdraw Withdraw liquidity or collateral Withdraw liquidity or collateral from the reserve. The SDK handles transaction building, instruction creation, and collateral release calculations. ## Withdraw for Lending Withdraw liquidity from the reserve. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getAssociatedTokenAddress, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import BN from 'bn.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Build Redeem Instructions > > Redeem all of the wallet's USDC reserve cTokens for USDC, principal plus the interest they earned. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const cTokenAccount = await getAssociatedTokenAddress(usdcReserve.getCTokenMint(), signer.address); > const { value: cTokenBalance } = await rpc.getTokenAccountBalance(cTokenAccount).send(); > > const redeemAction = await KaminoAction.buildRedeemReserveCollateralTxns({ > kaminoMarket: market!, > amount: new BN(cTokenBalance.amount), > reserveAddress: usdcReserve.address, > owner: signer, > obligation: new VanillaObligation(PROGRAM_ID), > scopeRefreshConfig: undefined, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > > [!NOTE] > > > > The amount is in cTokens, not USDC, so this reads the wallet's cToken balance and redeems all of it. > > **Step 4** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(redeemAction), tx) > ); > ``` > > **Step 5** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Redeem successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > The withdrawal is complete. The cTokens are redeemed and the USDC is back in the wallet. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Fetch Reserve Data > > ```rust theme={"theme":"css-variables"} > use klend_interface::ReserveInfo; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > let reserve_data = rpc_client.get_account(&reserve_pubkey)?; > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; > ``` > > > [!NOTE] > > > > Use `ReserveInfo::from_account_data(pubkey, &data)` to construct reserve info from raw RPC account bytes. > > **Step 4** > > ### Derive Token Accounts > > ```rust theme={"theme":"css-variables"} > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use spl_associated_token_account::get_associated_token_address; > > // User's ATA for the underlying token (e.g. USDC) > let user_destination_liquidity = get_associated_token_address(&owner, &reserve.liquidity_mint); > > // User's ATA for the cToken (collateral token received when depositing) > let (collateral_mint, _) = pda::reserve_collateral_mint(&KLEND_PROGRAM_ID, &reserve_pubkey); > let user_source_collateral = get_associated_token_address(&owner, &collateral_mint); > ``` > > **Step 5** > > ### Build Instructions > > ```rust theme={"theme":"css-variables"} > use klend_interface::helpers; > > let collateral_amount = 1_000_000; // amount of cTokens to redeem > > let instructions = helpers::withdraw::redeem( > owner, > &reserve, > user_source_collateral, // cToken account (burned) > user_destination_liquidity, // receives underlying tokens + interest > collateral_amount, > ); > // Returns: [refresh_reserve, redeem_reserve_collateral] > ``` > > > [!NOTE] > > > > For simple lending withdrawals (no obligation), use `helpers::withdraw::redeem()` to redeem cTokens for the underlying liquidity plus accrued interest. Use `ObligationContext::withdraw()` if you need to withdraw collateral from an obligation (borrowing flow). > > **Step 6** > > ### Build and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Redeem successful! Signature: {signature}"); > ``` > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/redeem_ctokens.rs) ## Withdraw for Borrowing Withdraw collateral from an obligation. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import BN from 'bn.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Load the Obligation > > Load the wallet's borrow position so the SDK refreshes every reserve it uses. > > ```typescript theme={"theme":"css-variables"} > const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); > > if (!obligation) { > console.log('No borrow position found for', signer.address); > } > ``` > > **Step 4** > > ### Build Withdraw Instructions > > Withdraw USDC collateral from the borrow position. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const withdrawAction = await KaminoAction.buildWithdrawTxns({ > kaminoMarket: market!, > amount: new BN(1_000_000), > reserveAddress: usdcReserve.address, > owner: signer, > obligation: obligation!, > useV2Ixs: true, > scopeRefreshConfig: undefined, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > > [!TIP] > > > > With open borrows, the withdrawal must keep the position under its borrow limit. To withdraw all of a deposit, pass `new BN(U64_MAX)` as the amount (`U64_MAX` is exported by the SDK). > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(withdrawAction), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Withdraw successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > The withdrawal is complete. The collateral is back in the wallet. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Build Obligation Context > > ```rust theme={"theme":"css-variables"} > use klend_interface::ObligationContext; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > // Derive the obligation PDA > let (obligation_pubkey, _) = pda::obligation( > &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, > &Pubkey::default(), &Pubkey::default(), > ); > > // Fetch the obligation account > let obligation_data = rpc_client.get_account(&obligation_pubkey)?; > > // Discover which reserves the obligation references > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; > > // Fetch all reserve accounts in one RPC call > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > > // Build the context > let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() > .zip(reserve_accounts.iter()) > .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) > .collect(); > let ctx = ObligationContext::from_account_data( > obligation_pubkey, &obligation_data.data, &reserves > )?; > ``` > > > [!NOTE] > > > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. > > **Step 4** > > ### Derive Token Accounts > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > // User's ATA for the withdrawal token (e.g. USDC) > let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); > let user_dest_liquidity = get_associated_token_address(&owner, &liquidity_mint); > ``` > > **Step 5** > > ### Build Instructions > > ```rust theme={"theme":"css-variables"} > let instructions = ctx.withdraw( > owner, > &reserve_pubkey, > user_dest_liquidity, > 1_000_000, // 1 USDC (6 decimals) > )?; > // Returns: [refresh_reserves..., refresh_obligation, withdraw_and_redeem] > ``` > > > [!NOTE] > > > > Use `helpers::withdraw::redeem()` if you hold cTokens without an obligation — see the [Withdraw for Lending](/build/developers/borrow/operations/withdraw#withdraw-for-lending) tab. > > **Step 6** > > ### Build and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Withdrawal successful! Signature: {signature}"); > ``` > > > [!TIP] > > > > The withdrawal is complete. Your collateral has been returned to your wallet. > > [View Code](https://github.com/Kamino-Finance/klend/blob/master/libs/klend-interface/examples/withdraw_obligation.rs) > [accordion] What Happens When You Withdraw Collateral? > > 1. The collateral amount is removed from your obligation > 2. Your borrowing capacity decreases > 3. Your loan-to-value (LTV) ratio increases # Calculate Claimable User Rewards Source: https://docs.kamino.com/build/developers/borrow/rewards/calculate-claimable-user-rewards Calculate pending rewards for a user across all farm positions and check claimability > [!NOTE] > > **Farm Position Types** > > User rewards can come from different types of farm positions: > > * **Liquidity Farms**: Rewards from providing liquidity to Kamino vaults > * **Lend Farms**: Rewards from depositing collateral or holding vault shares > * **Borrow Markets Farms**: Rewards from borrowing assets (debt farms) or holding collateral/debt combinations (extra farms) > * **Multiply Farms**: Rewards from leveraged positions > > This tutorial shows how to identify all farm positions for a user and calculate their claimable rewards across all position types. ## Calculate Claimable User Rewards Calculate pending rewards for a user across all farm positions and check if they are claimable based on cooldown periods. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address, type Address } from '@solana/kit'; import { Farms, fetchAllMaybeFarmState, type FarmState, type UserFarm, type PendingReward } from '@kamino-finance/farms-sdk'; import { VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import Decimal from 'decimal.js'; type FarmPositionType = 'Liquidity' | 'Lend' | 'Borrow Markets' | 'Multiply'; type RewardWithAmount = { reward: PendingReward; rewardInfo: FarmState['rewardInfos'][0]; lastClaimTs: string; amount: Decimal; }; const DEFAULT_PUBKEY = '11111111111111111111111111111111'; ``` **Step 2** ### Initialize RPC and User Address Set up the Solana RPC connection and define the user wallet and lending market addresses. ```typescript theme={"theme":"css-variables"} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const user = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); const lendingMarket = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); ``` **Step 3** ### Define Helper Functions Create helper functions to validate addresses and determine farm position types. First, define the address validation helper: ```typescript theme={"theme":"css-variables"} // Helper function: Check if address is not default pubkey const isNotDefaultPubkey = (addr: Address): boolean => { return addr.toString() !== DEFAULT_PUBKEY; }; ``` Next, create the farm type determination function that checks for Liquidity and Lend farms: ```typescript theme={"theme":"css-variables"} // Helper function: Determine farm position type based on farm and user state const determineFarmType = ( farmState: FarmState, userFarm: UserFarm, walletPubKey: Address, lendingMarketAddress: Address, obligationPDA: Address ): FarmPositionType => { // Check for Liquidity farm (has strategyId) if (isNotDefaultPubkey(farmState.strategyId)) { return 'Liquidity'; } // Check for Lend vault farm (has vaultId) const isVaultFarm = isNotDefaultPubkey(farmState.vaultId); if (isVaultFarm) { return 'Lend'; } ``` Finally, add the delegation logic to identify Borrow Markets and Multiply positions: ```typescript theme={"theme":"css-variables"} // Calculate delegation variables const delegateeIsOwner = userFarm.userState.delegatee.toString() === userFarm.userState.owner.toString(); const farmHasSecondDelegatedAuthority = isNotDefaultPubkey(farmState.secondDelegatedAuthority); const farmUserStateIsForObligation = userFarm.userState.delegatee.toString() === obligationPDA.toString(); // Check for Lend collateral farm (delegated but not for obligation) if (!delegateeIsOwner && farmHasSecondDelegatedAuthority && !farmUserStateIsForObligation) { return 'Lend'; } // Check for Borrow Markets (delegated to obligation) if ( lendingMarketAddress && (farmUserStateIsForObligation || walletPubKey.toString() === userFarm.userState.delegatee.toString()) ) { return 'Borrow Markets'; } // Default to Multiply return 'Multiply'; }; ``` > [!NOTE] > > The `determineFarmType` function uses various state checks to identify the farm position type. Liquidity farms have a `strategyId`, Lend farms have a `vaultId` or specific delegation patterns, and Borrow Markets farms are identified by obligation delegation. **Step 4** ### Fetch User Farms Get all farms the user is participating in and fetch their states in parallel. ```typescript theme={"theme":"css-variables"} const farms = new Farms(rpc); const currentTime = new Decimal(Math.floor(Date.now() / 1000)); // Get all farms user is participating in const userFarms = await farms.getAllFarmsForUser(user, currentTime); // Fetch farm states in batch const farmAddresses = Array.from(userFarms.keys()); const farmStates = await fetchAllMaybeFarmState(rpc, farmAddresses); // Build farm data objects const farmsData = farmAddresses.flatMap((farmAddress, index) => { const farmState = farmStates[index]; const userFarm = userFarms.get(farmAddress); return farmState.exists && userFarm ? [{ farmAddress, userFarm, farmState: farmState.data }] : []; }); ``` > [!NOTE] > > The `getAllFarmsForUser` method returns a map of all farms where the user has an active position. Using `fetchAllMaybeFarmState` fetches all farm states in a single batch request. **Step 5** ### Calculate Obligation PDA and Display Rewards Calculate the obligation PDA, then loop through all user farms to calculate pending rewards and check if they're claimable based on cooldown periods. First, calculate the obligation PDA: ```typescript theme={"theme":"css-variables"} // Calculate obligation PDA const obligationType = new VanillaObligation(PROGRAM_ID); const obligationPDA = await obligationType.toPda(lendingMarket, user); ``` Then iterate through farms and filter rewards with positive amounts: ```typescript theme={"theme":"css-variables"} for (const { farmAddress, userFarm, farmState } of farmsData) { // Determine farm type const farmType = determineFarmType(farmState, userFarm, user, lendingMarket, obligationPDA); // Filter and calculate token amounts const rewardsWithAmount = userFarm.pendingRewards .map((reward: PendingReward, index: number) => { const rewardInfo = farmState.rewardInfos[index]; const lastClaimTs = userFarm.userState.lastClaimTs[index]; if (reward.rewardTokenMint === DEFAULT_PUBKEY || !rewardInfo || !lastClaimTs) { return null; } const amount = new Decimal(reward.cumulatedPendingRewards.toString()).div( new Decimal(10).pow(Number(rewardInfo.token.decimals)) ); if (amount.gt(0)) { return { reward, rewardInfo, lastClaimTs: lastClaimTs.toString(), amount }; } return null; }) .filter((r): r is RewardWithAmount => r !== null); ``` Finally, check claimability based on cooldown periods and display the results: ```typescript theme={"theme":"css-variables"} // Only display farm if it has valid rewards if (rewardsWithAmount.length > 0) { console.log(`${farmType} Farm: ${farmAddress.toString()}`); console.log(` Owner: ${userFarm.userState.owner.toString()}`); console.log(` Delegatee: ${userFarm.userState.delegatee.toString()}`); for (const { reward, rewardInfo, lastClaimTs, amount } of rewardsWithAmount) { // Check if reward is claimable based on cooldown period const minClaimDuration = new Decimal(rewardInfo.minClaimDurationSeconds.toString()).toNumber(); const lastClaimTsNum = new Decimal(lastClaimTs).toNumber(); const currentTimeNum = currentTime.toNumber(); const timeSinceClaim = currentTimeNum - lastClaimTsNum; // Validate data (1 year = 31536000 seconds - anything larger is invalid) const isValidDuration = minClaimDuration < 31536000; const isValidTimestamp = timeSinceClaim >= 0 && timeSinceClaim < 31536000000; console.log(` Reward: ${reward.rewardTokenMint}`); console.log(` Amount: ${amount.toFixed(Number(rewardInfo.token.decimals))}`); if (!isValidDuration || !isValidTimestamp) { console.log(` Claimable: No\n`); } else { const claimable = timeSinceClaim >= minClaimDuration; if (claimable) { console.log(` Claimable: Yes\n`); } else { const timeRemaining = minClaimDuration - timeSinceClaim; console.log(` Claimable: ${Math.ceil(timeRemaining / 60)}m\n`); } } } } } ``` > [!TIP] > > The script outputs all pending rewards grouped by farm type and position. Each reward shows the token mint, amount, and claimability status. If a reward has a cooldown period, the remaining time is displayed in minutes. # Calculate Reserve Reward APY Source: https://docs.kamino.com/build/developers/borrow/rewards/calculate-reserve-reward-apy Calculate collateral and debt farm reward APY for market reserves > [!NOTE] > > **Reserve Farms vs Extra Farms** > > Reserve farms are attached directly to a reserve and reward all users who deposit or borrow that reserve asset. Depositors earn rewards through collateral farms, while borrowers earn rewards through debt farms. > > Extra farms reward users only when specific collateral and debt combinations are used. Rewards are conditional on holding qualifying positions rather than simply depositing or borrowing a single reserve. > > This tutorial focuses on reserve farms. ## Calculate Reserve Reward APY Calculate APY for both collateral and debt farm rewards on a specific reserve. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address, type Address } from '@solana/kit'; import { KaminoMarket, PROGRAM_ID, lamportsToNumberDecimal } from '@kamino-finance/klend-sdk'; import { fetchAllMaybeFarmState, calculateCurrentRewardPerToken } from '@kamino-finance/farms-sdk'; import Decimal from 'decimal.js'; type PriceData = { mint: string; price: string }; const DEFAULT_PUBKEY = '11111111111111111111111111111111'; ``` **Step 2** ### Initialize RPC and Fetch Prices Set up the Solana RPC connection and fetch token prices from the Kamino API. ```typescript theme={"theme":"css-variables"} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const mainMarket = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const usdsMint = address('USDSwr9ApdHk5bvJKMjzff41FfuX8bSxdKcR81vTwcA'); // Fetch token prices from Kamino API const pricesRes = await fetch('https://api.kamino.finance/oracles/prices?markets=main'); const pricesData = (await pricesRes.json()) as PriceData[]; const priceMap = new Map(); for (const p of pricesData) { priceMap.set(p.mint, parseFloat(p.price)); } ``` > [!NOTE] > > Creating a price map allows quick lookups for multiple reward tokens. The example uses USDS reserve which has both collateral and debt farm rewards active. **Step 3** ### Load Market and Reserve Load the Kamino market and get the reserve by its mint address. ```typescript theme={"theme":"css-variables"} // Load market and reserve const market = await KaminoMarket.load(rpc, mainMarket, 400, PROGRAM_ID); const [reserve] = market!.getReservesByMint(usdsMint); if (!reserve) { console.log('Reserve not found'); } else { ``` > [!NOTE] > > The `getReservesByMint` method returns the reserves for a mint (here, the first one), and retrieves the reserve configuration including references to both the collateral farm and debt farm addresses. **Step 4** ### Collect and Fetch Farm Addresses Collect both collateral and debt farm addresses, checking they're not the default pubkey, then fetch all farms in parallel. ```typescript theme={"theme":"css-variables"} // Collect debt and collateral farm addresses const farmsToFetch: { name: string; address: Address }[] = []; if (reserve.state.farmCollateral.toString() !== DEFAULT_PUBKEY) { farmsToFetch.push({ name: 'Collateral Farm Rewards', address: reserve.state.farmCollateral }); } if (reserve.state.farmDebt.toString() !== DEFAULT_PUBKEY) { farmsToFetch.push({ name: 'Debt Farm Rewards', address: reserve.state.farmDebt }); } // Fetch all farms in batch const farmAddresses = farmsToFetch.map((f) => f.address); const farmStates = await fetchAllMaybeFarmState(rpc, farmAddresses); const farms = farmsToFetch.flatMap((farmInfo, index) => { const state = farmStates[index]; return state.exists ? [{ name: farmInfo.name, state: state.data }] : []; }); ``` > [!NOTE] > > Checking for the default pubkey ensures we only fetch farms that are actually configured on the reserve. Using `fetchAllMaybeFarmState` fetches all farm states in a single batch request, which is more efficient than individual fetches. **Step 5** ### Calculate Farm Reward APY Calculate APY for each active reward on both collateral and debt farms. ```typescript theme={"theme":"css-variables"} for (const farm of farms) { const totalStaked = lamportsToNumberDecimal( farm.state.totalStakedAmount.toString(), Number(farm.state.token.decimals) || 6 ); console.log(farm.name + ':'); for (const rewardInfo of farm.state.rewardInfos) { if (rewardInfo.rewardsAvailable > 0n && !totalStaked.isZero()) { const rewardMint = rewardInfo.token.mint.toString(); const rewardPrice = priceMap.get(rewardMint) || 1; const currentTime = new Decimal(Date.now() / 1000); // Calculate APY from farm rewards const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(rewardInfo, currentTime); // returns the raw value const divisor = new Decimal(10) .pow(rewardInfo.rewardsPerSecondDecimals.toString()) .mul(new Decimal(10).pow(rewardInfo.token.decimals.toString())); const adjustedRewardPerToken = new Decimal(rewardPerTokenPerSecond).div(divisor); const dailyRewards = adjustedRewardPerToken.mul(86400).mul(rewardPrice); const apy = Decimal.pow(dailyRewards.div(totalStaked).plus(1), 365).minus(1); console.log(` Reward Token: ${rewardMint}`); console.log(` APY: ${(apy.toNumber() * 100).toFixed(2)}%\n`); } } } } ``` > [!TIP] > > The script outputs APY for all active rewards on both the collateral and debt farms. The `calculateCurrentRewardPerToken` helper from farms-sdk handles the reward schedule logic. Each reward is priced in USD and the total staked amount represents the value of all positions earning that reward. # Claim User Rewards Source: https://docs.kamino.com/build/developers/borrow/rewards/claim-user-rewards Claim all pending rewards from lending farm positions > [!NOTE] > > **Delegated vs Non-Delegated Farms** > > Different farm types use different delegation patterns. For the correct delegatees for your specific farm, check the user farm state returned by `getAllFarmsForUser` in the "Calculate Claimable User Rewards" tutorial. ## Claim User Rewards Claim all pending rewards from a user's farm position. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, parseKeypairFile, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import { Farms } from '@kamino-finance/farms-sdk'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} // Configuration - UPDATE THESE VALUES const KEYPAIR_FILE = '/path/to/your/keypair.json'; // Load keypair from file const signer = await parseKeypairFile(KEYPAIR_FILE); // Initialize RPC and RPC Subscriptions const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); ``` **Step 3** ### Load Market and Get Obligation Load the Kamino market and get the user's obligation address. ```typescript theme={"theme":"css-variables"} const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const market = await KaminoMarket.load(rpc, marketPubkey, 400); // Get obligation address for delegatees array const kaminoObligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!kaminoObligation) { console.log('No obligation found'); } console.log('Obligation:', kaminoObligation?.obligationAddress.toString()); ``` **Step 4** ### Build Claim Instructions Use the Farms SDK to build claim instructions for all rewards on the farm. ```typescript theme={"theme":"css-variables"} // Build claim instructions using farms-sdk const farm = new Farms(rpc); const claimIxs = await farm.claimForUserForFarmAllRewardsIx( signer, // payer signer.address, // user (wallet address = owner) address('Gsoc83qRQ5X1LfGGbPqU2FdxZnveqbkP2vMXq6BcmtMk'), // farm true, // isDelegated = true for lending farms [signer.address, kaminoObligation!.obligationAddress] // delegatees array ); ``` > [!WARNING] > > The `delegatees` array values depend on your specific farm position. To find the correct delegatee addresses for your farm, use the "Calculate Claimable User Rewards" tutorial - it shows the actual delegatee in the user farm state. **Step 5** ### Build and Sign Transaction Use Kit's functional pipe pattern to build and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const claimTx = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(claimIxs, tx) ); const claimSigned = await signTransactionMessageWithSigners(claimTx); const claimSignature = getSignatureFromTransaction(claimSigned); ``` **Step 6** ### Send and Confirm Transaction Send the transaction to the network and wait for confirmation. ```typescript theme={"theme":"css-variables"} await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(claimSigned, { commitment: 'confirmed', skipPreflight: true, }); console.log(`Claim farm rewards successful! Signature: ${claimSignature}`); ``` > [!TIP] > > The rewards have been claimed and transferred to your wallet. You can verify the transaction using the signature on a Solana explorer. # Calculate Extra Farm Reward APY Source: https://docs.kamino.com/build/developers/borrow/rewards/extra-farm-reward-apy Calculate APY for extra farm stablecoin rewards > [!NOTE] > > Extra farms provide additional rewards to users who deposit specific collateral and borrow specific assets. ## Calculate Extra Farm Reward APY Calculate APY for extra farm rewards paid in stablecoins like CASH that are pegged to USD. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { fetchAllMaybeFarmState, calculateCurrentRewardPerToken } from '@kamino-finance/farms-sdk'; import { KaminoMarket, PROGRAM_ID, lamportsToNumberDecimal } from '@kamino-finance/klend-sdk'; import Decimal from 'decimal.js'; type ExtraFarm = { market: string; farm: string; collMint: string; debtMint: string }; type Resources = { 'mainnet-beta': { extraFarms: ExtraFarm[] } }; ``` **Step 2** ### Initialize RPC and Load Market Set up the Solana RPC connection and load the Kamino market. ```typescript theme={"theme":"css-variables"} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const mainMarketAddress = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); // Load market and get CASH and SOL mints from reserves const market = await KaminoMarket.load(rpc, mainMarketAddress, 400, PROGRAM_ID); let cashReserve, solReserve; for (const reserve of market!.reserves.values()) { if (reserve.stats.symbol === 'CASH') cashReserve = reserve; if (reserve.stats.symbol === 'SOL') solReserve = reserve; } if (!cashReserve || !solReserve) { console.log('CASH or SOL reserve not found'); } const cashMint = cashReserve!.getLiquidityMint().toString(); const solMint = solReserve!.getLiquidityMint().toString(); ``` > [!NOTE] > > This example targets the SOL/CASH extra farm pair where users deposit SOL collateral and borrow CASH to earn rewards. **Step 3** ### Get and Filter Extra Farms Fetch the list of extra farms from the CDN and filter by SOL collateral and CASH debt. ```typescript theme={"theme":"css-variables"} // Get extraFarms from CDN API and filter by SOL/CASH pair const cdnRes = await fetch('https://cdn.kamino.finance/resources.json'); const allResources = (await cdnRes.json()) as Resources; const kaminoResources = allResources['mainnet-beta']; const extraFarmsForMarket = kaminoResources.extraFarms.filter((f) => f.market === mainMarketAddress.toString()); // Filter by collateral (SOL) and debt (CASH) mints const solCashFarms = extraFarmsForMarket.filter((f) => f.collMint === solMint && f.debtMint === cashMint); ``` > [!NOTE] > > The CDN resources endpoint provides a list of all extra farms. We filter for farms that specifically reward SOL collateral deposits paired with CASH borrows. **Step 4** ### Fetch All Farm States in Batch Fetch all farm states in a single batch request for better performance. ```typescript theme={"theme":"css-variables"} // Fetch all farm states in batch const farmAddresses = solCashFarms.map((f) => address(f.farm)); const farmStates = await fetchAllMaybeFarmState(rpc, farmAddresses); const farms = solCashFarms.flatMap((extraFarm, index) => { const farmState = farmStates[index]; return farmState.exists ? [{ farm: extraFarm.farm, farmState: farmState.data }] : []; }); ``` > [!NOTE] > > Using `fetchAllMaybeFarmState` fetches all farm states in a single batch request. **Step 5** ### Calculate APY for SOL/CASH Farms Loop through the fetched farms and calculate APY for CASH rewards. ```typescript theme={"theme":"css-variables"} for (const { farm, farmState } of farms) { const totalStaked = lamportsToNumberDecimal( farmState.totalStakedAmount.toString(), Number(farmState.token.decimals) || 6 ); const cashReward = farmState.rewardInfos.find( (r) => r.token.mint.toString() === cashMint && r.rewardsAvailable > 0n ); if (cashReward && !totalStaked.isZero()) { const currentTime = new Decimal(Date.now() / 1000); // Calculate APY from farm rewards const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(cashReward, currentTime); // returns the raw value const divisor = new Decimal(10) .pow(cashReward.rewardsPerSecondDecimals.toString()) .mul(new Decimal(10).pow(cashReward.token.decimals.toString())); const adjustedRewardPerToken = new Decimal(rewardPerTokenPerSecond).div(divisor); const dailyRewards = adjustedRewardPerToken.mul(86400); const apy = Decimal.pow(dailyRewards.div(totalStaked).plus(1), 365).minus(1); console.log(`ExtraFarm: ${farm}`); console.log(` CASH APY: ${(apy.toNumber() * 100).toFixed(2)}%\n`); } } ``` > [!TIP] > > The script outputs the APY for SOL/CASH extra farms paying CASH rewards. The `calculateCurrentRewardPerToken` helper from farms-sdk handles the reward schedule logic. Since CASH is pegged to USD, no price lookup is required. # Create a Vault Source: https://docs.kamino.com/build/developers/earn/data/advanced-concepts/creating-a-vault Create and configure Kamino vaults with custom fee structures to earn revenue > [!NOTE] > > Learn how to create a Kamino vault with [custom fee structures](#configure-vault), deposit limits, and allocation strategies. The SDK manages vault initialization, metadata setup, and lookup table creation to optimize future transactions. ## Creating a Vault Initialize a new vault with custom configuration and prepare it for user deposits. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Instruction, } from '@solana/kit'; import { KaminoManager, KaminoVault, KaminoVaultConfig, getMedianSlotDurationInMsFromLastEpochs, sleep, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Admin Keypair and Initialize Manager Load the admin keypair from file and initialize the Kamino manager with proper slot timing. ```typescript theme={"theme":"css-variables"} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const adminSigner = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const kaminoManager = new KaminoManager(rpc, slotDuration); ``` > [!NOTE] > > `parseKeypairFile` loads an existing keypair from a JSON file that will become the vault admin. The admin wallet needs SOL for rent and fees, plus a small amount of the vault token: creation takes an initial deposit of 1,000 lamports (0.001 USDC here) from it. **Step 3** ### Configure Vault Create a vault configuration with the core identity and fee structure. ```typescript theme={"theme":"css-variables"} const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(15.0), managementFeeRatePercentage: new Decimal(2.0), name: 'MyCustomVault', vaultTokenSymbol: 'USDC', vaultTokenName: 'MyCustomVaultToken', minDepositAmount: 1000, minWithdrawAmount: 10, minInvestAmount: 0, minInvestDelaySlots: 0, withdrawalPenaltyBps: 1, withdrawalPenaltyLamports: 1, crankFundFeePerReserve: 1, }); ``` > [!NOTE] > > The parameters from `minDepositAmount` down are optional. The values shown are the defaults, so omit them to keep the defaults. All parameters can be changed after creation. Unallocated weight and cap can only be set after creation, see the [Configure Vault Parameters](#configure-vault-parameters-post-creation) step below. **Vault Configuration Parameters** | Parameter | Type | Default | Description | | - | - | - | - | | `admin` | `TransactionSigner` | | Keypair that owns and manages the vault | | `tokenMint` | `Address` | | SPL token mint address (e.g., USDC) | | `tokenMintProgramId` | `Address` | | Token program of the mint (`TOKEN_PROGRAM_ADDRESS`, or the Token-2022 program for Token-2022 mints) | | `performanceFeeRatePercentage` | `Decimal` | | Percentage of earned yield collected as fees | | `managementFeeRatePercentage` | `Decimal` | | Annual percentage fee on total assets | | `name` | `string` | | Vault name stored on-chain (max 40 characters) | | `vaultTokenSymbol` | `string` | | Symbol for vault share token (max 5 characters) | | `vaultTokenName` | `string` | | Display name for vault share token (max 10 characters) | | `minDepositAmount` | `number` | 1000 | Optional. Minimum deposit per transaction (lamports) | | `minWithdrawAmount` | `number` | 10 | Optional. Minimum withdrawal per transaction (lamports) | | `minInvestAmount` | `number` | 0 | Optional. Minimum amount moved in a single investment (lamports) | | `minInvestDelaySlots` | `number` | 0 | Optional. Slots between investments in a reserve | | `withdrawalPenaltyBps` | `number` | 1 | Optional. Percentage-based withdrawal fee (basis points) | | `withdrawalPenaltyLamports` | `number` | 1 | Optional. Absolute withdrawal fee (lamports) | | `crankFundFeePerReserve` | `number` | 1 | Optional. Fee per reserve to fund crank operations (lamports) | | `allowAllocationsInWhitelistedReservesOnly` | `boolean` | false | Optional. Only allow allocations to whitelisted reserves | | `allowInvestInWhitelistedReservesOnly` | `boolean` | false | Optional. Only allow investing in whitelisted reserves | **Step 4** ### Generate Vault Creation Instructions Pass the vault configuration to the Kamino manager to generate all required initialization instructions. ```typescript theme={"theme":"css-variables"} const { vault: vaultSigner, initVaultIxs: instructions } = await kaminoManager.createVaultIxs(kaminoVaultConfig); console.log('New vault address:', vaultSigner.address); ``` > [!NOTE] > > `createVaultIxs` returns a new vault keypair plus instruction bundles for initializing the vault, creating and filling its lookup table, creating its two farms (the Vault Farm for rewards and the First Loss Capital Farm), registering the farms on the vault, and setting the share token metadata. They are sent across four transactions in the steps below. **Step 5** ### Create a Send Function Vault creation sends several transactions, so define one function that builds, signs, and sends each of them. ```typescript theme={"theme":"css-variables"} async function sendTransaction(ixs: Instruction[], label: string) { const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(ixs, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`${label}:`, getSignatureFromTransaction(signedTransaction)); } ``` > [!NOTE] > > `signTransactionMessageWithSigners` signs with every signer in the instructions, including the new vault keypair. The blockhash is fetched inside the function so each transaction gets a fresh one. **Step 6** ### Initialize the Vault Send the first transaction: it creates the vault, applies the configuration, and creates the vault's lookup table. ```typescript theme={"theme":"css-variables"} await sendTransaction( [ ...instructions.createAtaIfNeededIxs, ...instructions.initVaultIxs, instructions.createLUTIx, ...instructions.cleanupIxs, ], 'Vault initialized' ); ``` > [!NOTE] > > The share token metadata instruction is sent later, in the last transaction. Adding it here takes this transaction over Solana's 1,232-byte limit. **Step 7** ### Create and Attach Farms Create the Vault Farm and the First Loss Capital Farm, and register each one on the vault. Each farm is one transaction. ```typescript theme={"theme":"css-variables"} const vaultFarm = instructions.createVaultFarms.createVaultFarmIxs; await sendTransaction( [...vaultFarm.setupFarmIxs, ...vaultFarm.updateFarmIxs, instructions.setFarmToVaultIxs.setFarmToVaultIx], 'Vault Farm created' ); const flcFarm = instructions.createVaultFarms.createFLCVaultFarmIxs; const setFlcFarm = instructions.setFarmToVaultIxs.setFLCFarmToVaultIx; if (flcFarm && setFlcFarm) { await sendTransaction( [...flcFarm.setupFarmIxs, ...flcFarm.updateFarmIxs, setFlcFarm], 'First Loss Capital Farm created' ); } ``` > [!NOTE] > > If you skip this step, you can create farms later with `kaminoManager.createVaultFarmIxs` and register them with `kaminoManager.updateVaultFarmIxs` (Vault Farm) or `kaminoManager.updateVaultFirstLossCapitalFarmIxs` (First Loss Capital Farm). See [Configure farms](/curators/vaults/guides/configure-farms) for the full post-creation flow. **Step 8** ### Fill the Lookup Table and Set Share Metadata Add the vault's accounts to its lookup table and set the share token metadata. ```typescript theme={"theme":"css-variables"} await sleep(2000); await sendTransaction( [...instructions.populateLUTIxs, instructions.initSharesMetadataIx], 'Lookup table filled and share metadata set' ); ``` > [!NOTE] > > A new lookup table can only be extended from the slot after it was created, so this transaction goes last. The lookup table keeps deposit and withdraw transactions for this vault small. **Step 9** ### Verify the Setup Check that every part of the vault was set up. ```typescript theme={"theme":"css-variables"} const vault = new KaminoVault(rpc, vaultSigner.address, slotDuration); const status = await kaminoManager.getVaultSetupStatus(vault, kaminoVaultConfig); if (status.allSet) { console.log('Vault created and fully set up:', vaultSigner.address); } else { console.log('Setup incomplete:', status); } ``` > [!NOTE] > > If a transaction failed, `kaminoManager.finishVaultSetup(vault, kaminoVaultConfig)` returns only the missing instructions, so you can send them without starting over. **Step 10** ### Configure Vault Parameters (Post-Creation) Set the parameters that are only available after creation (unallocated weight and cap), or update any parameter set during creation. ```typescript theme={"theme":"css-variables"} const vaultState = await vault.getState(); const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); const { updateVaultConfigIx: unallocWeightIx } = await kaminoManager.updateVaultUnallocatedWeightIxs(vault, 500, vaultReservesMap, adminSigner); const { updateVaultConfigIx: unallocCapIx } = await kaminoManager.updateVaultUnallocatedTokensCapIxs(vault, 2000000, vaultReservesMap, adminSigner); await sendTransaction([unallocWeightIx, unallocCapIx], 'Unallocated weight and cap set'); ``` > [!NOTE] > > Every creation parameter has an update method with the same arguments, for example `kaminoManager.updateVaultMinDepositAmountIxs(vault, 1000, vaultReservesMap, adminSigner)`. Each returns `{ updateVaultConfigIx }`. The new vault holds no allocations yet: add reserves with `kaminoManager.updateVaultReserveAllocationIxs` before it can earn. **Post-Creation Parameters** | Method | Parameter | Default | Description | | - | - | - | - | | `updateVaultMinDepositAmountIxs` | `minDepositAmount` | 1000 | Minimum deposit per transaction (lamports) | | `updateVaultMinWithdrawAmountIxs` | `minWithdrawAmount` | 10 | Minimum withdrawal per transaction (lamports) | | `updateVaultMinInvestAmountIxs` | `minInvestAmount` | 0 | Minimum amount moved in a single investment (lamports) | | `updateVaultMinInvestDelaySlotsIxs` | `minInvestDelaySlots` | 0 | Slots between investments in a reserve | | `updateVaultWithdrawalPenaltyBpsIxs` | `withdrawalPenaltyBps` | 1 | Percentage-based withdrawal fee (basis points); returned to vault | | `updateVaultWithdrawalPenaltyLamportsIxs` | `withdrawalPenaltyLamports` | 1 | Absolute withdrawal fee (lamports); system takes MAX of BPS and lamports | | `updateVaultCrankFundFeePerReserveIxs` | `crankFundFeePerReserve` | 1 | Fee per reserve to fund crank operations (lamports) | | `updateVaultUnallocatedWeightIxs` | `unallocatedWeight` | 500 | Relative weight for idle funds in total weight calculation | | `updateVaultUnallocatedTokensCapIxs` | `unallocatedTokensCap` | 2000000 | Maximum absolute amount to keep unallocated (lamports) | #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Instruction, } from '@solana/kit'; import { KaminoManager, KaminoVault, KaminoVaultConfig, getMedianSlotDurationInMsFromLastEpochs, sleep, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { Decimal } from 'decimal.js'; const KEYPAIR_FILE = '/path/to/your/keypair.json'; const adminSigner = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const kaminoManager = new KaminoManager(rpc, slotDuration); const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(15.0), managementFeeRatePercentage: new Decimal(2.0), name: 'MyCustomVault', vaultTokenSymbol: 'USDC', vaultTokenName: 'MyCustomVaultToken', minDepositAmount: 1000, minWithdrawAmount: 10, minInvestAmount: 0, minInvestDelaySlots: 0, withdrawalPenaltyBps: 1, withdrawalPenaltyLamports: 1, crankFundFeePerReserve: 1, }); const { vault: vaultSigner, initVaultIxs: instructions } = await kaminoManager.createVaultIxs(kaminoVaultConfig); console.log('New vault address:', vaultSigner.address); async function sendTransaction(ixs: Instruction[], label: string) { const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(ixs, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`${label}:`, getSignatureFromTransaction(signedTransaction)); } await sendTransaction( [ ...instructions.createAtaIfNeededIxs, ...instructions.initVaultIxs, instructions.createLUTIx, ...instructions.cleanupIxs, ], 'Vault initialized' ); const vaultFarm = instructions.createVaultFarms.createVaultFarmIxs; await sendTransaction( [...vaultFarm.setupFarmIxs, ...vaultFarm.updateFarmIxs, instructions.setFarmToVaultIxs.setFarmToVaultIx], 'Vault Farm created' ); const flcFarm = instructions.createVaultFarms.createFLCVaultFarmIxs; const setFlcFarm = instructions.setFarmToVaultIxs.setFLCFarmToVaultIx; if (flcFarm && setFlcFarm) { await sendTransaction( [...flcFarm.setupFarmIxs, ...flcFarm.updateFarmIxs, setFlcFarm], 'First Loss Capital Farm created' ); } await sleep(2000); await sendTransaction( [...instructions.populateLUTIxs, instructions.initSharesMetadataIx], 'Lookup table filled and share metadata set' ); const vault = new KaminoVault(rpc, vaultSigner.address, slotDuration); const status = await kaminoManager.getVaultSetupStatus(vault, kaminoVaultConfig); if (status.allSet) { console.log('Vault created and fully set up:', vaultSigner.address); } else { console.log('Setup incomplete:', status); } const vaultState = await vault.getState(); const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); const { updateVaultConfigIx: unallocWeightIx } = await kaminoManager.updateVaultUnallocatedWeightIxs(vault, 500, vaultReservesMap, adminSigner); const { updateVaultConfigIx: unallocCapIx } = await kaminoManager.updateVaultUnallocatedTokensCapIxs(vault, 2000000, vaultReservesMap, adminSigner); await sendTransaction([unallocWeightIx, unallocCapIx], 'Unallocated weight and cap set'); ``` # User Position Source: https://docs.kamino.com/build/developers/earn/data/user-position-data ## Reading User Position Data Retrieve user positions, balances, and transaction history using the Kamino SDK and API. > [!NOTE] > > Historical vault data is only available via the API. **Step 1** ### Get User Positions Retrieves user share balances across all vaults. Uses the SDK to query the user's positions in every vault they hold shares in. > [!NOTE] > > Using the SDK requires a private RPC connection or the public rate-limited [RPC endpoint](https://api.mainnet-beta.solana.com). ```typescript icon="typescript" getUserPositions theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; const manager = new KaminoManager( createSolanaRpc('https://api.mainnet-beta.solana.com'), await getMedianSlotDurationInMsFromLastEpochs() ); const user = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); const userSharesAllVaults = await manager.getUserSharesBalanceAllVaults(user); userSharesAllVaults.forEach((shares, vault) => { if (shares.totalShares.gt(0)) { console.log(`User shares in ${vault}:`, shares.totalShares.toString()); } }); ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-03-get-user-all-vaults-positions-example/index.ts) **Step 2** ### Get User Vault Position Retrieves user share balance and token value for a specific vault. Uses the SDK to calculate both shares held and their equivalent token amount. > [tab] TypeScript > > ```typescript icon="typescript" getUserVaultPosition theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > await getMedianSlotDurationInMsFromLastEpochs() > ); > > const user = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const shares = await vault.getUserShares(user); > const rate = await vault.getExchangeRate(await getCurrentLedgerInstant(rpc)); > > console.log({ > unstakedShares: shares.unstakedShares.toString(), > stakedShares: shares.stakedShares.toString(), > totalShares: shares.totalShares.toString(), > tokens: shares.totalShares.mul(rate).toString(), // the user's position in tokens > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-02-get-user-vault-position-example/index.ts) > [tab] Rust > > > [!NOTE] > > > > Read a user's vault position with the [`kvault-interface`](https://crates.io/crates/kvault-interface) crate: look up their share balance and value it in underlying tokens using the vault's current exchange rate (AUM ÷ shares issued). > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > kvault-interface = "0.1.0" > solana-client = "2.3" > solana-pubkey = "2.1" > spl-associated-token-account = "6" > ``` > > **Step 2** > > ### Fetch Vault State > > ```rust theme={"theme":"css-variables"} > use std::str::FromStr; > > use kvault_interface::{pda, state::VaultState, Fraction, KVAULT_PROGRAM_ID}; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use spl_associated_token_account::get_associated_token_address; > > let rpc = RpcClient::new("https://api.mainnet-beta.solana.com".to_string()); > > let vault_pubkey = Pubkey::from_str("HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E").unwrap(); > let user = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY").unwrap(); > > let vault_account = rpc.get_account(&vault_pubkey).unwrap(); > let vault = kvault_interface::from_account_data::(&vault_account.data).unwrap(); > ``` > > **Step 3** > > ### Read the User's Share Balance > > The shares mint is a PDA of the vault. Read the `amount` field (bytes 64..72, u64 little-endian) from the user's shares ATA. > > ```rust theme={"theme":"css-variables"} > let (shares_mint, _bump) = pda::shares_mint(&KVAULT_PROGRAM_ID, &vault_pubkey); > let user_shares_ata = get_associated_token_address(&user, &shares_mint); > > let shares_account = rpc.get_account(&user_shares_ata).unwrap(); > let user_shares = u64::from_le_bytes(shares_account.data[64..72].try_into().unwrap()); > ``` > > > [!NOTE] > > > > This only counts shares held in the user's share ATA. If the vault has a share farm (`VaultState::vault_farm` is set), most users keep their shares **staked in the farm**, so a complete implementation must also read the staked balance from `vault.vault_farm` (Kamino Farms) and add it. > > **Step 4** > > ### Compute Exchange Rate and Position Value > > ```rust theme={"theme":"css-variables"} > let aum = Fraction::from_bits(u128::from(vault.prev_aum_sf)); > let total_shares = vault.shares_issued; > > println!("Vault: {vault_pubkey}"); > println!(" Total AUM: {aum:.6}"); > println!(" Shares issued: {total_shares}"); > println!("\nUser: {user}"); > println!(" Shares held: {user_shares}"); > > if total_shares > 0 { > let exchange_rate = aum / Fraction::from_num(total_shares); > let position_value = Fraction::from_num(user_shares) * exchange_rate; > println!(" Exchange rate: {exchange_rate:.6} tokens/share"); > println!(" Position value: {position_value:.6} tokens"); > } else { > println!(" Vault has no shares issued"); > } > ``` > > [View Code](https://github.com/Kamino-Finance/kvault/blob/master/libs/kvault-interface/examples/user_position.rs) **Step 3** ### Get User Vault Transactions Queries transaction history for a specific user and vault over a time range. Returns time-series data including position changes and transaction details. ```typescript icon="typescript" getUserVaultTransactions theme={"theme":"css-variables"} const kvaultPubkey = 'A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'; const ownerPubkey = '883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62'; // user const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2024-01-01T00:00:00.000Z', end: '2025-10-01T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/history?${params}`; const res = await fetch(url); if (!res.ok) { console.log(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); for (const item of data) { console.log({ createdOn: item.createdOn, sharesAmount: item.sharesAmount, usdAmount: item.usdAmount, cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, }); } ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-08-get-user-vault-position-historical-info-example/index.ts) **Step 4** ### Get User Total Metrics History Queries cumulative performance metrics for a user across all vaults over a time range. Returns aggregated time-series data including total positions and earnings. ```typescript icon="typescript" getUserTotalMetricsHistory theme={"theme":"css-variables"} const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2024-01-01T00:00:00.000Z', end: '2025-11-20T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/metrics/history?${params}`; const res = await fetch(url); if (!res.ok) { console.log(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); for (const item of data) { console.log({ createdOn: item.createdOn, usdAmount: item.usdAmount, solAmount: item.solAmount, weightedApy: item.weightedApy, cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, }); } ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-09-get-user-all-vaults-positions-historical-info-example/index.ts) **Step 5** ### Get User Vault Metrics History Retrieves historical performance metrics for a specific user and vault. Returns time-series data including shares, APY, and cumulative interest earned. ```typescript icon="typescript" getUserVaultMetricsHistory theme={"theme":"css-variables"} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/history`; const res = await fetch(url); if (!res.ok) { console.log(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); for (const item of data) { console.log({ createdOn: item.createdOn, sharesAmount: item.sharesAmount, apy: item.apy, cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, }); } ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-08-get-user-vault-position-historical-info-example/index.ts) **Step 6** ### Get User Vault PnL Retrieves current profit and loss data for a user's position in a specific vault. Returns PnL metrics in USD, SOL, and token denominations. ```typescript icon="typescript" getUserVaultPnL theme={"theme":"css-variables"} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const url = `${API_BASE_URL}/kvaults/${kvaultPubkey}/users/${ownerPubkey}/pnl`; const res = await fetch(url); if (!res.ok) { console.log(`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, }); ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-11-get-vault-user-pnl-example/index.ts) **Step 7** ### Get User Vault PnL History Queries historical profit and loss data for a user's vault position. Returns transaction-level PnL history with cost basis, realized gains, and position values. ```typescript icon="typescript" getUserVaultPnLHistory theme={"theme":"css-variables"} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/pnl/history`; const res = await fetch(url); if (!res.ok) { console.log(`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, costBasisUsd: item.costBasis?.usd, positionValueUsd: item.positionValue?.usd, }); } ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) # Vault Source: https://docs.kamino.com/build/developers/earn/data/vault-data ## Reading Vault Data Retrieve vault TVL, APY, farm rewards, allocation weights, and user share balances using the Kamino SDK and API. > [!NOTE] > > Historical vault data is only available via the API. **Step 1** ### Get All Vaults This fetches all available Kamino vaults from the API, and returns an array of vault objects containing address, state, and configuration data for each vault. ```typescript icon="typescript" getAllVaults theme={"theme":"css-variables"} const url = 'https://api.kamino.finance/kvaults/vaults'; const res = await fetch(url); if (!res.ok) { console.log(`Request failed: ${res.status} ${res.statusText}`); } const vaults = await res.json(); console.log({ address: vaults[0].address, name: vaults[0].state.name, tokenMint: vaults[0].state.tokenMint, sharesIssued: vaults[0].state.sharesIssued, tokenAvailable: vaults[0].state.tokenAvailable, }); ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) **Step 2** ### Get Vault Info Retrieves real-time vault metrics including holdings, APY rates, and exchange rate. And uses the SDK to query on-chain vault state and performance data. > [!NOTE] > > Using the SDK requires a private RPC connection or the public rate-limited [RPC endpoint](https://api.mainnet-beta.solana.com). > [tab] TypeScript > > ```typescript icon="typescript" getVaultInfo theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > await getMedianSlotDurationInMsFromLastEpochs() > ); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const apys = await vault.getAPYs(ledgerInstant); > > console.log({ > holdings: (await vault.getVaultHoldings(ledgerInstant)).asJSON(), > actualAPY: apys.actualAPY.netAPY.toString(), > theoreticalAPY: apys.theoreticalAPY.netAPY.toString(), > exchangeRate: (await vault.getExchangeRate(ledgerInstant)).toString(), > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-01-get-vault-info-example/index.ts) > [tab] Rust > > > [!NOTE] > > > > Read and inspect a vault's on-chain state with the [`kvault-interface`](https://crates.io/crates/kvault-interface) crate — configuration, fees, AUM, and per-reserve allocations — using zero-copy deserialization, no SDK or RPC framework required beyond `solana-client`. > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > kvault-interface = "0.1.0" > solana-client = "2.3" > solana-pubkey = "2.1" > ``` > > **Step 2** > > ### Fetch and Parse the Vault > > `from_account_data::` deserializes the raw account bytes into a zero-copy `VaultState` view. > > ```rust theme={"theme":"css-variables"} > use std::str::FromStr; > > use kvault_interface::{ > from_account_data, > state::{VaultAllocation, VaultState}, > Fraction, > }; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > > let rpc = RpcClient::new("https://api.mainnet-beta.solana.com".to_string()); > let vault_pubkey = Pubkey::from_str("HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E").unwrap(); > > let vault_account = rpc.get_account(&vault_pubkey).unwrap(); > let vault = from_account_data::(&vault_account.data).unwrap(); > ``` > > **Step 3** > > ### Read Vault Configuration > > ```rust theme={"theme":"css-variables"} > println!("Vault: {vault_pubkey}"); > println!(" Admin: {}", vault.vault_admin_authority); > println!(" Token mint: {}", vault.token_mint); > println!(" Available liquidity: {}", vault.token_available); > println!(" Shares issued: {}", vault.shares_issued); > println!(" Performance fee: {} bps", vault.performance_fee_bps); > println!(" Management fee: {} bps", vault.management_fee_bps); > > let prev_aum = Fraction::from_bits(u128::from(vault.prev_aum_sf)); > println!(" Previous AUM: {prev_aum:.6}"); > ``` > > > [!NOTE] > > > > Fields suffixed with `_sf` are **scaled fractions** (fixed-point integers, 68 integer bits + 60 fractional bits). Convert them to a readable decimal with `Fraction::from_bits(u128::from(value))`. > > **Step 4** > > ### Inspect Per-Reserve Allocations > > The vault splits its assets across Klend reserves. Empty slots have a default `reserve` pubkey, so filter those out. > > ```rust theme={"theme":"css-variables"} > let active_allocations: Vec<&VaultAllocation> = vault > .vault_allocation_strategy > .iter() > .filter(|a| a.reserve != Pubkey::default()) > .collect(); > > println!("\n Active allocations: {}", active_allocations.len()); > for alloc in &active_allocations { > let target = Fraction::from_bits(u128::from(alloc.token_target_allocation_sf)); > println!(" Reserve: {}", alloc.reserve); > println!(" Weight: {}", alloc.target_allocation_weight); > println!(" cToken balance: {}", alloc.ctoken_allocation); > println!(" Token cap: {}", alloc.token_allocation_cap); > println!(" Target allocation: {target:.6}"); > } > ``` > > [View Code](https://github.com/Kamino-Finance/kvault/blob/master/libs/kvault-interface/examples/vault_data.rs) **Step 3** ### Get User Vault Position Historical Info This queries historical performance metrics for a specific user's position in a vault over a time range, and returns time-series data including the user's balance, yield, and allocation changes. ```typescript icon="typescript" getUserVaultPositionHistory theme={"theme":"css-variables"} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2024-01-01T00:00:00.000Z', end: '2025-01-01T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/history?${params}`; const res = await fetch(url); if (!res.ok) { console.log(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); console.log(data); ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-08-get-user-vault-position-historical-info-example/index.ts) **Step 4** ### Get Vault Metrics History Retrieves historical vault-level performance metrics including TVL, APY, and farm rewards APY. Returns time-series data showing the vault's total value locked, yield rates, and reward rates over time. ```typescript icon="typescript" getVaultMetricsHistory theme={"theme":"css-variables"} const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2024-06-01T00:00:00.000Z', end: '2025-01-01T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/kvaults/vaults/${kvaultPubkey}/metrics/history?${params}`; const res = await fetch(url); if (!res.ok) { console.log(`Request failed: ${res.status} ${res.statusText}`); } const data = await res.json(); for (const item of data) { console.log({ tvl: item.tvl, apy: item.apy, apyFarmRewards: item.apyFarmRewards, }); } ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) **Step 5** ### Get Advanced Vault Allocation Info Queries the vault's allocation strategy showing how funds are distributed across different reserves with their target weights and current allocations. ```typescript icon="typescript" getVaultAllocations theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault await getMedianSlotDurationInMsFromLastEpochs() ); const allocations = await vault.getVaultAllocations(); for (const [address, overview] of allocations) { console.log( `Reserve: ${address}: weight ${overview.targetWeight.toString()}, allocation: ${overview.ctokenAllocationLamports.toString()}` ); } ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-06-get-vault-advanced-info-allocations-example/index.ts) **Step 6** ### Get Advanced Vault Incentives Info Retrieves detailed incentive information for the vault including delegated farm rewards, reserve farm incentives, and direct vault farm incentives along with comprehensive vault overview metrics. ```typescript icon="typescript" getVaultIncentives theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { Farms } from '@kamino-finance/farms-sdk'; import { Decimal } from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const kaminoManager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); const ledgerInstant = await getCurrentLedgerInstant(rpc); const vaultTokenPrice = new Decimal(1.0); // as it is an USDC vault the token price is 1 const vaultOverview = await kaminoManager.getVaultOverview( vault, vaultTokenPrice, ledgerInstant, vaultReservesMap, await kaminoManager.loadKaminoMarketsForVaultReserves(vaultReservesMap), await kaminoManager.loadVaultFarmStates([vaultState], vaultReservesMap), new Farms(rpc), await kaminoManager.loadKVaultGlobalConfig(), ledgerInstant ); console.log('delegated farm incentives', vaultOverview.delegatedFarmIncentives); console.log('reserves farm incentives', vaultOverview.reservesFarmsIncentives); console.log('vault farm incentives', vaultOverview.vaultFarmIncentives); ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-07-get-vault-advanced-info-incentives-example/index.ts) **Step 7** ### Vault Revenue Share Earn revenue by deploying vaults with custom fee structures. Set performance fees on profits and management fees on assets under management. ```typescript icon="typescript" vaultRevenueShare theme={"theme":"css-variables"} import { address, generateKeyPairSigner } from '@solana/kit'; import { KaminoVaultConfig } from '@kamino-finance/klend-sdk'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { Decimal } from 'decimal.js'; const adminSigner = await generateKeyPairSigner(); const tokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: tokenMint, tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(10.0), // 10% performance fee on profits managementFeeRatePercentage: new Decimal(1.0), // 1% annual management fee on AUM name: 'Revenue Share Vault', vaultTokenSymbol: 'kUSDC', vaultTokenName: 'kUSDC receipt', }); ``` [View Code](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) # Earn Vaults Source: https://docs.kamino.com/build/developers/earn/index Learn how to build with Earn ## Overview Integrating Kamino's Earn vaults lets users supply tokens to curated lending strategies on Solana. Deposits are routed to lending markets according to the vault configuration, and interest from borrowers becomes yield for depositors. On deposit, users receive share tokens representing their position. If the vault has a farm attached, shares are automatically staked in the farm and are not visible in the user's wallet. If the vault has no farm, shares remain in the user's wallet. ## Key Components of Earn Integration > [card] Vault Operations > > Deposit, withdraw, and track user positions in the Lend program. > [card] Yield Tracking > > Read APY and performance from the public API or on-chain accounts, present recent and longer windows. ## Ways to Fetch Data > [card] Public API > > Simplest source for vault lists, APY, TVL, status. > [card] SDK > > Helpers to deposit, withdraw, and read user positions. ### Deposit > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoManager, KaminoVault, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault(rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), slotDuration); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > > // Deposit 100 USDC > const { depositIxs, stakeInFarmIfNeededIxs } = await vault.depositIxs( > user, // TransactionSigner (multisig cannot sign directly) > new Decimal(100.0), // amount in tokens > vaultReservesMap, > farmState, > null > ); > > console.log('Deposit Instructions:', [...depositIxs, ...stakeInFarmIfNeededIxs]); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-04-user-deposit-example/index.ts) > [tab] Rust > > ```rust expandable theme={"theme":"css-variables"} > use kvault_interface::{ > from_account_data, helpers, pda, state::VaultState, ReserveInfo, VaultInfo, KVAULT_PROGRAM_ID, > }; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use spl_associated_token_account::get_associated_token_address; > > let rpc = RpcClient::new("https://api.mainnet-beta.solana.com".to_string()); > let vault_pubkey: Pubkey = "HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E".parse().unwrap(); > > // Load the vault + its active reserves (their lending markets are needed to refresh klend on-chain) > let vault_data = rpc.get_account(&vault_pubkey).unwrap(); > let vault_state = from_account_data::(&vault_data.data).unwrap(); > let mut reserve_infos = Vec::new(); > for reserve in VaultInfo::active_reserve_addresses(vault_state) { > let acc = rpc.get_account(&reserve).unwrap(); > reserve_infos.push(ReserveInfo::from_account_data(reserve, &acc.data).unwrap()); > } > let vault = VaultInfo::from_account_data(vault_pubkey, &vault_data.data, &reserve_infos).unwrap(); > > // Derive the user's token + shares ATAs > let user_token_ata = get_associated_token_address(&owner, &vault.token_mint); > let (shares_mint, _) = pda::shares_mint(&KVAULT_PROGRAM_ID, &vault_pubkey); > let user_shares_ata = get_associated_token_address(&owner, &shares_mint); > > // Build a deposit instruction for 1 USDC — PDAs + remaining accounts are derived for you > let deposit_ix = > helpers::deposit::deposit(&vault, owner, user_token_ata, user_shares_ata, 1_000_000); > ``` > [!NOTE] > > For the full deposit example, including transaction sending and confirmation, check out [Deposit Operations](/build/developers/earn/operations/deposit). ### Withdraw > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault(rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), slotDuration); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > > // Withdraw 1.5 shares > const { unstakeFromFarmIfNeededIxs, withdrawIxs, postWithdrawIxs } = await vault.withdrawIxs( > user, // TransactionSigner (multisig cannot sign directly) > new Decimal(1.5), // shares to withdraw > await getCurrentLedgerInstant(rpc), > vaultReservesMap, > farmState, > null > ); > > console.log('Withdraw Instructions:', [...unstakeFromFarmIfNeededIxs, ...withdrawIxs, ...postWithdrawIxs]); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-05-user-withdraw-example/index.ts) > [tab] Rust > > ```rust expandable theme={"theme":"css-variables"} > use kvault_interface::{ > from_account_data, helpers, pda, state::VaultState, ReserveInfo, VaultInfo, KVAULT_PROGRAM_ID, > }; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use spl_associated_token_account::get_associated_token_address; > > let rpc = RpcClient::new("https://api.mainnet-beta.solana.com".to_string()); > let vault_pubkey: Pubkey = "HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E".parse().unwrap(); > let reserve_pubkey: Pubkey = "D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59".parse().unwrap(); > > // Load the vault, the disinvest-target reserve, and every active reserve > let vault_data = rpc.get_account(&vault_pubkey).unwrap(); > let reserve_data = rpc.get_account(&reserve_pubkey).unwrap(); > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data).unwrap(); > let vault_state = from_account_data::(&vault_data.data).unwrap(); > let mut reserve_infos = Vec::new(); > for r in VaultInfo::active_reserve_addresses(vault_state) { > let acc = rpc.get_account(&r).unwrap(); > reserve_infos.push(ReserveInfo::from_account_data(r, &acc.data).unwrap()); > } > let vault = VaultInfo::from_account_data(vault_pubkey, &vault_data.data, &reserve_infos).unwrap(); > > let user_token_ata = get_associated_token_address(&owner, &vault.token_mint); > let (shares_mint, _) = pda::shares_mint(&KVAULT_PROGRAM_ID, &vault_pubkey); > let user_shares_ata = get_associated_token_address(&owner, &shares_mint); > > // Burn 1.5 shares (raw units) — disinvests from the reserve if available liquidity is low > let withdraw_ix = > helpers::withdraw::withdraw(&vault, owner, user_token_ata, user_shares_ata, &reserve, 1_500_000); > ``` > [!NOTE] > > For the full withdraw example, including transaction sending and confirmation, check out [Withdraw Operations](/build/developers/earn/operations/withdraw). ## Key Data Structures > [tab] TypeScript > > ##### VaultState > > ```typescript theme={"theme":"css-variables"} > class VaultState { > tokenMint: Address > tokenVault: Address > sharesMint: Address > tokenAvailable: BN > sharesIssued: BN > performanceFeeBps: BN > managementFeeBps: BN > vaultAllocationStrategy: Array > unallocatedTokensCap: BN > unallocatedWeight: BN > minDepositAmount: BN > withdrawalPenaltyLamports: BN > withdrawalPenaltyBps: BN > cumulativeEarnedInterestSf: BN > cumulativeMgmtFeesSf: BN > cumulativePerfFeesSf: BN > name: Array > vaultFarm: Address > creationTimestamp: BN > allowAllocationsInWhitelistedReservesOnly: Boolean > allowInvestInWhitelistedReservesOnly: Boolean > } > ``` > > [View Full TypeScript VaultState](https://github.com/Kamino-Finance/klend-sdk/blob/636ccc98fd3aacfb49ed5d9d5f74ba527a9c75f9/src/%40codegen/kvault/accounts/VaultState.ts#L96) > > **Fields** > > | Field | Type | Description | > | - | - | - | > | `tokenMint` | `Address` | SPL token mint address that this vault accepts | > | `tokenVault` | `Address` | Vault's token account holding deposited assets | > | `sharesMint` | `Address` | Mint address for vault share tokens | > | `tokenAvailable` | `BN` | Amount of tokens available in the vault (lamports) | > | `sharesIssued` | `BN` | Total number of vault shares issued to depositors (lamports) | > | `performanceFeeBps` | `BN` | Performance fee in basis points (100 = 1%) | > | `managementFeeBps` | `BN` | Management fee in basis points | > | `vaultAllocationStrategy` | `Array` | Array of allocation strategies across reserves | > | `unallocatedTokensCap` | `BN` | Maximum unallocated token amount (lamports) | > | `unallocatedWeight` | `BN` | Relative weight for unallocated funds | > | `minDepositAmount` | `BN` | Minimum deposit amount per transaction (lamports) | > | `withdrawalPenaltyLamports` | `BN` | Absolute withdrawal penalty | > | `withdrawalPenaltyBps` | `BN` | Percentage withdrawal penalty | > | `cumulativeEarnedInterestSf` | `BN` | Cumulative earned interest (scaled fraction) | > | `cumulativeMgmtFeesSf` | `BN` | Cumulative management fees (scaled fraction) | > | `cumulativePerfFeesSf` | `BN` | Cumulative performance fees (scaled fraction) | > | `name` | `Array` | Vault name as byte array | > | `vaultFarm` | `Address` | Associated farm address for rewards | > | `creationTimestamp` | `BN` | Unix timestamp of vault creation | > | `allowAllocationsInWhitelistedReservesOnly` | `Boolean` | Restrict allocations to verified reserves | > | `allowInvestInWhitelistedReservesOnly` | `Boolean` | Restrict investments to verified reserves | > > **VaultAllocation Structure** > > \ > VaultAllocation > > ```typescript theme={"theme":"css-variables"} > class VaultAllocation { > reserve: Address > ctokenVault: Address > targetAllocationWeight: BN > tokenAllocationCap: BN > ctokenAllocation: BN > reserveType: number > priority: number > lastInvestSlot: BN > tokenTargetAllocationSf: BN > } > ``` > > [View Full TypeScript VaultAllocation](https://github.com/Kamino-Finance/klend-sdk/blob/636ccc98fd3aacfb49ed5d9d5f74ba527a9c75f9/src/%40codegen/kvault/types/VaultAllocation.ts#L35) > > | Field | Type | Description | > | - | - | - | > | `reserve` | `Address` | Lending reserve address where funds are allocated | > | `ctokenVault` | `Address` | Vault's cToken account for this reserve | > | `targetAllocationWeight` | `BN` | Relative integer weight for this allocation | > | `tokenAllocationCap` | `BN` | Maximum tokens that can be allocated to this reserve | > | `ctokenAllocation` | `BN` | Current amount of cTokens held in this allocation | > | `reserveType` | `number` | `standard` or `conditional` (as number); Allocation behavior (see Reserve Types) | > | `priority` | `number` | Priority ordering for conditional investments (see Reserve Types) | > | `lastInvestSlot` | `BN` | Last slot when funds were invested in this reserve | > | `tokenTargetAllocationSf` | `BN` | Target allocation amount (scaled fraction) | > [tab] JSON > > ##### VaultState > > ```json theme={"theme":"css-variables"} > { > "tokenMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", > "tokenVault": "...", > "sharesMint": "...", > "tokenAvailable": "1000000000000", > "sharesIssued": "950000000000", > "performanceFeeBps": "1500", > "managementFeeBps": "200", > "vaultAllocationStrategy": [], > "unallocatedTokensCap": "0", > "unallocatedWeight": "0", > "minDepositAmount": "0", > "withdrawalPenaltyLamports": "0", > "withdrawalPenaltyBps": "0", > "cumulativeEarnedInterestSf": "0", > "cumulativeMgmtFeesSf": "0", > "cumulativePerfFeesSf": "0", > "name": [99, 108, 105, 102, 102, 111, 114, 100], > "vaultFarm": "...", > "creationTimestamp": "1234567890", > "allowAllocationsInWhitelistedReservesOnly": false, > "allowInvestInWhitelistedReservesOnly": false > } > ``` > > [View Full VaultStateJSON](https://github.com/Kamino-Finance/klend-sdk/blob/636ccc98fd3aacfb49ed5d9d5f74ba527a9c75f9/src/%40codegen/kvault/accounts/VaultState.ts#L57C1-L94C2) > > **Fields** > > | Field | Type | Description | > | - | - | - | > | `tokenMint` | `string` | SPL token mint address that this vault accepts | > | `tokenVault` | `string` | Vault's token account holding deposited assets | > | `sharesMint` | `string` | Mint address for vault share tokens | > | `tokenAvailable` | `string` | Amount of tokens available in the vault | > | `sharesIssued` | `string` | Total number of vault shares issued to depositors | > | `performanceFeeBps` | `string` | Performance fee in basis points (100 = 1%) | > | `managementFeeBps` | `string` | Management fee in basis points | > | `vaultAllocationStrategy` | `array` | Array of allocation strategies across reserves | > | `unallocatedTokensCap` | `string` | Maximum unallocated token amount (lamports) | > | `unallocatedWeight` | `string` | Relative weight for unallocated funds | > | `minDepositAmount` | `string` | Minimum deposit amount per transaction (lamports) | > | `withdrawalPenaltyLamports` | `string` | Absolute withdrawal penalty | > | `withdrawalPenaltyBps` | `string` | Percentage withdrawal penalty | > | `cumulativeEarnedInterestSf` | `string` | Cumulative earned interest (scaled fraction) | > | `cumulativeMgmtFeesSf` | `string` | Cumulative management fees (scaled fraction) | > | `cumulativePerfFeesSf` | `string` | Cumulative performance fees (scaled fraction) | > | `name` | `array` | Vault name as byte array | > | `vaultFarm` | `string` | Associated farm address for rewards | > | `creationTimestamp` | `string` | Unix timestamp of vault creation | > | `allowAllocationsInWhitelistedReservesOnly` | `boolean` | Restrict allocations to verified reserves | > | `allowInvestInWhitelistedReservesOnly` | `boolean` | Restrict investments to verified reserves | > > **VaultAllocation Structure** > > \ > VaultAllocationJSON > > ```json theme={"theme":"css-variables"} > { > "reserve": "...", > "ctokenVault": "...", > "targetAllocationWeight": "100", > "tokenAllocationCap": "1000000000", > "ctokenAllocation": "500000000", > "reserveType": 0, > "priority": 0, > "lastInvestSlot": "123456789", > "tokenTargetAllocationSf": "0" > } > ``` > > [View Full VaultAllocationJSON](https://github.com/Kamino-Finance/klend-sdk/blob/636ccc98fd3aacfb49ed5d9d5f74ba527a9c75f9/src/%40codegen/kvault/types/VaultAllocation.ts#L21C1-L33C2) > > | Field | Type | Description | > | - | - | - | > | `reserve` | `string` | Lending reserve address where funds are allocated | > | `ctokenVault` | `string` | Vault's cToken account for this reserve | > | `targetAllocationWeight` | `string` | Relative integer weight for this allocation | > | `tokenAllocationCap` | `string` | Maximum tokens that can be allocated to this reserve | > | `ctokenAllocation` | `string` | Current amount of cTokens held in this allocation | > | `reserveType` | `number` | `0` = standard, `1` = conditional; allocation behavior (see Reserve Types) | > | `priority` | `number` | Priority ordering for conditional investments (see Reserve Types) | > | `lastInvestSlot` | `string` | Last slot when funds were invested in this reserve | > | `tokenTargetAllocationSf` | `string` | Target allocation amount (scaled fraction) | > [tab] Rust > > ##### VaultState > > ```rust theme={"theme":"css-variables"} > pub struct VaultState { > pub token_mint: Pubkey > pub token_vault: Pubkey > pub shares_mint: Pubkey > pub token_available: u64 > pub shares_issued: u64 > pub performance_fee_bps: u64 > pub management_fee_bps: u64 > pub vault_allocation_strategy: [VaultAllocation; MAX_RESERVES] > pub unallocated_tokens_cap: u64 > pub unallocated_weight: u64 > pub min_deposit_amount: u64 > pub withdrawal_penalty_lamports: u64 > pub withdrawal_penalty_bps: u64 > pub cumulative_earned_interest_sf: u128 > pub cumulative_mgmt_fees_sf: u128 > pub cumulative_perf_fees_sf: u128 > pub name: [u8; 40] > pub vault_farm: Pubkey > pub creation_timestamp: u64 > pub allow_allocations_in_whitelisted_reserves_only: bool > pub allow_invest_in_whitelisted_reserves_only: bool > } > ``` > > [View Full Rust VaultState](https://github.com/Kamino-Finance/kvault/blob/0321f6287d236b8286495ff7b7a410fcb93f0599/programs/kvault/src/state.rs#L17) > > **Fields** > > | Field | Type | Description | > | - | - | - | > | `token_mint` | `Pubkey` | SPL token mint address that this vault accepts | > | `token_vault` | `Pubkey` | Vault's token account holding deposited assets | > | `shares_mint` | `Pubkey` | Mint address for vault share tokens | > | `token_available` | `u64` | Amount of tokens available in the vault | > | `shares_issued` | `u64` | Total number of vault shares issued to depositors | > | `performance_fee_bps` | `u64` | Performance fee in basis points (100 = 1%) | > | `management_fee_bps` | `u64` | Management fee in basis points | > | `vault_allocation_strategy` | `[VaultAllocation; MAX_RESERVES]` | Fixed array of allocation strategies across reserves (MAX_RESERVES = 25) | > | `unallocated_tokens_cap` | `u64` | Maximum unallocated token amount (lamports) | > | `unallocated_weight` | `u64` | Relative weight for unallocated funds | > | `min_deposit_amount` | `u64` | Minimum deposit amount per transaction (lamports) | > | `withdrawal_penalty_lamports` | `u64` | Absolute withdrawal penalty | > | `withdrawal_penalty_bps` | `u64` | Percentage withdrawal penalty | > | `cumulative_earned_interest_sf` | `u128` | Cumulative earned interest (scaled fraction) | > | `cumulative_mgmt_fees_sf` | `u128` | Cumulative management fees (scaled fraction) | > | `cumulative_perf_fees_sf` | `u128` | Cumulative performance fees (scaled fraction) | > | `name` | `[u8; 40]` | Vault name as byte array | > | `vault_farm` | `Pubkey` | Associated farm address for rewards | > | `creation_timestamp` | `u64` | Unix timestamp of vault creation | > | `allow_allocations_in_whitelisted_reserves_only` | `bool` | Restrict allocations to verified reserves | > | `allow_invest_in_whitelisted_reserves_only` | `bool` | Restrict investments to verified reserves | > > **VaultAllocation Structure** > > \ > VaultAllocation > > ```rust theme={"theme":"css-variables"} > pub struct VaultAllocation { > pub reserve: Pubkey > pub ctoken_vault: Pubkey > pub target_allocation_weight: u64 > pub token_allocation_cap: u64 > pub ctoken_vault_bump: u64 > pub reserve_type: u8 > pub allocation_priority: u8 > pub ctoken_allocation: u64 > pub last_invest_slot: u64 > pub token_target_allocation_sf: u128 > } > ``` > > [View Full Rust VaultAllocation](https://github.com/Kamino-Finance/kvault/blob/0321f6287d236b8286495ff7b7a410fcb93f0599/programs/kvault/src/state.rs#L425) > > | Field | Type | Description | > | - | - | - | > | `reserve` | `Pubkey` | Lending reserve address where funds are allocated | > | `ctoken_vault` | `Pubkey` | Vault's cToken account for this reserve | > | `target_allocation_weight` | `u64` | Relative integer weight for this allocation | > | `token_allocation_cap` | `u64` | Maximum tokens that can be allocated to this reserve | > | `ctoken_vault_bump` | `u64` | PDA bump seed for the cToken vault | > | `reserve_type` | `u8` | `standard` or `conditional` (as number); Allocation behavior (see Reserve Types) | > | `allocation_priority` | `u8` | Priority ordering for conditional investments (see Reserve Types) | > | `ctoken_allocation` | `u64` | Current amount of cTokens held in this allocation | > | `last_invest_slot` | `u64` | Last slot when funds were invested in this reserve | > | `token_target_allocation_sf` | `u128` | Target allocation amount (scaled fraction) | ## Relevant Links > [card] [Fetch Vaults Data via the API](https://api-docs.kamino.com/) > > Access vault metrics and performance data through REST endpoints. > [card] [Smart contract repository](https://github.com/Kamino-Finance/klend) > > Explore the on-chain program source code and documentation. > [card] [NPM SDK package](https://www.npmjs.com/package/@kamino-finance/klend-sdk) > > Install the TypeScript SDK to integrate vault operations. > [card] [Rust Interface Crate](https://crates.io/crates/kvault-interface) > > Lightweight instruction builder for Rust bots and on-chain CPI. > [card] [More Earn tutorials](/build/tutorials/earn/index) > > Step-by-step guides for building with Kamino Earn vaults. # Deposit Source: https://docs.kamino.com/build/developers/earn/operations/deposit Deposit assets into Kamino Earn vaults Deposit assets into Kamino Earn vaults to start earning yield. The SDK handles transaction building, instruction creation, and vault interaction. ## Complete Flow Implement the full deposit flow either in an off-chain TypeScript client or via on-chain Rust CPI within your Anchor program. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > compressTransactionMessageUsingAddressLookupTables, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > type Address, > } from '@solana/kit'; > import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import { Decimal } from 'decimal.js'; > ``` > > > [!NOTE] > > > > `@solana/kit` provides modern utilities for RPC, transaction building, and signing. `@kamino-finance/klend-sdk` contains vault operation methods. > > **Step 2** > > ### Load Signer and Initialize RPC > > Load your keypair from a file and initialize RPC connections. > > ```typescript theme={"theme":"css-variables"} > 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'); > ``` > > > [!NOTE] > > > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. > > **Step 3** > > ### Load the Vault > > Initialize the vault and load its state, reserves, and farm state once. The deposit instructions need all three. > > ```typescript theme={"theme":"css-variables"} > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > ``` > > **Step 4** > > ### Set Slippage Protection > > Estimate the shares the deposit will mint, minus a slippage tolerance. The deposit reverts if fewer shares would be minted. > > ```typescript theme={"theme":"css-variables"} > const depositAmount = new Decimal(1.0); // 1 USDC > const minSharesOut = manager.estimateSharesFromTokens( > vaultState, > depositAmount, > await getCurrentLedgerInstant(rpc), > vaultReservesMap, > 10 // 0.1% slippage > ); > ``` > > > [!NOTE] > > > > The deposit amount is in tokens (`1.0` is 1 USDC), not lamports. > > **Step 5** > > ### Build Deposit Instructions > > Generate the deposit instructions, plus the instructions that stake the new shares in the vault's farm. > > ```typescript theme={"theme":"css-variables"} > const bundle = await vault.depositIxs( > signer, > depositAmount, > vaultReservesMap, > farmState, > null, // first-loss capital farm > undefined, // payer > undefined, // memo > minSharesOut > ); > const instructions = [...bundle.depositIxs, ...bundle.stakeInFarmIfNeededIxs]; > ``` > > > [!NOTE] > > > > If the vault has a rewards farm, `stakeInFarmIfNeededIxs` stakes the minted shares in it so the position earns farm rewards. Shares staked here are unstaked automatically when you withdraw. > > **Step 6** > > ### Load the Vault's Lookup Table > > Fetch the vault's address lookup table to keep the transaction small. > > ```typescript theme={"theme":"css-variables"} > const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); > const lutsByAddress: Record = {}; > for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; > ``` > > > [!NOTE] > > > > Every vault has its own lookup table. Compressing with it cuts the deposit from about 1,021 to 528 bytes, well under Solana's 1,232-byte transaction limit. > > **Step 7** > > ### Build and Sign Transaction > > Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. > > ```typescript theme={"theme":"css-variables"} > 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); > ``` > > **Step 8** > > ### Send and Confirm Transaction > > Send the deposit transaction and wait for confirmation. > > ```typescript theme={"theme":"css-variables"} > const signature = getSignatureFromTransaction(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Deposit successful! Signature:', signature); > ``` > > > [!TIP] > > > > 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. > [tab] Rust > > > [!NOTE] > > > > A standalone off-chain Rust client that deposits into a Kamino Vault using the [`kvault-interface`](https://crates.io/crates/kvault-interface) crate. The crate's `helpers` build the instruction for you — deriving every PDA and the per-reserve `remaining_accounts` from the on-chain vault state — so you never hand-assemble account lists or discriminators. > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > kvault-interface = "0.1.0" > solana-client = "2.3" > solana-sdk = "2.3" > solana-pubkey = "2.1" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `kvault-interface` re-exports `ReserveInfo`, `VaultInfo`, `Fraction`, and the program IDs, so you don't need to depend on `klend-interface` directly for client code. > > **Step 2** > > ### Set Up RPC Client and Wallet > > Load the Solana CLI wallet from `~/.config/solana/id.json` and create an RPC client. > > ```rust theme={"theme":"css-variables"} > use std::str::FromStr; > > use kvault_interface::{ > from_account_data, helpers, pda, state::VaultState, ReserveInfo, VaultInfo, KVAULT_PROGRAM_ID, > }; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use solana_sdk::signer::{keypair::read_keypair_file, Signer}; > use spl_associated_token_account::get_associated_token_address; > > let rpc = RpcClient::new("https://api.mainnet-beta.solana.com".to_string()); > > let home = std::env::var("HOME").unwrap(); > let signer = read_keypair_file(format!("{home}/.config/solana/id.json")) > .expect("Failed to load wallet from ~/.config/solana/id.json"); > let owner = signer.pubkey(); > ``` > > > [!NOTE] > > > > The wallet needs at least \~0.01 SOL (transaction fees + ATA rent) and enough USDC to cover the deposit amount configured below. > > **Step 3** > > ### Fetch Vault and Reserve Data > > Load the vault account, then fetch every reserve the vault actively allocates to. The on-chain refresh that runs inside `deposit` needs each reserve **and** its lending market, so `VaultInfo` collects them up front. > > ```rust theme={"theme":"css-variables"} > // Steakhouse USDC vault > let vault_pubkey = Pubkey::from_str("HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E").unwrap(); > > let vault_data = rpc.get_account(&vault_pubkey).unwrap(); > > let vault_state = from_account_data::(&vault_data.data).unwrap(); > let mut reserve_infos = Vec::new(); > for reserve_pubkey in VaultInfo::active_reserve_addresses(vault_state) { > let reserve_data = rpc.get_account(&reserve_pubkey).unwrap(); > reserve_infos.push(ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data).unwrap()); > } > > let vault = VaultInfo::from_account_data(vault_pubkey, &vault_data.data, &reserve_infos).unwrap(); > ``` > > **Step 4** > > ### Derive User Token Accounts > > Compute the user's ATA for the underlying token (USDC) and for the vault shares mint. The shares mint is a PDA of the vault state, derived with `pda::shares_mint`. > > ```rust theme={"theme":"css-variables"} > let user_token_ata = get_associated_token_address(&owner, &vault.token_mint); > > let (shares_mint, _bump) = pda::shares_mint(&KVAULT_PROGRAM_ID, &vault_pubkey); > let user_shares_ata = get_associated_token_address(&owner, &shares_mint); > ``` > > > [!NOTE] > > > > Create these ATAs with `spl_associated_token_account::instruction::create_associated_token_account_idempotent` if they may not exist yet, and prepend those instructions to the transaction below. > > **Step 5** > > ### Build the Deposit Instruction > > `helpers::deposit::deposit` returns a single instruction with the PDAs and per-reserve `remaining_accounts` already derived from `VaultInfo`. > > ```rust theme={"theme":"css-variables"} > let ix = helpers::deposit::deposit( > &vault, > owner, > user_token_ata, // source: user's token account > user_shares_ata, // destination: user's shares account > 1_000_000, // 1 USDC (6 decimals) > ); > ``` > > **Step 6** > > ### Send the Deposit Transaction > > ```rust theme={"theme":"css-variables"} > let message = solana_sdk::message::Message::new(&[ix], Some(&owner)); > let recent_blockhash = rpc.get_latest_blockhash().unwrap(); > let tx = solana_sdk::transaction::Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc.send_and_confirm_transaction(&tx).unwrap(); > println!("Deposit successful! Signature: {signature}"); > ``` > > > [!NOTE] > > > > Depositing only mints shares to your share ATA. If the vault has a share farm (`VaultState::vault_farm` is set), you must also **stake** those shares into the farm to earn vault-level rewards — staking is a separate Kamino Farms instruction, appended after this deposit. > > > [!TIP] > > > > The deposit is complete. Your USDC has been transferred to the vault, and you've received kVUSDC shares redeemable at the current share price. > > [View Code](https://github.com/Kamino-Finance/kvault/blob/master/libs/kvault-interface/examples/deposit.rs) > [tab] Rust (CPI) > > > [!NOTE] > > > > This example shows how an **on-chain Anchor program** can CPI into a Kamino Vault to deposit assets, using the [`kvault-interface`](https://crates.io/crates/kvault-interface) `instructions` builders. A PDA authority owns the user token and shares accounts and signs the CPI via `invoke_signed` — the builder assembles the discriminator and account metas, so you never hand-roll them. > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > kvault-interface = "0.1.0" > anchor-lang = "0.31" > anchor-spl = "0.31" > solana-program = "2.1" > ``` > > > [!NOTE] > > > > Use Anchor **0.31+** here: `kvault-interface` is built on the Solana 2.x crates (`solana-pubkey`/`solana-instruction`), and Anchor 0.31 is the first release on that line — so its `Pubkey` type matches the crate's. Older Anchor (0.30) pulls Solana 1.x and won't type-check against the builders. > > **Step 2** > > ### Define Program IDs, PDA Authority, and Handler > > ```rust theme={"theme":"css-variables"} > use anchor_lang::prelude::*; > use anchor_lang::solana_program::instruction::AccountMeta; > use anchor_spl::token::{Token, TokenAccount}; > use kvault_interface::instructions::deposit::{deposit, DepositAccounts}; > > declare_id!("YourProgram1111111111111111111111111111111111"); > > const AUTHORITY_SEED: &[u8] = b"vault_authority"; > > // Mainnet program IDs — see accordion below for devnet equivalents > pub const KVAULT_PROGRAM_ID: Pubkey = pubkey!("KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd"); > pub const KLEND_PROGRAM_ID: Pubkey = pubkey!("KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD"); > > #[program] > pub mod vault_deposit { > use super::*; > > pub fn deposit_into_vault<'info>( > ctx: Context<'_, '_, '_, 'info, Deposit<'info>>, > max_amount: u64, > ) -> Result<()> { > let vault_state_key = ctx.accounts.vault_state.key(); > let authority_seeds: &[&[u8]] = &[ > AUTHORITY_SEED, > vault_state_key.as_ref(), > &[ctx.bumps.authority], > ]; > ``` > > > [accordion] Mainnet Program IDs > > > > | Constant | Address | > > | - | - | > > | `KVAULT_PROGRAM_ID` | `KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd` | > > | `KLEND_PROGRAM_ID` | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | > > > [accordion] Devnet Program IDs > > > > | Constant | Address | > > | - | - | > > | `KVAULT_PROGRAM_ID` | `devkRngFnfp4gBc5a3LsadgbQKdPo8MSZ4prFiNSVmY` | > > | `KLEND_PROGRAM_ID` | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | > > **Step 3** > > ### Forward the Refresh Accounts > > Klend reserve allocations live in `remaining_accounts` — writable reserve metas followed by readonly lending-market metas, in allocation-slot order. Forward them to the builder unchanged. > > ```rust theme={"theme":"css-variables"} > let remaining_metas: Vec = ctx > .remaining_accounts > .iter() > .map(|a| AccountMeta { > pubkey: *a.key, > is_signer: a.is_signer, > is_writable: a.is_writable, > }) > .collect(); > ``` > > **Step 4** > > ### Build the Deposit Instruction > > `deposit` takes a `DepositAccounts` struct, the `max_amount`, and the refresh list. It derives the event-authority PDA and packs the discriminator + args for you. > > ```rust theme={"theme":"css-variables"} > let ix = deposit( > DepositAccounts { > user: ctx.accounts.authority.key(), > vault_state: ctx.accounts.vault_state.key(), > token_vault: ctx.accounts.token_vault.key(), > token_mint: ctx.accounts.token_mint.key(), > base_vault_authority: ctx.accounts.base_vault_authority.key(), > shares_mint: ctx.accounts.shares_mint.key(), > user_token_ata: ctx.accounts.user_token_ata.key(), > user_shares_ata: ctx.accounts.user_shares_ata.key(), > klend_program: ctx.accounts.klend_program.key(), > token_program: ctx.accounts.token_program.key(), > shares_token_program: ctx.accounts.shares_token_program.key(), > }, > max_amount, > remaining_metas, > ); > ``` > > **Step 5** > > ### Invoke Signed with the PDA > > The `AccountInfo`s are supplied in the order the builder emits metas — the 11 named accounts, then the event-authority and kvault program (appended by the builder), then the forwarded `remaining_accounts`. > > ```rust theme={"theme":"css-variables"} > let mut account_infos = vec![ > ctx.accounts.authority.to_account_info(), > ctx.accounts.vault_state.to_account_info(), > ctx.accounts.token_vault.to_account_info(), > ctx.accounts.token_mint.to_account_info(), > ctx.accounts.base_vault_authority.to_account_info(), > ctx.accounts.shares_mint.to_account_info(), > ctx.accounts.user_token_ata.to_account_info(), > ctx.accounts.user_shares_ata.to_account_info(), > ctx.accounts.klend_program.to_account_info(), > ctx.accounts.token_program.to_account_info(), > ctx.accounts.shares_token_program.to_account_info(), > ctx.accounts.event_authority.to_account_info(), > ctx.accounts.kvault_program.to_account_info(), > ]; > account_infos.extend(ctx.remaining_accounts.iter().cloned()); > > solana_program::program::invoke_signed(&ix, &account_infos, &[authority_seeds])?; > Ok(()) > } > } > ``` > > **Step 6** > > ### Account Validation Struct > > ```rust expandable title="Deposit accounts" theme={"theme":"css-variables"} > #[derive(Accounts)] > pub struct Deposit<'info> { > #[account( > mut, > seeds = [AUTHORITY_SEED, vault_state.key().as_ref()], > bump, > )] > pub authority: SystemAccount<'info>, > > #[account(mut, token::authority = authority)] > pub user_token_ata: Account<'info, TokenAccount>, > > #[account(mut, token::authority = authority)] > pub user_shares_ata: Account<'info, TokenAccount>, > > /// CHECK: Kvault state account. > #[account(mut)] > pub vault_state: UncheckedAccount<'info>, > /// CHECK: Token vault owned by the Kvault program. > #[account(mut)] > pub token_vault: UncheckedAccount<'info>, > /// CHECK: Underlying token mint. > pub token_mint: UncheckedAccount<'info>, > /// CHECK: Kvault base vault authority PDA. > pub base_vault_authority: UncheckedAccount<'info>, > /// CHECK: Shares mint. > #[account(mut)] > pub shares_mint: UncheckedAccount<'info>, > /// CHECK: Event-emit PDA owned by the Kvault program. > pub event_authority: UncheckedAccount<'info>, > > /// CHECK: The Kvault program. > #[account(address = KVAULT_PROGRAM_ID)] > pub kvault_program: UncheckedAccount<'info>, > /// CHECK: The Klend program. > #[account(address = KLEND_PROGRAM_ID)] > pub klend_program: UncheckedAccount<'info>, > pub token_program: Program<'info, Token>, > pub shares_token_program: Program<'info, Token>, > } > ``` > > [View API](https://docs.rs/kvault-interface/latest/kvault_interface/instructions/index.html) #### Full Code Example > [tab] TypeScript > > ```typescript expandable theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > compressTransactionMessageUsingAddressLookupTables, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > type Address, > } from '@solana/kit'; > import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import { Decimal } from 'decimal.js'; > > 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 slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > > const depositAmount = new Decimal(1.0); // 1 USDC > const minSharesOut = manager.estimateSharesFromTokens( > vaultState, > depositAmount, > await getCurrentLedgerInstant(rpc), > vaultReservesMap, > 10 // 0.1% slippage > ); > > const bundle = await vault.depositIxs( > signer, > depositAmount, > vaultReservesMap, > farmState, > null, // first-loss capital farm > undefined, // payer > undefined, // memo > minSharesOut > ); > const instructions = [...bundle.depositIxs, ...bundle.stakeInFarmIfNeededIxs]; > > const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); > const lutsByAddress: Record = {}; > for (const lut of lookupTables) lutsByAddress[lut.address] = lut.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('Deposit successful! Signature:', signature); > ``` # Withdraw Source: https://docs.kamino.com/build/developers/earn/operations/withdraw Withdraw assets from Kamino Earn vaults Withdraw assets from Kamino Earn vaults to redeem your shares for underlying tokens. The SDK handles transaction building and vault interaction. ## Complete Flow Implement the full withdrawal flow either in an off-chain TypeScript client or via on-chain Rust CPI within your Anchor program. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > compressTransactionMessageUsingAddressLookupTables, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > type Address, > } from '@solana/kit'; > import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import { Decimal } from 'decimal.js'; > ``` > > > [!NOTE] > > > > `@solana/kit` provides modern utilities for RPC, transaction building, and signing. `@kamino-finance/klend-sdk` contains vault operation methods. > > **Step 2** > > ### Load Signer and Initialize RPC > > Load your keypair from a file and initialize RPC connections. > > ```typescript theme={"theme":"css-variables"} > 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'); > ``` > > > [!NOTE] > > > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. > > **Step 3** > > ### Load the Vault > > Initialize the vault and load its state, reserves, and farm state once. The withdraw instructions need all three. > > ```typescript theme={"theme":"css-variables"} > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > ``` > > **Step 4** > > ### Convert Tokens to Shares > > Convert the token amount you want back into vault shares, capped at the shares you hold. > > ```typescript theme={"theme":"css-variables"} > const withdrawAmount = new Decimal(1.0); // 1 USDC > > const userShares = await vault.getUserShares(signer.address); > const tokensPerShare = await manager.getTokensPerShareSingleVault(vault, ledgerInstant, vaultReservesMap, ledgerInstant); > const sharesToWithdraw = Decimal.min(withdrawAmount.div(tokensPerShare), userShares.totalShares); > ``` > > > [!NOTE] > > > > `withdrawIxs` takes an amount of **vault shares**, not tokens. Shares grow in value as interest accrues, so one share is worth more than one token. To withdraw everything, pass `userShares.totalShares`. > > **Step 5** > > ### Build Withdraw Instructions > > Generate the unstake and withdraw instructions. > > ```typescript theme={"theme":"css-variables"} > const bundle = await vault.withdrawIxs( > signer, > sharesToWithdraw, > ledgerInstant, > vaultReservesMap, > farmState, > null // first-loss capital farm > ); > const instructions = [...bundle.unstakeFromFarmIfNeededIxs, ...bundle.withdrawIxs, ...bundle.postWithdrawIxs]; > ``` > > > [!NOTE] > > > > Deposits stake shares in the vault's farm, so `unstakeFromFarmIfNeededIxs` must come before `withdrawIxs`. Without it, withdrawing staked shares fails with `CannotWithdrawZeroShares`. > > **Step 6** > > ### Load the Vault's Lookup Table > > Fetch the vault's address lookup table to keep the transaction small. > > ```typescript theme={"theme":"css-variables"} > const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); > const lutsByAddress: Record = {}; > for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; > ``` > > > [!NOTE] > > > > Some vaults need the lookup table for a withdraw to fit in one transaction. Without it, a withdraw from one vault we tested was 1,274 bytes, over Solana's 1,232-byte limit. > > **Step 7** > > ### Build and Sign Transaction > > Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. > > ```typescript theme={"theme":"css-variables"} > 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); > ``` > > **Step 8** > > ### Send and Confirm Transaction > > Send the withdraw transaction and wait for confirmation. > > ```typescript theme={"theme":"css-variables"} > const signature = getSignatureFromTransaction(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Withdraw successful! Signature:', signature); > ``` > > > [!TIP] > > > > Once the withdraw transaction is confirmed, your vault shares are burned and you receive the underlying tokens plus any accrued interest. > [tab] Rust > > > [!NOTE] > > > > A standalone off-chain Rust client that burns vault shares to redeem the underlying tokens, using the [`kvault-interface`](https://crates.io/crates/kvault-interface) crate. If the vault's available balance is too low, `withdraw` automatically disinvests from a Klend reserve — the helper assembles every account needed for that path. Uses the same `Cargo.toml` and wallet setup as the [deposit client](#). > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > kvault-interface = "0.1.0" > solana-client = "2.3" > solana-sdk = "2.3" > solana-pubkey = "2.1" > spl-associated-token-account = "6" > ``` > > **Step 2** > > ### Set Up RPC Client and Wallet > > ```rust theme={"theme":"css-variables"} > use std::str::FromStr; > > use kvault_interface::{ > from_account_data, helpers, pda, state::VaultState, ReserveInfo, VaultInfo, KVAULT_PROGRAM_ID, > }; > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use solana_sdk::signer::{keypair::read_keypair_file, Signer}; > use spl_associated_token_account::get_associated_token_address; > > let rpc = RpcClient::new("https://api.mainnet-beta.solana.com".to_string()); > > let home = std::env::var("HOME").unwrap(); > let signer = read_keypair_file(format!("{home}/.config/solana/id.json")) > .expect("Failed to load wallet from ~/.config/solana/id.json"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Fetch Vault and Reserve Data > > Load the vault and the reserve to disinvest from, plus every active reserve (each with its lending market) so the on-chain refresh has everything it needs. The disinvest target is reused from the set already fetched. > > ```rust theme={"theme":"css-variables"} > let vault_pubkey = Pubkey::from_str("HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E").unwrap(); > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > let vault_data = rpc.get_account(&vault_pubkey).unwrap(); > > let reserve_data = rpc.get_account(&reserve_pubkey).unwrap(); > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data).unwrap(); > > let vault_state = from_account_data::(&vault_data.data).unwrap(); > let mut reserve_infos = Vec::new(); > for active_reserve in VaultInfo::active_reserve_addresses(vault_state) { > if active_reserve == reserve.address { > reserve_infos.push(ReserveInfo::from_account_data(reserve.address, &reserve_data.data).unwrap()); > } else { > let data = rpc.get_account(&active_reserve).unwrap(); > reserve_infos.push(ReserveInfo::from_account_data(active_reserve, &data.data).unwrap()); > } > } > > let vault = VaultInfo::from_account_data(vault_pubkey, &vault_data.data, &reserve_infos).unwrap(); > ``` > > **Step 4** > > ### Derive User Token Accounts > > ```rust theme={"theme":"css-variables"} > let user_token_ata = get_associated_token_address(&owner, &vault.token_mint); > > let (shares_mint, _bump) = pda::shares_mint(&KVAULT_PROGRAM_ID, &vault_pubkey); > let user_shares_ata = get_associated_token_address(&owner, &shares_mint); > ``` > > **Step 5** > > ### Build the Withdraw Instruction > > `helpers::withdraw::withdraw` takes the disinvest-target `ReserveInfo` and the number of shares to burn, and derives the rest. > > ```rust theme={"theme":"css-variables"} > let ix = helpers::withdraw::withdraw( > &vault, > owner, > user_token_ata, > user_shares_ata, > &reserve, > 1_000_000, // shares to burn > ); > ``` > > **Step 6** > > ### Send the Withdraw Transaction > > ```rust theme={"theme":"css-variables"} > let message = solana_sdk::message::Message::new(&[ix], Some(&owner)); > let recent_blockhash = rpc.get_latest_blockhash().unwrap(); > let tx = solana_sdk::transaction::Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc.send_and_confirm_transaction(&tx).unwrap(); > println!("Withdrawal successful! Signature: {signature}"); > ``` > > > [!NOTE] > > > > If the vault has a share farm (`VaultState::vault_farm` is set), your shares are staked in the farm and must be **unstaked first** — `withdraw` can only burn shares held in your share ATA. A complete flow prepends a Kamino Farms unstake instruction before the withdraw. > > > [!TIP] > > > > The withdrawal is complete. Your kVUSDC shares have been burned and the underlying USDC has been transferred to your wallet at the current share price. > > [View Code](https://github.com/Kamino-Finance/kvault/blob/master/libs/kvault-interface/examples/withdraw.rs) > [tab] Rust (CPI) > > > [!NOTE] > > > > This example shows how an **on-chain Anchor program** can CPI into a Kamino Vault to withdraw assets, using the [`kvault-interface`](https://crates.io/crates/kvault-interface) `instructions` builders. A PDA authority owns the user token and shares accounts and signs the CPI via `invoke_signed`. The `withdraw` builder flattens the "withdraw from available" and "withdraw from invested" account groups for you, so you don't hand-assemble the 25-account meta list. > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > kvault-interface = "0.1.0" > anchor-lang = "0.31" > anchor-spl = "0.31" > solana-program = "2.1" > ``` > > > [!NOTE] > > > > Use Anchor **0.31+** here: `kvault-interface` is built on the Solana 2.x crates (`solana-pubkey`/`solana-instruction`), and Anchor 0.31 is the first release on that line — so its `Pubkey` type matches the crate's. Older Anchor (0.30) pulls Solana 1.x and won't type-check against the builders. > > **Step 2** > > ### Define Program IDs, PDA Authority, and Handler > > ```rust theme={"theme":"css-variables"} > use anchor_lang::prelude::*; > use anchor_lang::solana_program::instruction::AccountMeta; > use anchor_spl::token::{Token, TokenAccount}; > use kvault_interface::instructions::withdraw::{withdraw, WithdrawAccounts}; > > declare_id!("YourProgram1111111111111111111111111111111111"); > > const AUTHORITY_SEED: &[u8] = b"vault_authority"; > > pub const KVAULT_PROGRAM_ID: Pubkey = pubkey!("KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd"); > pub const KLEND_PROGRAM_ID: Pubkey = pubkey!("KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD"); > > #[program] > pub mod vault_withdraw { > use super::*; > > pub fn withdraw_from_vault<'info>( > ctx: Context<'_, '_, '_, 'info, Withdraw<'info>>, > shares_amount: u64, > ) -> Result<()> { > let vault_state_key = ctx.accounts.vault_state.key(); > let authority_seeds: &[&[u8]] = &[ > AUTHORITY_SEED, > vault_state_key.as_ref(), > &[ctx.bumps.authority], > ]; > ``` > > > [accordion] Mainnet Program IDs > > > > | Constant | Address | > > | - | - | > > | `KVAULT_PROGRAM_ID` | `KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd` | > > | `KLEND_PROGRAM_ID` | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | > > > [accordion] Devnet Program IDs > > > > | Constant | Address | > > | - | - | > > | `KVAULT_PROGRAM_ID` | `devkRngFnfp4gBc5a3LsadgbQKdPo8MSZ4prFiNSVmY` | > > | `KLEND_PROGRAM_ID` | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | > > **Step 3** > > ### Forward the Refresh Accounts > > The refresh list — writable reserve metas followed by readonly lending-market metas, in allocation-slot order — is forwarded from `remaining_accounts` to the builder unchanged. > > ```rust theme={"theme":"css-variables"} > let remaining_metas: Vec = ctx > .remaining_accounts > .iter() > .map(|a| AccountMeta { > pubkey: *a.key, > is_signer: a.is_signer, > is_writable: a.is_writable, > }) > .collect(); > ``` > > **Step 4** > > ### Build the Withdraw Instruction > > `withdraw` takes a `WithdrawAccounts` struct covering both the available and invested phases, the `shares_amount` to burn, and the refresh list. Pass `u64::MAX` to burn the caller's entire balance. > > ```rust theme={"theme":"css-variables"} > let ix = withdraw( > WithdrawAccounts { > // withdraw-from-available > user: ctx.accounts.authority.key(), > vault_state: ctx.accounts.vault_state.key(), > global_config: ctx.accounts.global_config.key(), > token_vault: ctx.accounts.token_vault.key(), > base_vault_authority: ctx.accounts.base_vault_authority.key(), > user_token_ata: ctx.accounts.user_token_ata.key(), > token_mint: ctx.accounts.token_mint.key(), > user_shares_ata: ctx.accounts.user_shares_ata.key(), > shares_mint: ctx.accounts.shares_mint.key(), > token_program: ctx.accounts.token_program.key(), > shares_token_program: ctx.accounts.shares_token_program.key(), > klend_program: ctx.accounts.klend_program.key(), > // withdraw-from-invested (vault_state repeats) > invested_vault_state: ctx.accounts.vault_state.key(), > reserve: ctx.accounts.reserve.key(), > ctoken_vault: ctx.accounts.ctoken_vault.key(), > lending_market: ctx.accounts.lending_market.key(), > lending_market_authority: ctx.accounts.lending_market_authority.key(), > reserve_liquidity_supply: ctx.accounts.reserve_liquidity_supply.key(), > reserve_collateral_mint: ctx.accounts.reserve_collateral_mint.key(), > reserve_collateral_token_program: ctx.accounts.reserve_collateral_token_program.key(), > instruction_sysvar_account: ctx.accounts.instruction_sysvar_account.key(), > }, > shares_amount, > remaining_metas, > ); > ``` > > **Step 5** > > ### Invoke Signed with the PDA > > The `AccountInfo`s are supplied in the order the builder emits metas. `vault_state`, `event_authority`, and `kvault_program` each appear twice — once per account group — so they're repeated here too. > > ```rust theme={"theme":"css-variables"} > let mut account_infos = vec![ > // withdraw-from-available > ctx.accounts.authority.to_account_info(), > ctx.accounts.vault_state.to_account_info(), > ctx.accounts.global_config.to_account_info(), > ctx.accounts.token_vault.to_account_info(), > ctx.accounts.base_vault_authority.to_account_info(), > ctx.accounts.user_token_ata.to_account_info(), > ctx.accounts.token_mint.to_account_info(), > ctx.accounts.user_shares_ata.to_account_info(), > ctx.accounts.shares_mint.to_account_info(), > ctx.accounts.token_program.to_account_info(), > ctx.accounts.shares_token_program.to_account_info(), > ctx.accounts.klend_program.to_account_info(), > ctx.accounts.event_authority.to_account_info(), > ctx.accounts.kvault_program.to_account_info(), > // withdraw-from-invested > ctx.accounts.vault_state.to_account_info(), > ctx.accounts.reserve.to_account_info(), > ctx.accounts.ctoken_vault.to_account_info(), > ctx.accounts.lending_market.to_account_info(), > ctx.accounts.lending_market_authority.to_account_info(), > ctx.accounts.reserve_liquidity_supply.to_account_info(), > ctx.accounts.reserve_collateral_mint.to_account_info(), > ctx.accounts.reserve_collateral_token_program.to_account_info(), > ctx.accounts.instruction_sysvar_account.to_account_info(), > ctx.accounts.event_authority.to_account_info(), > ctx.accounts.kvault_program.to_account_info(), > ]; > account_infos.extend(ctx.remaining_accounts.iter().cloned()); > > solana_program::program::invoke_signed(&ix, &account_infos, &[authority_seeds])?; > Ok(()) > } > } > ``` > > **Step 6** > > ### Account Validation Struct > > ```rust expandable title="Withdraw accounts" theme={"theme":"css-variables"} > #[derive(Accounts)] > pub struct Withdraw<'info> { > #[account( > mut, > seeds = [AUTHORITY_SEED, vault_state.key().as_ref()], > bump, > )] > pub authority: SystemAccount<'info>, > > #[account(mut, token::authority = authority)] > pub user_token_ata: Account<'info, TokenAccount>, > > #[account(mut, token::authority = authority)] > pub user_shares_ata: Account<'info, TokenAccount>, > > /// CHECK: Kvault state account. > #[account(mut)] > pub vault_state: UncheckedAccount<'info>, > /// CHECK: Kvault global config account. > pub global_config: UncheckedAccount<'info>, > /// CHECK: Token vault owned by the Kvault program. > #[account(mut)] > pub token_vault: UncheckedAccount<'info>, > /// CHECK: Kvault base vault authority PDA. > pub base_vault_authority: UncheckedAccount<'info>, > /// CHECK: Underlying token mint. > #[account(mut)] > pub token_mint: UncheckedAccount<'info>, > /// CHECK: Shares mint. > #[account(mut)] > pub shares_mint: UncheckedAccount<'info>, > /// CHECK: Event-emit PDA owned by the Kvault program. > pub event_authority: UncheckedAccount<'info>, > > /// CHECK: Klend reserve account. > #[account(mut)] > pub reserve: UncheckedAccount<'info>, > /// CHECK: cToken vault owned by the Kvault program. > #[account(mut)] > pub ctoken_vault: UncheckedAccount<'info>, > /// CHECK: Klend lending market. > pub lending_market: UncheckedAccount<'info>, > /// CHECK: Klend lending market authority PDA. > pub lending_market_authority: UncheckedAccount<'info>, > /// CHECK: Reserve's underlying liquidity supply vault. > #[account(mut)] > pub reserve_liquidity_supply: UncheckedAccount<'info>, > /// CHECK: Reserve's cToken mint. > #[account(mut)] > pub reserve_collateral_mint: UncheckedAccount<'info>, > /// CHECK: Reserve's cToken program. > pub reserve_collateral_token_program: UncheckedAccount<'info>, > /// CHECK: Solana instructions sysvar. > #[account(address = solana_program::sysvar::instructions::ID)] > pub instruction_sysvar_account: UncheckedAccount<'info>, > > /// CHECK: The Kvault program. > #[account(address = KVAULT_PROGRAM_ID)] > pub kvault_program: UncheckedAccount<'info>, > /// CHECK: The Klend program. > #[account(address = KLEND_PROGRAM_ID)] > pub klend_program: UncheckedAccount<'info>, > pub token_program: Program<'info, Token>, > pub shares_token_program: Program<'info, Token>, > } > ``` > > [View API](https://docs.rs/kvault-interface/latest/kvault_interface/instructions/index.html) #### Full Code Example > [tab] TypeScript > > ```typescript expandable theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > compressTransactionMessageUsingAddressLookupTables, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > type Address, > } from '@solana/kit'; > import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import { Decimal } from 'decimal.js'; > > 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 slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const withdrawAmount = new Decimal(1.0); // 1 USDC > > const userShares = await vault.getUserShares(signer.address); > const tokensPerShare = await manager.getTokensPerShareSingleVault(vault, ledgerInstant, vaultReservesMap, ledgerInstant); > const sharesToWithdraw = Decimal.min(withdrawAmount.div(tokensPerShare), userShares.totalShares); > > const bundle = await vault.withdrawIxs( > signer, > sharesToWithdraw, > ledgerInstant, > vaultReservesMap, > farmState, > null // first-loss capital farm > ); > const instructions = [...bundle.unstakeFromFarmIfNeededIxs, ...bundle.withdrawIxs, ...bundle.postWithdrawIxs]; > > const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); > const lutsByAddress: Record = {}; > for (const lut of lookupTables) lutsByAddress[lut.address] = lut.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('Withdraw successful! Signature:', signature); > ``` # Strategy Source: https://docs.kamino.com/build/developers/liquidity/data/strategy ## Reading Strategy Data Retrieve strategy metadata, share price, TVL, APY, and aggregate metrics using the Kamino SDK and API. > [!NOTE] > > Historical strategy data is only available via the API. For the TypeScript shapes used by the methods below — both arguments and return values — see [Strategy Types](#strategy-types). ### Get All Strategies Fetches all live strategies from the API. Returns an array of strategy objects with addresses and pool metadata. ```typescript icon="typescript" getAllStrategies theme={"theme":"css-variables"} const url = 'https://api.kamino.finance/strategies?env=mainnet-beta&status=LIVE'; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const strategies = await res.json(); console.log({ address: strategies[0].address, pool: strategies[0].pool, tokenA: strategies[0].tokenA, tokenB: strategies[0].tokenB, }); ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get Strategies with Filters Filter strategies by type, status, community, or owner using the SDK. These filtering options aren't exposed by the public API. ```typescript icon="typescript" getStrategiesWithFilters theme={"theme":"css-variables"} import { createSolanaRpc } from '@solana/kit'; import { Kamino, StrategiesFilters } from '@kamino-finance/kliquidity-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const rpc = createSolanaRpc(RPC_ENDPOINT); const kamino = new Kamino('mainnet-beta', rpc); const filters: StrategiesFilters = { strategyCreationStatus: 'LIVE', strategyType: 'NON_PEGGED', }; const results = await kamino.getAllStrategiesWithFilters(filters); console.log(`Filters:`, filters); console.log(`Matched strategies: ${results.length}`); console.log('First 10:'); for (const { address, strategy } of results.slice(0, 10)) { console.log({ address: address.toString(), tokenAMint: strategy.tokenAMint.toString(), tokenBMint: strategy.tokenBMint.toString(), sharesMint: strategy.sharesMint.toString(), }); } ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get Strategy Metrics Returns real-time strategy metrics including share price, TVL, and APY for a specific strategy. ```typescript icon="typescript" getStrategyMetrics theme={"theme":"css-variables"} const strategyPubkey = '2H4xebnp2M9JYgPPfUw58uUQahWF8f1YTNxwwtmdqVYV'; // strategy address const url = `https://api.kamino.finance/strategies/${strategyPubkey}/metrics?env=mainnet-beta`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const metrics = await res.json(); console.log({ sharePrice: metrics.sharePrice, totalValueLocked: metrics.totalValueLocked, apy: metrics.apy, }); ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get Strategy Info Live on-chain read of a strategy's share price and underlying balances. ```typescript icon="typescript" getStrategyInfo theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { Kamino } from '@kamino-finance/kliquidity-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const STRATEGY = address('CEz5keL9hBCUbtVbmcwenthRMwmZLupxJ6YtYAgzp4ex'); // strategy address const rpc = createSolanaRpc(RPC_ENDPOINT); const kamino = new Kamino('mainnet-beta', rpc); const shareData = await kamino.getStrategyShareData(STRATEGY); const { price, balance } = shareData; const { computedHoldings, tokenAAmounts, tokenBAmounts, prices } = balance; console.log('Strategy:', STRATEGY); console.log('Share price (USD):', price.toString()); console.log('Total holdings (USD):', computedHoldings.totalSum.toString()); console.log('Available token A:', computedHoldings.available.a.toString()); console.log('Available token B:', computedHoldings.available.b.toString()); console.log('Invested token A:', computedHoldings.invested.a.toString()); console.log('Invested token B:', computedHoldings.invested.b.toString()); console.log('Raw token A amount:', tokenAAmounts.toString()); console.log('Raw token B amount:', tokenBAmounts.toString()); console.log('Token A price (USD):', prices.aPrice?.toString() ?? 'n/a'); console.log('Token B price (USD):', prices.bPrice?.toString() ?? 'n/a'); ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get Strategy Historical Metrics Time-series data for charting strategy share price, TVL, fees, and APY. ```typescript icon="typescript" getStrategyHistoricalMetrics theme={"theme":"css-variables"} const strategyPubkey = '2H4xebnp2M9JYgPPfUw58uUQahWF8f1YTNxwwtmdqVYV'; // strategy address const API_BASE_URL = 'https://api.kamino.finance'; const params = new URLSearchParams({ start: '2024-01-01T00:00:00.000Z', end: '2025-01-01T00:00:00.000Z', }).toString(); const url = `${API_BASE_URL}/v2/strategies/${strategyPubkey}/history?${params}`; const res = await fetch(url); if (!res.ok) { throw new Error(`Request failed: ${res.status} ${res.statusText}`); } const history = await res.json(); for (const item of history) { console.log({ timestamp: item.timestamp, sharePrice: item.sharePrice, tvl: item.tvl, apy: item.apy, }); } ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get Total TVL Returns aggregate total value locked across all live strategies. ```typescript icon="typescript" getTotalTvl theme={"theme":"css-variables"} const url = 'https://api.kamino.finance/strategies/tvl?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({ totalTvl: data }); ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### 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={"theme":"css-variables"} 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); ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ## Strategy Types TypeScript shapes used by the Kliquidity SDK for strategy reads — both arguments (e.g. `StrategiesFilters`) and return values. > [tab] StrategyWithAddress > > On-chain strategy account paired with its address. > > ```typescript theme={"theme":"css-variables"} > type StrategyWithAddress = { > address: Address; > strategy: WhirlpoolStrategy; > }; > ``` > [tab] StrategyBalances > > Raw token amounts and computed position values. > > ```typescript theme={"theme":"css-variables"} > type StrategyBalances = { > computedHoldings: Holdings; > prices: PriceData; > tokenAAmounts: Decimal; > tokenBAmounts: Decimal; > }; > ``` > [tab] PriceData > > Pool price, range bounds, and rebalance triggers. > > ```typescript theme={"theme":"css-variables"} > type PriceData = { > aPrice: Decimal | null; > bPrice: Decimal | null; > poolPrice: Decimal; > lowerPrice: Decimal; > upperPrice: Decimal; > }; > ``` > [tab] StrategyPrices > > Oracle and TWAP prices for strategy tokens and rewards. > > ```typescript theme={"theme":"css-variables"} > type StrategyPrices = { /* ... */ }; > ``` > [tab] StrategiesFilters > > Query parameters for filtering strategies by type, status, and ownership. > > ```typescript theme={"theme":"css-variables"} > type StrategiesFilters = { /* ... */ }; > ``` ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) # User Position Source: https://docs.kamino.com/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). ### 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={"theme":"css-variables"} 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(), }); } ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### 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={"theme":"css-variables"} 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, }); ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get User PnL History Returns time-series PnL snapshots for charting a user's position over time. ```typescript icon="typescript" getUserPnlHistory theme={"theme":"css-variables"} 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, }); } ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get User Fees and Rewards Returns cumulative fees and rewards earned by the user in a specific strategy. ```typescript icon="typescript" getUserFeesAndRewards theme={"theme":"css-variables"} 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); ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get User Rewards History Returns historical rewards earned by a wallet across all strategies. ```typescript icon="typescript" getUserRewardsHistory theme={"theme":"css-variables"} 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); ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ### Get User Transactions Deposit, withdrawal, and claim transaction history for a wallet across all strategies. ```typescript icon="typescript" getUserTransactions theme={"theme":"css-variables"} 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, }); } ``` [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) ## Position Types TypeScript shapes returned by the Kliquidity SDK for user position reads. > [tab] KaminoPosition > > A user's share holdings in a specific strategy. > > ```typescript theme={"theme":"css-variables"} > interface KaminoPosition { > strategy: Address; > shareMint: Address; > sharesAmount: Decimal; > strategyDex: Dex; > } > ``` > [tab] Holdings > > Available and invested token values with USD valuations. > > ```typescript theme={"theme":"css-variables"} > type Holdings = { > available: TokenAmounts; > availableUsd: Decimal; > invested: TokenAmounts; > investedUsd: Decimal; > totalSum: Decimal; > }; > ``` > [tab] TokenAmounts > > Pair of token quantities (A and B amounts). > > ```typescript theme={"theme":"css-variables"} > type TokenAmounts = { > a: Decimal; > b: Decimal; > }; > ``` > [tab] ShareData > > Current share price with strategy balances. > > ```typescript theme={"theme":"css-variables"} > type ShareData = { > price: Decimal; > balance: StrategyBalances; > }; > ``` > [tab] StrategyHolder > > A wallet and its share count in a strategy. > > ```typescript theme={"theme":"css-variables"} > type StrategyHolder = { > holderPubkey: Address; > amount: Decimal; > }; > ``` > [tab] 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={"theme":"css-variables"} > type WithdrawShares = { > prerequisiteIxs: TransactionInstruction[]; > withdrawIx: TransactionInstruction; > closeSharesAtaIx?: TransactionInstruction; > }; > ``` ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) # Deposit Source: https://docs.kamino.com/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. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, address lookup table fetching, and Kit transaction building. ```typescript theme={"theme":"css-variables"} 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 2** ### 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={"theme":"css-variables"} 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 3** ### Load Strategy State Fetch the on-chain strategy account so the SDK has current state to build instructions against. ```typescript theme={"theme":"css-variables"} const strategyState = (await kamino.getStrategiesWithAddresses([STRATEGY]))[0]; if (!strategyState) { console.log("Strategy not found:", STRATEGY); process.exit(1); } ``` **Step 4** ### 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={"theme":"css-variables"} const { instructions, lookupTablesAddresses } = await kamino.singleSidedDepositTokenB( { address: STRATEGY, strategy: strategyState.strategy }, usdcAmount, signer, slippageBps, ); ``` **Step 5** ### 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. ```typescript theme={"theme":"css-variables"} const allAddresses = new Set(); 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 = {}; for (const acc of lutAccounts) { lutsByAddress[acc.address] = acc.data.addresses; } ``` **Step 6** ### 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={"theme":"css-variables"} 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, ); ``` > [!TIP] > > The deposit is complete. Your USDC has been swapped and deposited into the strategy. #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} 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(); 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 = {}; 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. **Step 1** ### 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={"theme":"css-variables"} 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"; ``` **Step 2** ### 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={"theme":"css-variables"} 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. **Step 3** ### Load Strategy State Fetch the on-chain strategy account so the SDK has current state to build instructions against. ```typescript theme={"theme":"css-variables"} 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 4** ### 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={"theme":"css-variables"} 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 5** ### 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={"theme":"css-variables"} 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. **Step 6** ### Build Two-Sided Deposit Instructions Build the deposit instruction and the wSOL ATA close instruction, then assemble the final instruction list. ```typescript theme={"theme":"css-variables"} 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. **Step 7** ### 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. ```typescript theme={"theme":"css-variables"} const allAddresses = new Set(); 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 = {}; for (const acc of lutAccounts) { lutsByAddress[acc.address] = acc.data.addresses; } ``` **Step 8** ### 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={"theme":"css-variables"} 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, ); ``` > [!TIP] > > 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. #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} 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(); 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 = {}; 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://docs.kamino.com/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. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, address lookup table fetching, and Kit transaction building. ```typescript theme={"theme":"css-variables"} 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 2** ### Configure Constants and Initialize Kamino Set the keypair path, RPC endpoints, and target strategy. Load the signer and initialize the Kamino client. ```typescript theme={"theme":"css-variables"} 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 3** ### Load Strategy State Fetch the strategy account so the SDK has the current state and token mints. ```typescript theme={"theme":"css-variables"} const strategy = await kamino.getStrategyByAddress(STRATEGY); if (!strategy) { console.log("Strategy not found:", STRATEGY); process.exit(1); } const strategyWithAddress = { strategy, address: STRATEGY }; ``` **Step 4** ### 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={"theme":"css-variables"} 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 5** ### 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={"theme":"css-variables"} 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 6** ### 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. ```typescript theme={"theme":"css-variables"} const allAddresses = new Set(); 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 = {}; for (const acc of lutAccounts) { lutsByAddress[acc.address] = acc.data.addresses; } ``` **Step 7** ### 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={"theme":"css-variables"} 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); ``` > [!TIP] > > The withdrawal is complete. Token A and Token B have been transferred to your ATAs. #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} 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) { 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(); 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 = {}; 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://docs.kamino.com/build/developers/liquidity/overview Learn how to build with Kamino's automated concentrated liquidity vaults ## 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](/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](/products/liquidity/concepts) for the full explanation before integrating. ## Key Components of Liquidity Integration > [card] Strategy Operations > > Two-sided and single-sided deposits, partial and full withdrawals, with ATA management and lookup-table resolution handled by the SDK. > [card] Position Tracking > > User share holdings, USD valuation, pending fees and rewards, PnL, and transaction history. > [card] Strategy Analytics > > Share price, TVL, APR/APY, price range, and historical metrics for charts and dashboards. ## Integration Options > [card] Public API > > Read-only access to strategy metrics, historical performance, user PnL, fees and rewards, and transaction history. Language-agnostic REST endpoints. > [card] TypeScript SDK > > On-chain reads and transaction building for deposits, withdrawals, and position tracking. TS/JS only. ### Deposit > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > 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); > ``` > > [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) > [!NOTE] > > For the full deposit flow including lookup-table resolution and transaction confirmation, see [Deposit Operations](/build/developers/liquidity/operations/deposit). ### Withdraw > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > 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: 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); > ``` > > [View Code](https://github.com/Kamino-Finance/kliquidity-sdk/tree/master/examples) > [!NOTE] > > For the full withdraw flow including ATA setup, lookup-table resolution, and transaction confirmation, see [Withdraw Operations](/build/developers/liquidity/operations/withdraw). ## What's Covered > [card] [Strategy Data](/build/developers/liquidity/data/strategy) > > List strategies, read share price, TVL, APR/APY, price range, and token balances. > [card] [User Position Data](/build/developers/liquidity/data/user-position) > > Fetch user positions, USD valuation, pending fees and rewards, and PnL. > [card] [Deposit](/build/developers/liquidity/operations/deposit) > > Two-sided deposits and single-sided deposits via auto-swap. > [card] [Withdraw](/build/developers/liquidity/operations/withdraw) > > Withdraw a specific share amount or close the full position. ## Relevant Links > [card] [Fetch Data via the API](https://api-docs.kamino.com/) > > Access strategy metrics and performance data through REST endpoints. > [card] [Kliquidity SDK repository](https://github.com/Kamino-Finance/kliquidity-sdk) > > Explore the SDK source, on-chain program docs, and example scripts. > [card] [NPM SDK package](https://www.npmjs.com/package/@kamino-finance/kliquidity-sdk) > > Install the TypeScript SDK to integrate liquidity operations. > [card] [Liquidity Concepts](/products/liquidity/concepts) > > AMMs, concentrated liquidity, impermanent loss, and kTokens explained. # Monitor Position Health Source: https://docs.kamino.com/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 > [tab] SDK > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication and Kamino SDK operations. > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > ObligationTypeTag, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > Initialize the RPC connection and load the xStocks market. > > ```typescript theme={"theme":"css-variables"} > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market > const walletAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Fetch Multiply Obligations > > Retrieve all multiply obligations for the wallet address using the obligation type filter. > > ```typescript theme={"theme":"css-variables"} > const obligations = await market!.getUserObligationsByTag( > ObligationTypeTag.Multiply, > walletAddress, > await getCurrentLedgerInstant(rpc) > ); > > 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. > > **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 | > | `ObligationTypeTag.MultiplyFixedRate` | 4: Multiply positions tied to specific reserves, used when a token has a fixed-rate reserve | > | `ObligationTypeTag.LendingFixedRate` | 5: Lending-only positions tied to a specific reserve | > | `ObligationTypeTag.LeverageFixedRate` | 6: Leverage positions tied to specific reserves | > > **Step 4** > > ### Read Position Health Metrics > > Access the position health statistics from each obligation's `refreshedStats`. > > ```typescript theme={"theme":"css-variables"} > console.table( > obligations.map((obligation) => { > const stats = obligation.refreshedStats; > return { > obligation: obligation.obligationAddress, > depositsUsd: stats.userTotalDeposit.toFixed(2), > borrowsUsd: stats.userTotalBorrow.toFixed(2), > netValueUsd: stats.netAccountValue.toFixed(2), > leverage: `${stats.leverage.toFixed(2)}x`, > borrowLimitUsd: stats.borrowLimit.toFixed(2), > ltv: `${stats.loanToValue.mul(100).toFixed(2)}%`, > liquidationLtv: `${stats.liquidationLtv.mul(100).toFixed(2)}%`, > }; > }) > ); > ``` > > > [!TIP] > > > > You now have access to all position health metrics including leverage, borrowing capacity, and liquidation thresholds. > [tab] API > > ```typescript theme={"theme":"css-variables"} > 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)}%`); > }); > ``` *** ## 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](/build/developers/multiply/data/concepts). # Flash Loans Source: https://docs.kamino.com/build/developers/multiply/flash-loans Execute flash loans for atomic, uncollateralized borrowing within a single transaction ## Flash Loans > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > none, > assertIsTransactionWithinSizeLimit, > } from '@solana/kit'; > import { > KaminoMarket, > PROGRAM_ID, > getFlashLoanInstructions, > getAssociatedTokenAddress, > getMedianSlotDurationInMsFromLastEpochs, > } 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 2** > > ### Setup Market and Signer > > Load your keypair, initialize RPC connections, and load the Kamino market. > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Configure Flash Loan Parameters > > Set the token, the flash loan amount in lamports (1 USDC), and the wallet's token account that receives it. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const flashLoanAmount = new Decimal(1_000_000); > const usdcAta = await getAssociatedTokenAddress(usdcMint, signer.address, usdcReserve.getLiquidityTokenProgram()); > ``` > > **Step 4** > > ### Build Flash Loan Instructions > > Generate the flash borrow and flash repay instructions using the Kamino SDK. > > ```typescript theme={"theme":"css-variables"} > 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, > }); > ``` > > > [!NOTE] > > > > `borrowIxIndex: 0` says 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. > > > [!NOTE] > > > > The flash repay takes the amount plus the reserve's flash loan fee (`reserve.state.config.fees.flashLoanFeeSf`, 0.001% for USDC on the SOL/BTC Market). The wallet must already hold enough USDC in that token account to pay the fee, or the repay fails with insufficient funds. > > **Step 5** > > ### 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={"theme":"css-variables"} > const memoIx = getAddMemoInstruction({ memo: 'Hello Kamino' }); > > const allInstructions = [flashBorrowIx, memoIx, flashRepayIx]; > ``` > > **Step 6** > > ### Build and Send Transaction > > Build the transaction with a fresh blockhash and send it to the network. > > ```typescript theme={"theme":"css-variables"} > 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(allInstructions, tx) > ); > > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: false, > }); > > console.log('Flash loan successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > Your flash loan transaction is complete! The borrowed funds were used for your operations and automatically repaid within the same atomic transaction. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Fetch Reserve Data > > ```rust theme={"theme":"css-variables"} > use klend_interface::helpers; > use klend_interface::ReserveInfo; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > let reserve_data = rpc_client.get_account(&reserve_pubkey)?; > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; > ``` > > > [!NOTE] > > > > Use `ReserveInfo::from_account_data(pubkey, &data)` to construct reserve info from raw RPC account bytes. > > **Step 4** > > ### Derive Token Accounts > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > let user_token_account = get_associated_token_address(&owner, &reserve.liquidity_mint); > ``` > > **Step 5** > > ### Build Flash Loan Instructions > > ```rust theme={"theme":"css-variables"} > let (borrow_ix, repay_ix) = helpers::flash::flash_loan( > owner, > &reserve, > user_token_account, // source for repayment > user_token_account, // destination for borrowed funds > 1_000_000, // 1 USDC (6 decimals) > 0, // borrow instruction index in the transaction > None, // no referrer > ); > ``` > > > [!NOTE] > > > > The `borrow_instruction_index` parameter specifies the position of the flash borrow instruction in the final transaction. Set to `0` if it is the first instruction. > > **Step 6** > > ### Compose and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > // Insert your custom instructions between borrow and repay > let your_custom_instructions = vec![/* your logic here */]; > > let mut all_instructions = vec![borrow_ix]; > all_instructions.extend(your_custom_instructions); > all_instructions.push(repay_ix); > > let message = Message::new(&all_instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Flash loan successful! Signature: {signature}"); > ``` > > > [!NOTE] > > > > The flash borrow and repay must be in the same transaction. You can insert any number of instructions between them. # Multiply Deleverage with xStocks Source: https://docs.kamino.com/build/developers/multiply/operations/deleverage-xstocks Reduce leverage on xStocks positions by selling collateral to repay debt atomically Deleveraging takes value out of a multiply position in a single atomic transaction: it sells TSLAx collateral through KSwap, repays part of the USDC debt with a flash loan, and sends the rest to the wallet, with no external funds needed. The position shrinks but keeps its LTV, so its leverage stays the same. To lower leverage, repay debt with [Repay](/build/developers/multiply/operations/repay-xstocks) or [Repay with Collateral](/build/developers/multiply/operations/repay-collateral). > [!NOTE] > > Multiply positions use `MultiplyObligation` which derives a unique PDA (Program Derived Address) based on your wallet, market, collateral token (TSLAx), and debt token (USDC). Each collateral/debt pair creates a separate obligation address, allowing you to have multiple multiply positions simultaneously. ## Deleverage Multiply Position with xStocks Reduce leverage on a TSLAx multiply position by selling collateral to repay USDC debt. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, none, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, isTransactionMessageWithinSizeLimit, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, type Instruction, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoMarket, MultiplyObligation, PROGRAM_ID, getWithdrawWithLeverageIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, type SwapInputs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { KswapSdk, loadRouterContext, type RouteOutput } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; import BN from 'bn.js'; import Decimal from 'decimal.js'; ``` > [!NOTE] > > Use `@kamino-finance/kswap-sdk` 2.9.0. It's the last version on `@solana/kit` 2, which `@kamino-finance/klend-sdk` 13 uses; 3.x moved to kit 8. **Step 2** ### Load Configuration and Initialize SDKs ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const WITHDRAW_AMOUNT = new Decimal(3); const SLIPPAGE_BPS = 50; const MAX_COMPUTE_UNITS = 1_400_000; const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const collReserve = market!.getExistingFloatRateReserveByMint(collMint); const debtReserve = market!.getExistingFloatRateReserveByMint(debtMint); const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); const scope = new Scope('mainnet-beta', rpc); ``` **Step 3** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. ```typescript theme={"theme":"css-variables"} const obligationAddress = await new MultiplyObligation(collMint, debtMint, PROGRAM_ID).toPda(marketPubkey, signer.address); const obligation = await market!.getObligationByAddress(obligationAddress); if (!obligation) { console.log('No Multiply position found for', signer.address); } ``` **Step 4** ### Read the Position `deposited` and `borrowed` are the position's current amounts in token units. ```typescript theme={"theme":"css-variables"} const deposited = obligation!.getDepositAmountByReserve(collReserve); const borrowed = obligation!.getBorrowAmountByReserve(debtReserve); console.log(`Current position: ${deposited} TSLAx deposited, ${borrowed} USDC borrowed`); ``` **Step 5** ### Get Scope Price Refresh Instructions ```typescript theme={"theme":"css-variables"} const scopeRefreshIx = await getScopeRefreshIxForObligationAndReserves( market!, collReserve, debtReserve, obligation!, { scope, scopeConfigurations: await scope.getAllConfigurations() } ); ``` **Step 6** ### Define the Swap Helpers The SDK asks for swaps through two callbacks: a quoter that prices the swap and a swapper that returns its instructions. Both use every KSwap route, sorted by output. ```typescript theme={"theme":"css-variables"} async function getRoutes(inputs: SwapInputs) { const { routes } = await kswap.getAllRoutes( { executor: signer.address, tokenIn: inputs.inputMint, tokenOut: inputs.outputMint, amount: new BN(inputs.inputAmountLamports.floor().toString()), maxSlippageBps: SLIPPAGE_BPS, swapType: 'exactIn', wrapAndUnwrapSol: false, }, await loadRouterContext(rpc, inputs.inputMint, inputs.outputMint) ); if (routes.length === 0) { console.log('No KSwap route found for', inputs.inputMint, '->', inputs.outputMint); } return routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); } function midPrice(route: RouteOutput) { const amounts = route.amountsExactIn!; const amountIn = new Decimal(amounts.amountIn.toString()).div(new Decimal(10).pow(route.inputTokenDecimals!)); const amountOut = new Decimal(amounts.amountOut.toString()).div(new Decimal(10).pow(route.outputTokenDecimals!)); return amountOut.div(amountIn); } const quoter = async (inputs: SwapInputs) => { const [bestRoute] = await getRoutes(inputs); return { priceAInB: midPrice(bestRoute), quoteResponse: bestRoute }; }; const swapper = async (inputs: SwapInputs) => (await getRoutes(inputs)).map((route) => { const routeIxs = route.instructions!; return { preActionIxs: [], swapIxs: [ ...routeIxs.createInAtaIxs, ...routeIxs.wrapSolIxs, ...routeIxs.swapIxs, ...routeIxs.unwrapSolIxs, ...routeIxs.createOutAtaIxs, ], lookupTables: route.lookupTableAccounts ?? [], quote: { priceAInB: midPrice(route), quoteResponse: route }, }; }); ``` > [!WARNING] > > `priceAInB` must be the mid price (`amountOut / amountIn`, each in token units), before slippage. The SDK applies `slippagePct` itself, so a guaranteed or minimum-out price counts slippage twice and sizes the position wrong. `getBestRoute` currently returns no routes, so use `getAllRoutes`, which in kswap-sdk 2.9.0 takes the router context as a second argument. **Step 7** ### Build the Withdraw Routes The SDK builds one candidate transaction per swap route: flash borrow, repay part of the debt, withdraw TSLAx, swap it to USDC, repay the flash loan, and send the rest to the wallet. ```typescript theme={"theme":"css-variables"} const routes = await getWithdrawWithLeverageIxs({ owner: signer, kaminoMarket: market!, debtReserveAddress: debtReserve.address, collReserveAddress: collReserve.address, obligation: obligation!, deposited, borrowed, referrer: none(), currentLedgerInstant: await getCurrentLedgerInstant(rpc), withdrawAmount: WITHDRAW_AMOUNT, priceCollToDebt: collReserve.getOracleMarketPrice().div(debtReserve.getOracleMarketPrice()), slippagePct: new Decimal(SLIPPAGE_BPS / 100), isClosingPosition: false, selectedTokenMint: debtMint, userSolBalanceLamports: Number((await rpc.getBalance(signer.address).send()).value), scopeRefreshIx, budgetAndPriorityFeeIxs: getComputeBudgetAndPriorityFeeIxs(MAX_COMPUTE_UNITS), quoteBufferBps: new Decimal(0), quoter, swapper, useV2Ixs: true, }); ``` > [!NOTE] > > `withdrawAmount` is in the selected token (USDC here). To close the whole position, set `isClosingPosition` to `true`. **Step 8** ### Fetch Lookup Tables Fetch Kamino's lookup tables for each candidate transaction, one request per candidate. ```typescript theme={"theme":"css-variables"} async function getKaminoLookupTables(instructions: Instruction[]) { const addresses = [ ...new Set(instructions.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), ]; const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addresses }), }); if (!lutResponse.ok) { console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); } const { lutAddresses } = await lutResponse.json(); return fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); } ``` > [!NOTE] > > `/luts/find-minimal` takes one transaction's worth of addresses (between 64 and 128), so a single request for all candidates is rejected. **Step 9** ### Pick the Route That Fits Compress each candidate with its route's lookup tables and Kamino's, then take the best-output one that fits in a transaction. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const candidates = await Promise.all( routes.map(async (route) => { const lookupTables = [...route.lookupTables, ...(await getKaminoLookupTables(route.ixs))]; const lookupTableAddresses: Record = Object.fromEntries( lookupTables.map((lut) => [lut.address, lut.data.addresses]) ); return pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(route.ixs, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) ); }) ); const transactionMessage = candidates.find((candidate) => isTransactionMessageWithinSizeLimit(candidate)); if (!transactionMessage) { console.log(`None of the ${candidates.length} swap routes fit in one transaction`); } ``` > [!NOTE] > > The best-output route often has too many accounts to fit, even compressed: in testing only one or two of five to ten routes did. The slippage setting covers the gap between the best route's quote and the one sent. **Step 10** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage!); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deleverage successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The position is smaller and the USDC is in the wallet. The position keeps its LTV, so its leverage is unchanged. ### Borrow and Multiply SDK Methods | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral while the position stays under its borrow limit | | `getWithdrawWithLeverageIxs` | Shrink the position and withdraw | Take value out while keeping the position's LTV; leverage stays the same | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | > [!NOTE] > > **Multiply operations** use `MultiplyObligation`. **Vanilla operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. # Multiply Deposit with xStocks Source: https://docs.kamino.com/build/developers/multiply/operations/deposit-xstocks Create leveraged positions using xStocks collateral with atomic flash loan deposits A multiply deposit creates a leveraged collateral position in a single, atomic transaction by combining an initial deposit with temporary liquidity. When a multiply deposit is initiated, the protocol first temporarily borrows the debt token (for example, USDC) through a flash loan. The borrowed amount is swapped into the collateral token (for example, TSLAx) using KSwap (Kamino's token swap SDK). The resulting collateral is then deposited into Kamino Lend. With the collateral in place, the position borrows the debt token against it, and the borrowed amount is used to repay the flash loan before the transaction completes. The result is a leveraged position with increased exposure to the collateral token and an outstanding debt balance. ## Multiply Deposit with xStocks Create a leveraged position in a single atomic transaction using Klend's multiply feature and KSwap multi-route swap optimization. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, none, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, isTransactionMessageWithinSizeLimit, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, type Instruction, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoMarket, MultiplyObligation, ObligationTypeTag, PROGRAM_ID, getDepositWithLeverageIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, getUserLutAddressAndSetupIxs, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, type SwapInputs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { KswapSdk, loadRouterContext, type RouteOutput } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; import BN from 'bn.js'; import Decimal from 'decimal.js'; ``` > [!NOTE] > > Use `@kamino-finance/kswap-sdk` 2.9.0. It's the last version on `@solana/kit` 2, which `@kamino-finance/klend-sdk` 13 uses; 3.x moved to kit 8. **Step 2** ### Load Configuration and Initialize SDKs ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const DEPOSIT_AMOUNT = new Decimal(10); const TARGET_LEVERAGE = new Decimal(2); const SLIPPAGE_BPS = 50; const MAX_COMPUTE_UNITS = 1_400_000; const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const collReserve = market!.getExistingFloatRateReserveByMint(collMint); const debtReserve = market!.getExistingFloatRateReserveByMint(debtMint); const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); const scope = new Scope('mainnet-beta', rpc); ``` **Step 3** ### Set Up a New Wallet The leverage functions expect the wallet's Kamino user metadata to exist. A wallet that has never used Kamino sends one setup transaction first. ```typescript theme={"theme":"css-variables"} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); const [, userMetadata] = await market!.getUserMetadata(signer.address); if (!userMetadata) { const [, setupInstructions] = await getUserLutAddressAndSetupIxs(market!, signer, none(), false); const { value: setupBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const setupTransaction = await signTransactionMessageWithSigners( pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(setupBlockhash, tx), (tx) => appendTransactionMessageInstructions(setupInstructions.flat(), tx) ) ); await sendAndConfirm(setupTransaction, { commitment: 'confirmed', skipPreflight: true }); } ``` **Step 4** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. It's `null` until the first deposit creates it. ```typescript theme={"theme":"css-variables"} const obligationAddress = await new MultiplyObligation(collMint, debtMint, PROGRAM_ID).toPda(marketPubkey, signer.address); const obligation = await market!.getObligationByAddress(obligationAddress); ``` **Step 5** ### Get Scope Price Refresh Instructions ```typescript theme={"theme":"css-variables"} const scopeRefreshIx = await getScopeRefreshIxForObligationAndReserves( market!, collReserve, debtReserve, obligation ?? undefined, { scope, scopeConfigurations: await scope.getAllConfigurations() } ); ``` **Step 6** ### Define the Swap Helpers The SDK asks for swaps through two callbacks: a quoter that prices the swap and a swapper that returns its instructions. Both use every KSwap route, sorted by output. ```typescript theme={"theme":"css-variables"} async function getRoutes(inputs: SwapInputs) { const { routes } = await kswap.getAllRoutes( { executor: signer.address, tokenIn: inputs.inputMint, tokenOut: inputs.outputMint, amount: new BN(inputs.inputAmountLamports.floor().toString()), maxSlippageBps: SLIPPAGE_BPS, swapType: 'exactIn', wrapAndUnwrapSol: false, }, await loadRouterContext(rpc, inputs.inputMint, inputs.outputMint) ); if (routes.length === 0) { console.log('No KSwap route found for', inputs.inputMint, '->', inputs.outputMint); } return routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); } function midPrice(route: RouteOutput) { const amounts = route.amountsExactIn!; const amountIn = new Decimal(amounts.amountIn.toString()).div(new Decimal(10).pow(route.inputTokenDecimals!)); const amountOut = new Decimal(amounts.amountOut.toString()).div(new Decimal(10).pow(route.outputTokenDecimals!)); return amountOut.div(amountIn); } const quoter = async (inputs: SwapInputs) => { const [bestRoute] = await getRoutes(inputs); return { priceAInB: midPrice(bestRoute), quoteResponse: bestRoute }; }; const swapper = async (inputs: SwapInputs) => (await getRoutes(inputs)).map((route) => { const routeIxs = route.instructions!; return { preActionIxs: [], swapIxs: [ ...routeIxs.createInAtaIxs, ...routeIxs.wrapSolIxs, ...routeIxs.swapIxs, ...routeIxs.unwrapSolIxs, ...routeIxs.createOutAtaIxs, ], lookupTables: route.lookupTableAccounts ?? [], quote: { priceAInB: midPrice(route), quoteResponse: route }, }; }); ``` > [!WARNING] > > `priceAInB` must be the mid price (`amountOut / amountIn`, each in token units), before slippage. The SDK applies `slippagePct` itself, so a guaranteed or minimum-out price counts slippage twice and sizes the position wrong. `getBestRoute` currently returns no routes, so use `getAllRoutes`, which in kswap-sdk 2.9.0 takes the router context as a second argument. **Step 7** ### Build the Leverage Routes The SDK builds one candidate transaction per swap route: flash borrow USDC, swap it to TSLAx, deposit, borrow USDC, repay the flash loan. ```typescript theme={"theme":"css-variables"} const routes = await getDepositWithLeverageIxs({ owner: signer, kaminoMarket: market!, debtReserveAddress: debtReserve.address, collReserveAddress: collReserve.address, depositAmount: DEPOSIT_AMOUNT, priceDebtToColl: debtReserve.getOracleMarketPrice().div(collReserve.getOracleMarketPrice()), slippagePct: new Decimal(SLIPPAGE_BPS / 100), obligation, referrer: none(), currentLedgerInstant: await getCurrentLedgerInstant(rpc), targetLeverage: TARGET_LEVERAGE, selectedTokenMint: debtMint, obligationTypeTagOverride: ObligationTypeTag.Multiply, scopeRefreshIx, budgetAndPriorityFeeIxs: getComputeBudgetAndPriorityFeeIxs(MAX_COMPUTE_UNITS), quoteBufferBps: new Decimal(0), quoter, swapper, useV2Ixs: true, }); ``` > [!NOTE] > > `selectedTokenMint` is the token you deposit: the debt token (USDC) here, or the collateral token. `quoteBufferBps` inflates only the amount used for the quote; 0 quotes the exact swap amount and leaves price moves to the slippage setting. **Step 8** ### Fetch Lookup Tables Fetch Kamino's lookup tables for each candidate transaction, one request per candidate. ```typescript theme={"theme":"css-variables"} async function getKaminoLookupTables(instructions: Instruction[]) { const addresses = [ ...new Set(instructions.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), ]; const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addresses }), }); if (!lutResponse.ok) { console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); } const { lutAddresses } = await lutResponse.json(); return fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); } ``` > [!NOTE] > > `/luts/find-minimal` takes one transaction's worth of addresses (between 64 and 128), so a single request for all candidates is rejected. **Step 9** ### Pick the Route That Fits Compress each candidate with its route's lookup tables and Kamino's, then take the best-output one that fits in a transaction. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const candidates = await Promise.all( routes.map(async (route) => { const lookupTables = [...route.lookupTables, ...(await getKaminoLookupTables(route.ixs))]; const lookupTableAddresses: Record = Object.fromEntries( lookupTables.map((lut) => [lut.address, lut.data.addresses]) ); return pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(route.ixs, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) ); }) ); const transactionMessage = candidates.find((candidate) => isTransactionMessageWithinSizeLimit(candidate)); if (!transactionMessage) { console.log(`None of the ${candidates.length} swap routes fit in one transaction`); } ``` > [!NOTE] > > The best-output route often has too many accounts to fit, even compressed: in testing only one or two of five to ten routes did. The slippage setting covers the gap between the best route's quote and the one sent. **Step 10** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage!); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Multiply deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The 2x TSLAx position is open: TSLAx collateral with a USDC debt, created in one transaction. ## Transaction Flow > [accordion] View Transaction Flow Diagram > > ```mermaid theme={"theme":"css-variables"} > graph TD > A[Load Market & SDKs] --> B[Set Up New Wallet] > B --> C[Load Multiply Obligation] > C --> D[Refresh Scope Prices] > D --> E[Build One Candidate per Swap Route] > E --> F[Compress with Lookup Tables] > F --> G[Pick Best Route That Fits] > G --> J[Sign & Send Transaction] > > J --> K{Transaction Success?} > K -->|Yes| L[Leveraged Position Created] > K -->|No| M[Transaction Reverts] > ``` ## Asset Flow > [accordion] 2x Leveraged TSLAx Position: Step-by-Step > > **1. Initial State** > > * Wallet: 10 USDC > * Position: None > > **2. Flash Borrow** > > * Flash loan: 10 USDC (temporary) > * Available: 20 USDC total > > **3. Swap & Deposit** > > * Swap 20 USDC to TSLAx via KSwap > * Deposit TSLAx as collateral > > **4. Borrow & Repay** > > * Borrow 10 USDC against collateral > * Repay 10 USDC flash loan > > **5. Final Position** > > * Collateral: TSLAx (\$20 value) > * Debt: 10 USDC > * Net Equity: 10 USDC > * Leverage: 2x ## Key Concepts > [accordion] Flash Loans > > Flash loans are uncollateralized loans that must be borrowed and repaid within the same transaction. They enable: > > * **Zero upfront capital**: Borrow large amounts without collateral > * **Atomic execution**: All operations succeed or fail together > * **Leverage creation**: Bootstrap leveraged positions in one transaction > * **Risk-free**: Transaction reverts if flash loan cannot be repaid > [accordion] Multiply Obligation Type > > The `MultiplyObligation` is a specialized obligation type that: > > * **Defines position type**: Multiply vs Leverage vs Vanilla > * **Derives unique address**: Via PDA using collateral/debt mints > * **Supports multiple positions**: Create different obligations with same tokens using ID parameter > * **Creates new obligation**: When none exists (indicated by `obligation: null`) > [accordion] KSwap Multi-Route Optimization > > KSwap provides optimal swap execution through: > > * **Multi-DEX routing**: Tests routes across Jupiter, OKX, dFlow, and other DEX aggregators > * **Route choice**: Sorted by output; the best-output route that fits in one transaction is sent > * **Slippage protection**: Each route enforces a minimum output within the slippage setting > * **Automatic ATA creation**: Handles token account creation and SOL wrapping/unwrapping ### Borrow and Multiply SDK Methods | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid | | `getWithdrawWithLeverageIxs` | Shrink the position and withdraw | Take value out while keeping the position's LTV; leverage stays the same | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | > [!NOTE] > > **Multiply operations** use `MultiplyObligation`. **Vanilla operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. ## Related Resources > [card] [Deposit and Borrow](/build/tutorials/borrow/deposit-and-borrow) > > Learn basic deposit and borrow operations > [card] [Market Data](/build/developers/borrow/data/market-data) > > Read market metrics and reserve data > [card] [KSwap SDK](https://www.npmjs.com/package/@kamino-finance/kswap-sdk) > > Multi-DEX swap routing SDK > [card] [Scope SDK](https://github.com/Kamino-Finance/scope-sdk) > > Oracle price aggregation SDK # Repay with Collateral Source: https://docs.kamino.com/build/developers/multiply/operations/repay-collateral Repay debt using collateral from your position with KSwap routing Repay with collateral reduces debt in a single atomic transaction by converting collateral into the debt token without requiring additional funds. The protocol flash borrows the debt token, repays the debt, withdraws the freed collateral, swaps it to the debt token via KSwap, and repays the flash loan, all in one transaction. ## Repay with Collateral using KSwap Reduce debt in a single transaction by converting collateral using a flash loan and KSwap. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, none, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, isTransactionMessageWithinSizeLimit, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, type Instruction, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoMarket, MultiplyObligation, PROGRAM_ID, getRepayWithCollIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, type SwapInputs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { KswapSdk, loadRouterContext, type RouteOutput } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; import BN from 'bn.js'; import Decimal from 'decimal.js'; ``` > [!NOTE] > > Use `@kamino-finance/kswap-sdk` 2.9.0. It's the last version on `@solana/kit` 2, which `@kamino-finance/klend-sdk` 13 uses; 3.x moved to kit 8. **Step 2** ### Load Configuration and Initialize SDKs ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const REPAY_AMOUNT = new Decimal(5); const SLIPPAGE_BPS = 50; const MAX_COMPUTE_UNITS = 1_400_000; const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const collReserve = market!.getExistingFloatRateReserveByMint(collMint); const debtReserve = market!.getExistingFloatRateReserveByMint(debtMint); const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); const scope = new Scope('mainnet-beta', rpc); ``` **Step 3** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. ```typescript theme={"theme":"css-variables"} const obligationAddress = await new MultiplyObligation(collMint, debtMint, PROGRAM_ID).toPda(marketPubkey, signer.address); const obligation = await market!.getObligationByAddress(obligationAddress); if (!obligation) { console.log('No Multiply position found for', signer.address); } ``` **Step 4** ### Get Scope Price Refresh Instructions ```typescript theme={"theme":"css-variables"} const scopeRefreshIx = await getScopeRefreshIxForObligationAndReserves( market!, collReserve, debtReserve, obligation!, { scope, scopeConfigurations: await scope.getAllConfigurations() } ); ``` **Step 5** ### Define the Swap Helpers The SDK asks for swaps through two callbacks: a quoter that prices the swap and a swapper that returns its instructions. Both use every KSwap route, sorted by output. ```typescript theme={"theme":"css-variables"} async function getRoutes(inputs: SwapInputs) { const { routes } = await kswap.getAllRoutes( { executor: signer.address, tokenIn: inputs.inputMint, tokenOut: inputs.outputMint, amount: new BN(inputs.inputAmountLamports.floor().toString()), maxSlippageBps: SLIPPAGE_BPS, swapType: 'exactIn', wrapAndUnwrapSol: false, }, await loadRouterContext(rpc, inputs.inputMint, inputs.outputMint) ); if (routes.length === 0) { console.log('No KSwap route found for', inputs.inputMint, '->', inputs.outputMint); } return routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); } function midPrice(route: RouteOutput) { const amounts = route.amountsExactIn!; const amountIn = new Decimal(amounts.amountIn.toString()).div(new Decimal(10).pow(route.inputTokenDecimals!)); const amountOut = new Decimal(amounts.amountOut.toString()).div(new Decimal(10).pow(route.outputTokenDecimals!)); return amountOut.div(amountIn); } const quoter = async (inputs: SwapInputs) => { const [bestRoute] = await getRoutes(inputs); return { priceAInB: midPrice(bestRoute), quoteResponse: bestRoute }; }; const swapper = async (inputs: SwapInputs) => (await getRoutes(inputs)).map((route) => { const routeIxs = route.instructions!; return { preActionIxs: [], swapIxs: [ ...routeIxs.createInAtaIxs, ...routeIxs.wrapSolIxs, ...routeIxs.swapIxs, ...routeIxs.unwrapSolIxs, ...routeIxs.createOutAtaIxs, ], lookupTables: route.lookupTableAccounts ?? [], quote: { priceAInB: midPrice(route), quoteResponse: route }, }; }); ``` > [!WARNING] > > `priceAInB` must be the mid price (`amountOut / amountIn`, each in token units), before slippage. The SDK applies `slippagePct` itself, so a guaranteed or minimum-out price counts slippage twice and sizes the position wrong. `getBestRoute` currently returns no routes, so use `getAllRoutes`, which in kswap-sdk 2.9.0 takes the router context as a second argument. **Step 6** ### Build the Repay Routes The SDK builds one candidate transaction per swap route: flash borrow, repay the debt, withdraw TSLAx, swap it to USDC, repay the flash loan. ```typescript theme={"theme":"css-variables"} const routes = await getRepayWithCollIxs({ owner: signer, kaminoMarket: market!, debtReserveAddress: debtReserve.address, collReserveAddress: collReserve.address, obligation: obligation!, referrer: none(), currentLedgerInstant: await getCurrentLedgerInstant(rpc), repayAmount: REPAY_AMOUNT, isClosingPosition: false, slippagePct: new Decimal(SLIPPAGE_BPS / 100), scopeRefreshIx, budgetAndPriorityFeeIxs: getComputeBudgetAndPriorityFeeIxs(MAX_COMPUTE_UNITS), quoter, swapper, useV2Ixs: true, }); ``` > [!NOTE] > > `slippagePct` also sizes the flash loan, so the worst-case swap fill still covers the repay. To repay all the debt and close the position, set `isClosingPosition` to `true`. **Step 7** ### Fetch Lookup Tables Fetch Kamino's lookup tables for each candidate transaction, one request per candidate. ```typescript theme={"theme":"css-variables"} async function getKaminoLookupTables(instructions: Instruction[]) { const addresses = [ ...new Set(instructions.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), ]; const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addresses }), }); if (!lutResponse.ok) { console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); } const { lutAddresses } = await lutResponse.json(); return fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); } ``` > [!NOTE] > > `/luts/find-minimal` takes one transaction's worth of addresses (between 64 and 128), so a single request for all candidates is rejected. **Step 8** ### Pick the Route That Fits Compress each candidate with its route's lookup tables and Kamino's, then take the best-output one that fits in a transaction. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const candidates = await Promise.all( routes.map(async (route) => { const lookupTables = [...route.lookupTables, ...(await getKaminoLookupTables(route.ixs))]; const lookupTableAddresses: Record = Object.fromEntries( lookupTables.map((lut) => [lut.address, lut.data.addresses]) ); return pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(route.ixs, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) ); }) ); const transactionMessage = candidates.find((candidate) => isTransactionMessageWithinSizeLimit(candidate)); if (!transactionMessage) { console.log(`None of the ${candidates.length} swap routes fit in one transaction`); } ``` > [!NOTE] > > The best-output route often has too many accounts to fit, even compressed: in testing only one or two of five to ten routes did. The slippage setting covers the gap between the best route's quote and the one sent. **Step 9** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage!); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Repay with collateral successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The debt is reduced by selling TSLAx collateral, with no USDC needed in the wallet. # Multiply Repay with xStocks Source: https://docs.kamino.com/build/developers/multiply/operations/repay-xstocks Repay debt on leveraged xStocks positions to reduce leverage and lower liquidation risk Repaying debt on a multiply position reduces your outstanding debt balance, lowers your LTV (Loan-to-Value) ratio, and improves position health. This example shows how to repay USDC debt on a TSLAx multiply position using the Klend SDK. ## Multiply Repay with xStocks Repay debt on a TSLAx multiply position to reduce leverage and improve position health. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, MultiplyObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. ```typescript theme={"theme":"css-variables"} const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const obligation = await market!.getObligationByWallet(signer.address, new MultiplyObligation(collMint, debtMint, PROGRAM_ID)); if (!obligation) { console.log('No Multiply position found for', signer.address); } ``` **Step 4** ### Build Repay Instructions Repay USDC debt on the Multiply position from the USDC in the wallet. ```typescript theme={"theme":"css-variables"} const debtReserve = market!.getExistingFloatRateReserveByMint(debtMint); const repayAction = await KaminoAction.buildRepayTxns({ kaminoMarket: market!, amount: new BN(5_000_000), reserveAddress: debtReserve.address, owner: signer, obligation: obligation!, useV2Ixs: true, scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!TIP] > > To repay all the debt, pass `new BN(U64_MAX)` as the amount (`U64_MAX` is exported by the SDK); the wallet needs the full debt in USDC. To repay by selling collateral instead, use [Repay with Collateral](/build/developers/multiply/operations/repay-collateral). **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(repayAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Multiply repay successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The USDC debt is reduced, lowering the position's LTV and leverage. ### Borrow and Multiply SDK Methods | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral while the position stays under its borrow limit | | `getWithdrawWithLeverageIxs` | Shrink the position and withdraw | Take value out while keeping the position's LTV; leverage stays the same | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | > [!NOTE] > > **Multiply operations** use `MultiplyObligation`. **Vanilla operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. # Multiply Withdraw with xStocks Source: https://docs.kamino.com/build/developers/multiply/operations/withdraw-xstocks Withdraw collateral from leveraged xStocks positions after repaying debt Withdrawing collateral from a multiply position unlocks your equity. With debt still open, the position must stay under its borrow limit. > [!NOTE] > > This operation uses `buildWithdrawTxns`: no swap and no debt repaid. To take value out of a position that still has debt while keeping its leverage, use `getWithdrawWithLeverageIxs`. ## Multiply Withdraw with xStocks Withdraw TSLAx collateral from a multiply position after all debt has been repaid. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, MultiplyObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. ```typescript theme={"theme":"css-variables"} const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const obligation = await market!.getObligationByWallet(signer.address, new MultiplyObligation(collMint, debtMint, PROGRAM_ID)); if (!obligation) { console.log('No Multiply position found for', signer.address); } ``` **Step 4** ### Build Withdrawal Instructions Withdraw TSLAx collateral from the Multiply position. ```typescript theme={"theme":"css-variables"} const collReserve = market!.getExistingFloatRateReserveByMint(collMint); const withdrawAction = await KaminoAction.buildWithdrawTxns({ kaminoMarket: market!, amount: new BN(1_250_000), reserveAddress: collReserve.address, owner: signer, obligation: obligation!, useV2Ixs: true, scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!NOTE] > > TSLAx uses 8 decimals, so `1_250_000` is 0.0125 TSLAx. With debt still open, the withdrawal raises the position's LTV and must keep it under the borrow limit. To withdraw all of it, pass `new BN(U64_MAX)` as the amount once the debt is repaid. **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(withdrawAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Multiply withdraw successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The TSLAx collateral is back in the wallet. ### Borrow and Multiply SDK Methods | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral while the position stays under its borrow limit | | `getWithdrawWithLeverageIxs` | Shrink the position and withdraw | Take value out while keeping the position's LTV; leverage stays the same | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | > [!NOTE] > > **Multiply operations** use `MultiplyObligation`. **Vanilla operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. # Multiply Source: https://docs.kamino.com/build/developers/multiply/overview Understanding how Multiply creates leveraged positions through atomic looping with flash loans ## What is Multiply? Multiply creates leveraged positions in a single atomic transaction by automating the looping process through flash loans. Instead of manually executing 8-10 separate deposit-borrow-swap cycles, Multiply collapses the entire leverage-building process into one transaction that either succeeds completely or reverts with no state changes. ### Borrow and Multiply SDK Methods | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid | | `getWithdrawWithLeverageIxs` | Deleverage and withdraw | Sell collateral to repay debt and receive remaining value in wallet | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | > [!NOTE] > > **Multiply operations** use `MultiplyObligation`. **Standard borrow operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. ### Borrow and Multiply: Rust Crate Helpers The Rust [`klend-interface`](https://crates.io/crates/klend-interface) crate exposes the lending primitives and flash loans, but does not include leveraged combo helpers. | Helper | Operation | When to Use | | - | - | - | | `helpers::flash::flash_loan` | Atomic flash borrow + repay pair | Building any flash-loan-based flow | | `ObligationContext.repay` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `ObligationContext.withdraw` | Withdraw collateral | Withdrawing collateral after debt is repaid | > [!NOTE] > > Leveraged combo operations (`getDepositWithLeverageIxs`, `getWithdrawWithLeverageIxs`, `getRepayWithCollIxs`) are **not** available in the Rust crate — they bundle flash loans with KSwap routing, which only the TypeScript SDK builds. *** ## SDK vs API vs Rust Crate: What's Available Understanding which operations are reachable from the SDK, the API, and the Rust crate is critical for building Multiply integrations. | Operation | SDK | API | Rust Crate | Notes | | - | - | - | - | - | | **Flash Loans** | Available | Not available | Available | Atomic transactions — SDK or Rust crate | | **Multiply Deposit (with KSwap)** | Required | Not available | Not available | Leveraged positions with swap routing — SDK only | | **Standard Borrow Operations** | Available | Available | Available | Deposit, borrow, repay, withdraw across SDK / API / Rust | | **Position Data** | Available | Available | Available | Read obligation data via any path | | **Market Reserve Data** | Available | Available | Limited | APYs, utilization, liquidity via SDK or API | ## Flash Loans A flash loan is an uncollateralized loan that must be borrowed and fully repaid within the same transaction block. This atomic property makes flash loans risk-free for the protocol. ### Flash Loan Properties | Property | Description | | - | - | | **Collateral Required** | None — uncollateralized | | **Repayment Window** | Same transaction block | | **Failure Behavior** | Entire transaction reverts (no state changes) | | **Fee** | 0.001% per transaction | | **Risk to Protocol** | Zero — atomicity guarantees repayment or reversion | > [!NOTE] > > If a flash loan cannot be repaid — due to slippage, insufficient liquidity, or any other failure — the entire transaction reverts. No intermediate state is committed to the blockchain. *** ## Looping: Manual vs Atomic Looping is the process of repeatedly depositing collateral, borrowing against it, and reinvesting the borrowed funds to amplify exposure. The method determines risk, cost, and execution complexity. ### Comparison Table | Aspect | Manual Looping | Atomic Looping (Multiply) | | - | - | - | | **Transaction Count** | 8-10 separate transactions | 1 atomic transaction | | **Price Exposure** | Exposed to price changes between each step | No exposure — all steps execute atomically | | **Slippage Risk** | Slippage on each swap individually | Single consolidated slippage check | | **Gas Costs** | Higher — multiple transactions | Lower — single transaction | | **Execution Risk** | High — any step can fail independently | Low — all-or-nothing execution | | **Time to Complete** | Minutes (dependent on block confirmations) | Single block (\~400ms on Solana) | | **Complexity** | Requires manual coordination of steps | Fully automated | > [!WARNING] > > Manual looping exposes you to market price movements between transactions. If the collateral asset price drops or borrow rates spike mid-loop, you may end up with a worse position than intended — or fail to complete the loop entirely. *** ## The Multiply Transaction Flow Multiply executes leverage creation in a precise sequence of steps within a single atomic transaction. **1. Flash Borrow** Protocol borrows the required debt token amount (e.g., SOL) via flash loan. No collateral is required. **2. Swap to Collateral** Flash-borrowed funds are swapped into the target collateral asset (e.g., SOL → JitoSOL) using Kamino Swap (KSwap) with multi-DEX routing for optimal execution. **3. Deposit Collateral** The full collateral amount (user deposit + swapped amount) is deposited into Kamino Lend as collateral. **4. Borrow Against Collateral** With collateral deposited, the protocol borrows the debt token against the collateral position. **5. Repay Flash Loan** Borrowed funds are used to repay the flash loan plus the 0.001% fee. **6. Position Established** Net result: Leveraged position with amplified collateral exposure and outstanding debt balance recorded on Kamino Lend. > [!NOTE] > > All steps execute in a single transaction. If any step fails (slippage exceeds tolerance, insufficient liquidity, etc.), the entire transaction reverts and no position is created. *** ## eMode (Elevation Mode) eMode enables significantly higher leverage for correlated asset pairs by raising the maximum permitted LTV ratio. ### How eMode Works Standard lending markets limit LTV to protect against price divergence between collateral and debt. When both assets are highly correlated (e.g., JitoSOL and SOL), price divergence risk is minimal — both assets move together. eMode reflects this reduced risk by permitting higher LTV ratios. ### eMode Leverage Comparison | Mode | Asset Pair | Max LTV | Max Leverage | Use Case | | - | - | - | - | - | | **Standard** | SOL / USDC | 75% | 4x | Uncorrelated assets | | **eMode (Main)** | mSOL, bSOL, JupSOL / SOL | \~87% | \~7.7x | Correlated LST/SOL pairs | | **eMode (Jito)** | JitoSOL / SOL | 90% | 10x | JitoSOL-specific correlation | | **No eMode** | JLP / USDC | 67% | \~3.2x | Uncorrelated (JLP is basket of assets) | > [!WARNING] > > Higher LTV from eMode means a smaller buffer between your operating LTV and liquidation threshold. Operating near maximum eMode leverage requires continuous monitoring of the yield spread (collateral yield minus borrow rate). ### Why Correlation Matters **Correlated pairs (LST/SOL)**: When SOL price moves, both JitoSOL and SOL debt move proportionally. Your LTV ratio stays relatively stable regardless of SOL's USD price. **Uncorrelated pairs (JLP/USDC)**: JLP value fluctuates with crypto markets while USDC stays flat. Price drops in SOL/ETH/BTC directly increase your LTV, creating liquidation risk independent of borrow rates. # Feeds Source: https://docs.kamino.com/build/developers/oracle/data/feeds Inspect a Scope feed's configuration, chain metadata, and oracle mappings ## Reading Feed Internals Beyond prices, the Scope SDK exposes the wiring behind a feed: its top-level `Configuration` account, the per-hop metadata for a scope chain (provider plus oracle type), and the raw per-slot oracle mappings. ### Feed Configuration A feed's `Configuration` holds the admin and the accounts it owns: `oraclePrices`, `oracleMappings`, `tokensMetadata`, and `oracleTwaps`. ```typescript icon="typescript" feedConfiguration theme={"theme":"css-variables"} import { createSolanaRpc } from '@solana/kit'; import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const rpc = createSolanaRpc(RPC_ENDPOINT); const scope = new Scope('mainnet-beta', rpc); const [configAddress, config] = await scope.getSingleFeedConfiguration({ config: SCOPE_MAINNET_HUBBLE_FEED.configuration, }); console.log('Config account:', configAddress); console.log({ admin: config.admin.toString(), adminCached: config.adminCached.toString(), oraclePrices: config.oraclePrices.toString(), oracleMappings: config.oracleMappings.toString(), tokensMetadata: config.tokensMetadata.toString(), oracleTwaps: config.oracleTwaps.toString(), }); ``` [View Code](https://github.com/Kamino-Finance/scope-sdk) > [!NOTE] > > List every feed on the Scope program with `scope.getAllConfigurations()`. ### Chain Metadata (what backs a price) `getChainMetadata` returns one entry per hop of a scope chain, telling you which provider serves the price and which oracle type produces it (one of about 40 kinds, including `PythPull`, `ScopeTwap`, `SplStake`, `DiscountToMaturity`, `MostRecentOf`, and `CappedFloored`). ```typescript icon="typescript" chainMetadata theme={"theme":"css-variables"} import { createSolanaRpc } from '@solana/kit'; import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const CHAIN = [0, 65535, 65535, 65535]; // SOL/USD, single-hop const rpc = createSolanaRpc(RPC_ENDPOINT); const scope = new Scope('mainnet-beta', rpc); const metadata = await scope.getChainMetadata( { config: SCOPE_MAINNET_HUBBLE_FEED.configuration }, CHAIN, ); metadata.forEach((m, hop) => { console.log(`hop ${hop}: ${m.name} (${m.simpleName})`); console.log(` provider: ${m.provider} | oracleType: ${m.oracleType}`); console.log(` nestedOracles: ${JSON.stringify(m.nestedOracles)}`); }); ``` > [!NOTE] > > The oracle type is chosen by the feed admin at config time (`updateFeedMapping`). This call only inspects what is already set. For the curator-facing configuration side, see [Scope Oracle Types](/curators/markets/scope-oracle-types). ### Oracle Mappings (raw per-slot wiring) `getOracleMappings` returns the raw per-slot wiring behind every price in the feed. Where `getChainMetadata` humanizes one chain's hops, the mappings expose every slot: the source account Scope reads, the oracle type discriminant, TWAP smoothing config, and the Reference Price Check slot. ```typescript icon="typescript" oracleMappings theme={"theme":"css-variables"} import { createSolanaRpc } from '@solana/kit'; import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const NONE = 65535; const rpc = createSolanaRpc(RPC_ENDPOINT); const scope = new Scope('mainnet-beta', rpc); const m = await scope.getOracleMappings({ config: SCOPE_MAINNET_HUBBLE_FEED.configuration, }); // First 6 slots. m.priceInfoAccounts.slice(0, 6).forEach((acct, slot) => { console.log({ slot, source: acct.toString(), oracleType: m.priceTypes[slot], twapEnabled: m.twapEnabledBitmask[slot].bitmask !== 0, refPriceSlot: m.refPrice[slot] === NONE ? 'none' : m.refPrice[slot], }); }); ``` > [!NOTE] > > `65535` is the unset sentinel throughout. `refPrice` is the slot an incoming price is sanity-checked against, the Reference Price Check feature described in [Scope Oracle Types](/curators/markets/scope-oracle-types). ## Additional Resources > [card] [SDK Repository](https://github.com/Kamino-Finance/scope-sdk) > [card] [Scope Oracle Types](/curators/markets/scope-oracle-types) # Prices Source: https://docs.kamino.com/build/developers/oracle/data/prices Read Scope oracle prices on-chain via the SDK or off-chain via REST ## Reading Scope Prices Scope serves prices two ways. On-chain, the `OraclePrices` account holds a fixed 512-slot array of dated prices and the SDK reads it directly. Off-chain, the Kamino REST endpoint serves the same prices pre-aggregated and keyed by mint, with no RPC or SDK required. ### Read All Prices > [tab] TypeScript > > Direct on-chain read of every populated slot in a feed. > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc } from '@solana/kit'; > import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; > import Decimal from 'decimal.js'; > > const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; > > const rpc = createSolanaRpc(RPC_ENDPOINT); > const scope = new Scope('mainnet-beta', rpc); > > const oraclePrices = await scope.getSingleOraclePrices({ > config: SCOPE_MAINNET_HUBBLE_FEED.configuration, > }); > > // Fixed-size array; a slot is unset when its price value is 0. > const populated = oraclePrices.prices > .map((p, index) => ({ index, p })) > .filter(({ p }) => p.price.value.toString() !== '0'); > > console.log(`Feed ${SCOPE_MAINNET_HUBBLE_FEED.oraclePrices}: ${populated.length} populated of ${oraclePrices.prices.length}`); > > populated.slice(0, 10).forEach(({ index, p }) => { > const price = new Decimal(p.price.value.toString()).div(new Decimal(10).pow(Number(p.price.exp))); > const updated = new Date(Number(p.unixTimestamp) * 1000).toISOString(); > console.log(` [${index}] ${price.toString()} (updated ${updated})`); > }); > ``` > > [View Code](https://github.com/Kamino-Finance/scope-sdk) > > A price is `value / 10^exp`; freshness comes from `lastUpdatedSlot` and `unixTimestamp` on the same dated price. `getSingleOraclePrices` accepts the feed by its configuration account, its `OraclePrices` pubkey, or its PDA seed. > [tab] API > > The same prices, pre-aggregated and keyed by mint. No RPC required. > > ```typescript theme={"theme":"css-variables"} > const API = 'https://api.kamino.finance/oracles/prices?source=scope'; > > type ScopePrice = { mint: string; name: string; price: string; timestamp: string; maxAgeInSeconds: string }; > const rows: ScopePrice[] = await (await fetch(API)).json(); > > console.log(`Scope prices: ${rows.length}`); > rows.slice(0, 10).forEach((r) => console.log(` ${r.name}: ${r.price} (${r.mint})`)); > ``` ### Get a Single Token Price > [tab] TypeScript > > A token's USD price is resolved by a "scope chain": up to 4 slot indices, padded with `65535`. One index means a direct price; several means a derived price (for example TOKEN/SOL then SOL/USD). > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc } from '@solana/kit'; > import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; > > const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; > const CHAIN = [0, 65535, 65535, 65535]; // SOL/USD, slot 0, single-hop > > const rpc = createSolanaRpc(RPC_ENDPOINT); > const scope = new Scope('mainnet-beta', rpc); > > const oraclePrices = await scope.getSingleOraclePrices({ > config: SCOPE_MAINNET_HUBBLE_FEED.configuration, > }); > if (!Scope.isScopeChainValid(CHAIN)) console.log('Chain is not valid:', CHAIN); > > const { price, timestamp } = await scope.getPriceFromChain(CHAIN, oraclePrices); > const ageSec = Math.floor(Date.now() / 1000) - timestamp.toNumber(); > > console.log(`Price: ${price.toString()}`); > console.log(`Updated: ${new Date(timestamp.toNumber() * 1000).toISOString()} (${ageSec}s ago)`); > ``` > > [View Code](https://github.com/Kamino-Finance/scope-sdk) > > The calling program supplies the scope chain. A klend reserve, for example, stores it on its token config; Scope just resolves it against the feed's price list. Sentinel slots (`65535`) are skipped. > [tab] API > > Filter the price list by mint. No scope chain to walk. > > ```typescript theme={"theme":"css-variables"} > const SOL_MINT = 'So11111111111111111111111111111111111111112'; > const API = 'https://api.kamino.finance/prices?source=scope'; > > type Price = { usdPrice: string; token: string; mint: string }; > const rows: Price[] = await (await fetch(API)).json(); > > const sol = rows.find((r) => r.mint === SOL_MINT); > if (!sol) console.log('Mint not found in price list:', SOL_MINT); > > console.log(`${sol?.token}: $${sol?.usdPrice}`); > ``` ### Get Token Price History Past prices for a single token, keyed by mint or symbol. API only, with no on-chain equivalent: the `OraclePrices` account holds only the current value per slot, so history is served off-chain. ```typescript theme={"theme":"css-variables"} const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; const API = `https://api.kamino.finance/prices/history?token=${USDC_MINT}&frequency=day&start=2026-06-01T00:00:00Z&end=2026-06-10T00:00:00Z`; // Each point is a [usdPrice, unixSeconds] pair, ordered oldest to newest. type PricePoint = [price: string, timestamp: number]; const points: PricePoint[] = await (await fetch(API)).json(); console.log(`History points: ${points.length}`); points.slice(0, 5).forEach(([price, ts]) => console.log(` ${new Date(ts * 1000).toISOString()}: $${price}`), ); ``` `frequency` is `minute`, `hour`, or `day`; omit `start`/`end` and the endpoint returns a default recent window (about the last day) at the chosen frequency. See the [Get token price history](/build/api-reference/oracle/token-prices-history) reference for the full parameter list. ## Types > [tab] ScopeDatedPrice > > Returned by `getPriceFromChain`. A resolved price plus its freshness. > > ```typescript theme={"theme":"css-variables"} > type ScopeDatedPrice = { > price: Decimal; > timestamp: BN; > }; > ``` > [tab] OraclePrices > > The on-chain account holding 512 dated prices. > > ```typescript theme={"theme":"css-variables"} > type OraclePrices = { > prices: DatedPrice[]; // length 512 > }; > > type DatedPrice = { > price: { value: BN; exp: BN }; > lastUpdatedSlot: BN; > unixTimestamp: BN; > }; > ``` ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Repository](https://github.com/Kamino-Finance/scope-sdk) # Refresh Prices Source: https://docs.kamino.com/build/developers/oracle/operations/refresh Build and send the permissionless Scope refresh instruction for one or more price slots ## Refresh Prices Scope prices are pushed on-chain by permissionless "crank" transactions: anyone can sign and send a refresh, no admin authority required. The Scope SDK builds one instruction that refreshes the specified token slots for a feed. This is the instruction Multiply and flash-loan flows bundle in front of a leverage operation so reserves read fresh prices. **Step 1** ### Import Dependencies Import the Scope SDK plus the Solana Kit transaction-building helpers and a keypair loader. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from "@kamino-finance/scope-sdk"; ``` **Step 2** ### Configure Constants and Initialize Scope Set the keypair path, RPC endpoints, and the slot indices to refresh. ```typescript theme={"theme":"css-variables"} 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"; // Slot indices to refresh on the Hubble feed: SOL/USD EMA, daoSOL stake rate, MPLX/SOL TWAP. const TOKENS = [52, 10, 41]; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const scope = new Scope("mainnet-beta", rpc); ``` **Step 3** ### Build the Refresh Instruction `refreshPriceListIx` returns one instruction that refreshes the listed slots, or `null` if there is nothing to refresh. Slots whose prices are pushed by the oracle provider, such as the Pyth Lazer feeds in slots 0, 1, and 2, can't be refreshed with this instruction and are skipped. If every listed slot is skipped, the result is `null`. ```typescript theme={"theme":"css-variables"} const ix = await scope.refreshPriceListIx( { config: SCOPE_MAINNET_HUBBLE_FEED.configuration }, TOKENS, ); if (!ix) console.log(`Nothing to refresh for tokens [${TOKENS}]`); console.log(`Built refresh ix: program ${ix?.programAddress}, ${ix?.accounts?.length ?? 0} accounts`); ``` > [!NOTE] > > The refresh is permissionless: any wallet can pay fees and send it. The Scope program writes the new dated prices to the feed's `OraclePrices` account. **Step 4** ### Build, Sign, and Send Transaction Compose the v0 transaction, sign, verify it fits the size limit, then send and confirm. ```typescript theme={"theme":"css-variables"} const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions([ix!], m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Refresh successful! Signature:", signature); ``` > [!TIP] > > The refresh is complete. The targeted slots now have fresh prices and timestamps on-chain. #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from "@kamino-finance/scope-sdk"; 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 TOKENS = [52, 10, 41]; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const scope = new Scope("mainnet-beta", rpc); const ix = await scope.refreshPriceListIx( { config: SCOPE_MAINNET_HUBBLE_FEED.configuration }, TOKENS, ); if (!ix) console.log(`Nothing to refresh for tokens [${TOKENS}]`); const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions([ix!], m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Refresh successful! Signature:", signature); ``` # Oracle Source: https://docs.kamino.com/build/developers/oracle/overview Build with Scope, Kamino's on-chain oracle aggregator: read prices, inspect feed wiring, and refresh price slots ## Overview Scope is Kamino's oracle aggregation framework for on-chain pricing. The Scope TypeScript SDK and REST endpoints provide direct access to price data, feed configuration, and refresh instructions. In leverage and flash-loan flows, price refreshes are commonly included before execution so reserves and strategies read the latest market data. > [!NOTE] > > A Scope feed is a fixed-size account: each `OraclePrices` account holds 512 slots, and a token's USD price is resolved through a "scope chain" of up to 4 slot indices (padded with the sentinel `65535`). For the configuration side, read [Configure oracles](/curators/markets/configuring-oracles) and [Scope oracle types](/curators/markets/scope-oracle-types). ## Key Components of Oracle Integration > [card] Prices > > Read every populated slot in a feed, or resolve a single token via its scope chain. > [card] Feed Internals > > Inspect a feed's configuration, per-hop chain metadata, and per-slot oracle mappings. > [card] Refresh > > Build the permissionless refresh instruction that pushes fresh prices on-chain. ## Integration Options > [card] Scope TypeScript SDK > > On-chain reads against the Scope program plus the refresh-instruction builder. TypeScript only. > [card] REST API > > Off-chain aggregated Scope prices keyed by mint. Language-agnostic, no RPC required. ### Read all prices > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc } from '@solana/kit'; > import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; > import Decimal from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const scope = new Scope('mainnet-beta', rpc); > > const oraclePrices = await scope.getSingleOraclePrices({ > config: SCOPE_MAINNET_HUBBLE_FEED.configuration, > }); > > const populated = oraclePrices.prices > .map((p, index) => ({ index, p })) > .filter(({ p }) => p.price.value.toString() !== '0'); > > console.log(`${populated.length} populated of ${oraclePrices.prices.length} slots`); > populated.slice(0, 5).forEach(({ index, p }) => { > const price = new Decimal(p.price.value.toString()).div(new Decimal(10).pow(Number(p.price.exp))); > console.log(` [${index}] ${price.toString()}`); > }); > ``` > > [View Code](https://github.com/Kamino-Finance/scope-sdk) ### Get a single token price > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc } from '@solana/kit'; > import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const scope = new Scope('mainnet-beta', rpc); > > // SOL/USD lives at slot 0 of the Hubble feed. Single-hop chain padded with 65535. > const CHAIN = [0, 65535, 65535, 65535]; > > const oraclePrices = await scope.getSingleOraclePrices({ > config: SCOPE_MAINNET_HUBBLE_FEED.configuration, > }); > > const { price, timestamp } = await scope.getPriceFromChain(CHAIN, oraclePrices); > console.log(`Price: ${price.toString()} (updated ${new Date(timestamp.toNumber() * 1000).toISOString()})`); > ``` > > [View Code](https://github.com/Kamino-Finance/scope-sdk) ## What's Covered > [card] [Prices](/build/developers/oracle/data/prices) > > Read every populated slot in a feed, or resolve a single token via its scope chain. SDK plus REST. > [card] [Feed Internals](/build/developers/oracle/data/feeds) > > Feed configuration, per-hop chain metadata, and per-slot oracle mappings. > [card] [Refresh Prices](/build/developers/oracle/operations/refresh) > > Build and send the permissionless refresh instruction for one or more slots. ## Relevant Links > [card] [NPM SDK package](https://www.npmjs.com/package/@kamino-finance/scope-sdk) > > Install the Scope TypeScript SDK to read feeds and build refresh instructions. > [card] [Scope SDK repository](https://github.com/Kamino-Finance/scope-sdk) > > TypeScript SDK source and example scripts. > [card] [Oracle Architecture](/security/oracles) > > Scope, price protection, and manipulation resistance explained. > [card] [Scope Oracle Types](/curators/markets/scope-oracle-types) > > Specialized Scope oracle entry types for fixed-income, multi-source, pegged, and LST assets. # Overview Source: https://docs.kamino.com/build/developers/overview The Kamino SDK, API, and Rust crate provide access to Earn vaults and Borrow markets Users deposit assets into Earn vaults or supply them to Kamino's lending markets as collateral to borrow against. Developers can integrate the same flows using the SDK's composable methods for deposits, borrows, repayments, and withdrawals. > [!TIP] > > Using AI tools or building with LLMs? Use our [llms.txt](https://docs.kamino.com/llms.txt) for a structured index of the docs, and [skill.md](https://docs.kamino.com/skill.md) for Kamino's full API and SDK capability reference. ## Integrate Kamino Developers can integrate Kamino using the REST API, the TypeScript SDK, or the Rust interface crate. > [card] [REST API](https://api-docs.kamino.com/) > > REST API for vault lists, performance metrics, user positions, and transaction history. > [card] [TypeScript SDK](https://github.com/Kamino-Finance/klend-sdk) > > Compose on-chain transactions for deposits, borrows, repayments, and withdrawals. > [card] [Rust Interface Crate](https://crates.io/crates/klend-interface) > > Lightweight instruction builder for Rust bots and on-chain CPI. ## Kamino Products > [card] [Borrow Markets](/build/borrow/index) > > Earn by supplying assets > [card] [Earn Vaults](/build/earn/index) > > Earn interest on assets ## Getting Started Set up your development environment: **1. Install SDK** Install the Klend TypeScript SDK and Solana Kit packages. ```bash theme={"theme":"css-variables"} npm i @kamino-finance/klend-sdk @solana/kit ``` **2. Setup the RPC (optional)** Use a private RPC for reliability. Public RPCs are often rate-limited and can cause transaction failures. > [!NOTE] > > Multiple RPC providers are available. [Helius](https://www.helius.dev) is one option. @solana/kit is used for standardized RPC interactions with improved type safety and better handling of Solana transactions. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc } from '@solana/kit'; const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com"); ``` **3. Create or Import Wallet (optional)** Choose a method to create or import a wallet for signing transactions. > [!NOTE] > > Alternatively, create a wallet using a browser wallet provider like [Phantom](https://phantom.app/). **Create with CLI** Use the Solana CLI to generate a new keypair file. ```bash theme={"theme":"css-variables"} solana-keygen new -o wallet.json ``` **Create with Solana Kit** Generate a new keypair programmatically using the Solana Kit. ```typescript theme={"theme":"css-variables"} import { generateKeyPairSigner } from "@solana/kit"; const signer = await generateKeyPairSigner(); console.log("address: ", signer.address); ``` **Import Keypair File** Import a wallet from an existing keypair file. ```typescript theme={"theme":"css-variables"} import { createKeyPairSignerFromBytes } from '@solana/kit'; import fs from 'fs'; import path from 'path'; import os from 'os'; const resolvedPath = path.resolve( filePath.startsWith("~") ? filePath.replace("~", os.homedir()) : filePath ); const loadedKeyBytes = Uint8Array.from( JSON.parse(fs.readFileSync(resolvedPath, "utf8")) ); const signer = await createKeyPairSignerFromBytes(loadedKeyBytes); console.log(signer.address); ``` **Import Private Key** Import a private key from an existing browser wallet. ```typescript theme={"theme":"css-variables"} import { createKeyPairSignerFromBytes } from '@solana/kit'; // Get your private key from browser wallet (as Uint8Array or number array) const privateKey = new Uint8Array([/* your private key bytes */]); const signer = await createKeyPairSignerFromBytes(privateKey); ``` # Kamino Portfolio API Source: https://docs.kamino.com/build/developers/portfolio/index Fetch a wallet's entire Kamino footprint across lending, multiply, leverage, liquidity, earn, private credit, and staking The Portfolio API returns a wallet's positions across **every Kamino product in one call**: lending, multiply, leverage, liquidity, earn, private credit, and staking. It's the single request a dashboard makes to paint the whole picture, plus a companion endpoint for pending farm rewards. > [!NOTE] > > **Source data, composed by you.** Positions arrive already valued (each carries `value`/`price`), but portfolio-wide totals, net worth, and PnL are intentionally left to client composition, so you build exactly the rollups your app needs. See [Calculate portfolio totals](/build/developers/portfolio/response#calculate-portfolio-totals). > [!NOTE] > > **No API key required.** All Portfolio endpoints are public on `https://api.kamino.finance`. ## Endpoints | Method | Endpoint | Returns | | - | - | - | | `GET` | `/portfolio/{pubkey}` | All positions across the seven product sections | | `GET` | `/portfolio/{pubkey}/rewards` | Pending farm rewards across all products | See the full field reference in [Portfolio response](/build/developers/portfolio/response). ## What you can build * **Portfolio dashboards:** render every position a wallet holds across Kamino from one request. * **Liquidation and health monitors:** read `ltv` against `liquidationLtv` on lending, multiply, and leverage positions to alert before liquidation. * **Net-worth and PnL tools:** sum `netValue` across sections and convert to USD with the [Oracle prices](/build/developers/oracle/data/prices) endpoint. * **Reward trackers:** surface pending farm rewards across lending, borrowing, and liquidity in one view. ## Quickstart Fetch a wallet's full portfolio and count positions per product. ```typescript theme={"theme":"css-variables"} const WALLET = 'YOUR_WALLET_ADDRESS'; // replace with your wallet pubkey const API = 'https://api.kamino.finance'; const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); console.log('Timestamp:', portfolio.timestamp); const products = ['lending', 'multiply', 'leverage', 'liquidity', 'earn', 'privateCredit', 'staking'] as const; products.forEach((p) => console.log(` ${p}: ${(portfolio[p] || []).length} position(s)`)); ``` > [!NOTE] > > Numeric fields are returned as **strings** (for example `"0.38"`, `"100.05"`). Parse them with `parseFloat` before doing math. ## Next steps > [card] [Portfolio response](/build/developers/portfolio/response) > > Full field reference for every product section, plus runnable examples. > [card] [API reference](/build/api-reference/portfolio/portfolio-source-data) > > The raw OpenAPI spec for both Portfolio endpoints. > [card] [Oracle prices](/build/developers/oracle/data/prices) > > Convert position amounts to USD when composing totals. > [card] [Rewards](/build/developers/portfolio/response#pending-rewards) > > Read and aggregate pending farm rewards across products. # Kamino Portfolio Data Source: https://docs.kamino.com/build/developers/portfolio/response Query Portfolio API response fields across all seven Kamino products The portfolio response returns a top level object with a timestamp, a `sections` object that reports indexing status and freshness for each product, and one array for each product section. Each position is returned already valued, with its own value and price included. > [!TIP] > > Run the endpoints live in the API playground: [portfolio](/build/api-reference/portfolio/portfolio-source-data) and [pending rewards](/build/api-reference/portfolio/portfolio-rewards). ## Parameters | Parameter | In | Required | Description | | - | - | - | - | | `pubkey` | path | Yes | Wallet address (base58). | | `programId` | query | No | KLend program ID to scope results. | ## Response object | Field | Type | Description | | - | - | - | | `timestamp` | string | ISO timestamp of the response. | | `sections` | object | Indexing status and freshness per product. See [Section state](#shared-building-blocks). | | `lending` `multiply` `leverage` | array | Borrow-side obligations (see the **Position fields** tabs). | | `liquidity` `earn` `privateCredit` `staking` | array | The remaining product positions. | ## Position fields by product > [tab] Lending, Multiply & Leverage > > One entry per obligation. The `tag` field distinguishes the kind (`Vanilla`, `Multiply`, and so on). Multiply and leverage entries add `depositMint` and `borrowMint`. > > | Field | Type | Description | > | - | - | - | > | `obligation` | string | Obligation pubkey. | > | `market` | string | Lending market pubkey. | > | `tag` | string | Obligation kind (`Vanilla`, `Multiply`, …). | > | `netValue` | string | USD net value (deposits minus borrows). | > | `totalDepositValue` | string | USD value of all deposits. | > | `totalBorrowValue` | string | USD value of all borrows. | > | `ltv` | string | Current loan-to-value (for example `"0.38"`). | > | `maxLtv` | string | Maximum borrowing LTV. | > | `liquidationLtv` | string | LTV at which liquidation triggers. | > | `leverage` | string | Position leverage (for example `"1.56"`). | > | `deposits` | array | Deposited assets ([Token object](#shared-building-blocks)). | > | `borrows` | array | Borrowed assets ([Token object](#shared-building-blocks)). | > | `depositMint` | string | Multiply and leverage only: collateral mint. | > | `borrowMint` | string | Multiply and leverage only: debt mint. | > [tab] Liquidity > > | Field | Type | Description | > | - | - | - | > | `strategy` | string | Strategy pubkey. | > | `shareMint` | string | Share token mint. | > | `shares` | string | Share balance. | > | `netValue` | string | USD value of the position. | > | `tokenA` | object | First pool token ([Token object](#shared-building-blocks)). | > | `tokenB` | object | Second pool token ([Token object](#shared-building-blocks)). | > [tab] Earn & Private Credit > > | Field | Type | Description | > | - | - | - | > | `vault` | string | Vault pubkey. | > | `tokenMint` | string | Deposit token mint. | > | `symbol` | string | Token symbol. | > | `name` | string | Vault name (for example `Steakhouse USDC`). | > | `netValue` | string | USD value of the position. | > | `shares` | string | Vault shares held. | > | `amount` | string | Underlying token amount. | > [tab] Staking > > | Field | Type | Description | > | - | - | - | > | `mint` | string | Staked token mint. | > | `symbol` | string | Token symbol. | > | `farm` | string | Farm pubkey. | > | `amount` | string | Staked amount. | > | `value` | string | USD value. | > | `price` | string | Token price. | ## Shared building blocks > [accordion] Token object (deposits, borrows, tokenA, tokenB) > > Entries in `deposits`, `borrows`, and the liquidity `tokenA` / `tokenB` share a common shape, with a few context-specific extras. > > | Field | Type | Description | > | - | - | - | > | `mint` | string | Token mint. | > | `symbol` | string | Token symbol. | > | `amount` | string | Token amount. | > | `value` | string | USD value. | > | `price` | string | Token price. | > | `reserve` | string | Reserve pubkey (deposits and borrows). | > | `maxLtv` | string | Deposits only: collateral max LTV. | > | `liquidationLtv` | string | Deposits only: collateral liquidation LTV. | > | `borrowFactor` | string | Borrows only: borrow factor. | > [accordion] Section state (sections object) > > Each product key in `sections` reports whether the wallet has data and how fresh it is. A section with `indexed: false` has no data for this wallet. > > | Field | Type | Description | > | - | - | - | > | `indexed` | boolean | `false` means no data for this wallet and product. | > | `positionsRefreshedOn` | string \| null | ISO timestamp positions were last refreshed. | > | `pricesRefreshedOn` | string \| null | ISO timestamp prices were last refreshed. | > | `errors` | array | Errors encountered while loading this section. | ## Pending rewards `GET /portfolio/{pubkey}/rewards` returns pending farm rewards across products: a `timestamp` and a `farms` array. Each farm entry lists its pending `rewards`. | Field | Type | Description | | - | - | - | | `farm` | string | Farm pubkey. | | `userState` | string | User state pubkey. | | `delegatee` | string | Wallet pubkey. | | `positionType` | string | Human-readable source (for example `Borrow Markets`). | | `activeStakeAmount` | string | Active staked amount. | | `tokenMints` | array | Associated token mints. | | `rewards` | array | Pending rewards (see below). | > [accordion] Reward entry fields > > | Field | Type | Description | > | - | - | - | > | `mint` | string | Reward token mint. | > | `amount` | string | Pending amount. | > | `index` | number | Reward index. | > | `type` | number | Reward type. | > | `tokenProgram` | string | Token program of the reward mint. | ## Examples **Step 1** ### Calculate LTV and liquidation headroom for each lending position Compare `ltv` against `liquidationLtv` to measure how close a position is to liquidation. ```typescript icon="typescript" lendingPositions theme={"theme":"css-variables"} const WALLET = 'YOUR_WALLET_ADDRESS'; const API = 'https://api.kamino.finance'; const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); (portfolio.lending || []).forEach((pos, i) => { const ltvPct = (parseFloat(pos.ltv) * 100).toFixed(2); const liqPct = (parseFloat(pos.liquidationLtv) * 100).toFixed(2); const headroom = ((parseFloat(pos.liquidationLtv) - parseFloat(pos.ltv)) * 100).toFixed(2); console.log(`\n--- Lending position ${i + 1} (${pos.tag}) ---`); console.log(` Net value: $${parseFloat(pos.netValue).toFixed(2)}`); console.log(` LTV: ${ltvPct}% (liq ${liqPct}%)`); console.log(` Headroom: ${headroom}% before liquidation`); }); ``` **Step 2** ### List earn vault positions with shares and USD value ```typescript icon="typescript" earnPositions theme={"theme":"css-variables"} const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); (portfolio.earn || []).forEach((pos) => { console.log({ vault: pos.vault, name: pos.name, symbol: pos.symbol, shares: pos.shares, amount: parseFloat(pos.amount).toFixed(6), netValueUsd: '$' + parseFloat(pos.netValue).toFixed(4), }); }); ``` **Step 3** ### Check which product sections are stale or failed to load Use `sections` to decide whether positions are stale or a product failed to load. ```typescript icon="typescript" sectionFreshness theme={"theme":"css-variables"} const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); const now = Date.now(); Object.entries(portfolio.sections).forEach(([name, sec]) => { if (!sec.indexed) return console.log(`${name}: not indexed`); const age = (ts) => (ts ? ((now - new Date(ts).getTime()) / 60_000).toFixed(1) + 'm ago' : 'never'); const errors = sec.errors.length ? ` ⚠ ${sec.errors.length} error(s)` : ''; console.log(`${name}: positions ${age(sec.positionsRefreshedOn)}, prices ${age(sec.pricesRefreshedOn)}${errors}`); }); ``` **Step 4** ### List pending farm rewards across all products ```typescript icon="typescript" pendingRewards theme={"theme":"css-variables"} const rewards = await (await fetch(`${API}/portfolio/${WALLET}/rewards?rewardTypes=0,1,2,3`)).json(); const farms = rewards.farms || []; console.log(`Pending rewards across ${farms.length} farm(s):`); farms.forEach((f) => { console.log(`\n Farm: ${f.farm} (${f.positionType})`); (f.rewards || []).forEach((r) => console.log(` ${r.amount} (mint ${r.mint}, type ${r.type})`)); }); ``` **Step 5** ### Sum total portfolio value and break it down per product Sum `netValue` from each section (and `value` for staking) for a portfolio total, then break it down per product. ```typescript icon="typescript" totalValue theme={"theme":"css-variables"} const portfolio = await (await fetch(`${API}/portfolio/${WALLET}`)).json(); const products = ['lending', 'multiply', 'leverage', 'liquidity', 'earn', 'privateCredit', 'staking']; let totalValue = 0; const breakdown = []; products.forEach((p) => { const positions = portfolio[p] || []; const value = positions.reduce((sum, pos) => sum + parseFloat((p === 'staking' ? pos.value : pos.netValue) || '0'), 0); totalValue += value; if (positions.length) breakdown.push({ product: p, value, count: positions.length }); }); console.log(`Total portfolio value: $${totalValue.toFixed(2)}`); breakdown .sort((a, b) => b.value - a.value) .forEach((b) => console.log(` ${b.product}: $${b.value.toFixed(2)} (${b.count} position(s))`)); ``` ## Calculate portfolio totals The API returns valued positions but no portfolio-wide rollups, so you compose them: * **Net worth:** sum `netValue` across every section, except **staking**, which exposes `value` instead. Multiply and leverage `netValue` is already deposits minus borrows, so totals reflect real equity. * **USD conversion:** positions carry `value` and `price`, but for any raw amounts you price yourself, use the [Oracle prices](/build/developers/oracle/data/prices) endpoint. # Farms Source: https://docs.kamino.com/build/developers/rewards/data/farm-state Read farm state, discover farms, and compute reward APY with the Kamino Farms SDK ## Reading Farm Data > [!NOTE] > > A **delegated** farm (for example a klend reserve farm or a kvault farm) has no stake-token mint of its own. A delegate authority stakes on users' behalf, so `farmState.token.mint` is empty and `farmState.delegateAuthority` is set. A **non-delegated** farm owns its stake token, so `farmState.token` gives the stake mint and decimals. For the TypeScript shapes used below, see [Farm Types](#farm-types). > [accordion] Farm state fields reference > > A `FarmState` account exposes the values below. An `Address` field set to the default pubkey means it is unused, for example `strategyId` and `vaultId` on a farm attached to neither. > > | Field | Type | Description | > | - | - | - | > | `token` | `TokenInfo` | Stake token: mint, decimals, and token program. Empty on delegated farms. | > | `rewardInfos` | `RewardInfo[]` | Fixed-size array of reward slots. Only slots with a real mint are active. | > | `numRewardTokens` | `BN` | Count of active reward tokens. | > | `totalStakedAmount` | `BN` | Total tokens staked and earning rewards, in raw units. | > | `isFarmDelegated` | `number` | `1` when the farm is delegated, so a delegate authority stakes on users' behalf. | > | `isFarmFrozen` | `number` | `1` when the farm is frozen and no new deposits are allowed. | > | `delegateAuthority` | `Address` | The delegate that stakes for users. Set only on delegated farms. | > | `depositWarmupPeriod` | `number` | Seconds between a deposit and when it starts earning. `0` if unused. | > | `withdrawalCooldownPeriod` | `number` | Seconds between unstaking and being able to withdraw. | > | `depositCapAmount` | `BN` | Maximum total stake the farm accepts, in raw units. | > | `lockingDuration` | `BN` | Deposit lockup length, in the farm's time unit. | > | `lockingEarlyWithdrawalPenaltyBps` | `BN` | Penalty in basis points for withdrawing before the lockup ends. | > | `scopePrices` | `Address` | Scope oracle prices account the farm reads for reward accrual. | > | `strategyId` | `Address` | kliquidity strategy this farm is attached to. Default if none. | > | `vaultId` | `Address` | kvault this farm is attached to. Default if none. | > | `farmVault` | `Address` | Token account that holds the staked tokens. | ### Get Farm State Live on-chain read of a single farm: stake token, totals, time gates, and reward slots. ```typescript icon="typescript" getFarmState theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { fetchFarmState, DEFAULT_PUBLIC_KEY } from '@kamino-finance/farms-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const FARM = address('9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6'); // farm address const rpc = createSolanaRpc(RPC_ENDPOINT); const { data: farmState } = await fetchFarmState(rpc, FARM); console.log('Delegated:', farmState.isFarmDelegated === 1); console.log('Frozen:', farmState.isFarmFrozen === 1); console.log('Total staked (raw):', farmState.totalStakedAmount.toString()); console.log('Deposit warmup (s):', farmState.depositWarmupPeriod); console.log('Withdrawal cooldown (s):', farmState.withdrawalCooldownPeriod); // rewardInfos is a fixed-size array; only slots with a real mint are active. const activeRewards = farmState.rewardInfos.filter( (r) => r.token.mint.toString() !== DEFAULT_PUBLIC_KEY.toString(), ); activeRewards.forEach((r) => console.log({ mint: r.token.mint.toString(), decimals: Number(r.token.decimals), rewardsAvailable: r.rewardsAvailable.toString(), rewardType: r.rewardType, }), ); ``` [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > `depositWarmupPeriod` and `withdrawalCooldownPeriod` are farm-level time gates in seconds, stored on the farm state with no REST equivalent. The cooldown is the wait between unstaking and being able to withdraw. To load several farms at once, use `fetchAllFarmState(rpc, [addr, ...])`. On a non-delegated farm, `farms.getStakedAmountForFarm(FARM)` returns the total staked in share units, already divided by the stake-token decimals. ### Find Farms Discover farms by their stake token, or batch-load known farm addresses in one call. ```typescript icon="typescript" findFarms theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { Farms } from '@kamino-finance/farms-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const STAKE_MINT = address('AYUjc3a3QQUiLE6jP7V29UMeUZGADdtiVxhSjoLcqYwr'); // stake (share) token mint const FARM_ADDRESSES = [ address('8qcg3HogEhVXXUxkgbgcC8wtZgVwRjQsaxiCMYRpkvKA'), address('DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi'), ]; const rpc = createSolanaRpc(RPC_ENDPOINT); const farms = new Farms(rpc); // Discover by stake mint (non-delegated farms only). const byMint = await farms.getFarmsForMint(STAKE_MINT); byMint.forEach((f) => console.log('farm:', f.key.toString())); // Batch-load specific farms by address (any farm type). const byKeys = await farms.getAllFarmStatesByPubkeys(FARM_ADDRESSES); byKeys.forEach((f) => console.log({ farm: f.key.toString(), delegated: f.farmState.isFarmDelegated === 1, rewardCount: f.farmState.numRewardTokens.toString(), }), ); ``` [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > `getFarmsForMint` filters on the stake-token mint, so it only finds non-delegated farms. Delegated farms leave that field empty, so you get their address elsewhere (a reserve's `farmCollateral` / `farmDebt`, or a kvault's `vaultFarm`; see the locating table in the [overview](/build/developers/rewards/overview)) and batch-load them with `getAllFarmStatesByPubkeys`. ### Get Incentive APY Compute a farm's reward APY two ways: the easy path for a strategy farm, and the generic path for any farm. ```typescript icon="typescript" getIncentiveApy theme={"theme":"css-variables"} import { createSolanaRpc, address, type Address } from '@solana/kit'; import { Farms } from '@kamino-finance/farms-sdk'; import { Kamino } from '@kamino-finance/kliquidity-sdk'; import Decimal from 'decimal.js'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const ORACLE_PRICES_URL = 'https://api.kamino.finance/oracles/prices?source=scope'; const FARM = address('DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi'); // farm address const STRATEGY = address('CjUsr5w686AHi1qNHYUggz6jGoAPwKVA4K9v4hQaGtzu'); // strategy address const STAKE_DECIMALS = 6; // strategy share token decimals const rpc = createSolanaRpc(RPC_ENDPOINT); const farms = new Farms(rpc); const kamino = new Kamino('mainnet-beta', rpc); // 1. Easy path: APY straight from the strategy, no prices to supply. const byStrategy = await farms.getRewardsAPYForStrategy(STRATEGY); console.log('Total incentives APY:', (byStrategy.totalIncentivesApy * 100).toFixed(4) + '%'); // 2. Generic path: supply reward prices and the staked-token price yourself. const rows: Array<{ mint: string; price: string }> = await (await fetch(ORACLE_PRICES_URL)).json(); const priceByMint = new Map(rows.map((r) => [r.mint, new Decimal(r.price)])); const getPrice = async (mint: Address): Promise => priceByMint.get(mint.toString()) ?? new Decimal(0); const stakedTokenPrice = await kamino.getStrategySharePrice(STRATEGY); const [farmAndKey] = await farms.getAllFarmStatesByPubkeys([FARM]); const calc = await farms.calculateFarmIncentivesApy( farmAndKey, getPrice, stakedTokenPrice, STAKE_DECIMALS, ); calc.incentivesStats.forEach((s) => console.log({ mint: s.rewardMint.toString(), apy: (s.incentivesApy * 100).toFixed(4) + '%', yearlyRewards: s.yearlyRewards.toString(), }), ); ``` [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > `getRewardsAPYForStrategy` is the easy path for a strategy farm: the SDK derives the share price and reward prices itself. `calculateFarmIncentivesApy` is generic and works for any farm, but you supply a `getPrice` callback for reward tokens (from the oracle endpoint) plus the staked-token price (from the kliquidity SDK, since a strategy share is not an oracle-tracked asset). The two totals land close to each other. ### Simulate APY After Stake or Unstake Project how the incentive APY changes after a hypothetical stake or unstake, reusing the `getPrice` callback and `stakedTokenPrice` from the previous example. ```typescript icon="typescript" simulateApy theme={"theme":"css-variables"} const totalStaked = await farms.getStakedAmountForFarm(FARM); // total staked, in share units const [farmAndKey] = await farms.getAllFarmStatesByPubkeys([FARM]); const scenarios = [ { label: 'baseline (no change)', delta: new Decimal(0) }, { label: 'stake +100% (double the pool)', delta: totalStaked }, { label: 'unstake -50% (halve the pool)', delta: totalStaked.div(2).neg() }, ]; for (const s of scenarios) { const sim = await farms.simulateFarmIncentivesApy( farmAndKey, s.delta, getPrice, stakedTokenPrice, STAKE_DECIMALS, ); console.log(`${s.label}: ${(sim.totalIncentivesApy * 100).toFixed(4)}%`); } ``` [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > `stakedTokenDelta` is in share units (the decimal share amount, not raw lamports) and adds to the current total stake. A positive delta simulates staking more, so the same rewards spread over a bigger pool and APY falls. A negative delta simulates unstaking, so APY rises. ## Farm Types TypeScript shapes used by the Farms SDK for farm reads. > [tab] FarmState > > On-chain farm account. Fetched with `fetchFarmState` / `fetchAllFarmState`. See the collapsible field reference at the top of the page for what each value means. > > ```typescript theme={"theme":"css-variables"} > class FarmState { > token: TokenInfo; // stake token (empty on delegated farms) > rewardInfos: RewardInfo[]; // fixed-size; unused slots have a default mint > numRewardTokens: BN; > totalStakedAmount: BN; > isFarmDelegated: number; // 1 when delegated > isFarmFrozen: number; > delegateAuthority: Address; // set on delegated farms > depositWarmupPeriod: number; // seconds > withdrawalCooldownPeriod: number; // seconds > depositCapAmount: BN; > scopePrices: Address; > strategyId: Address; > vaultId: Address; > } > ``` > [tab] TokenInfo > > A token's mint, decimals, and owning token program. > > ```typescript theme={"theme":"css-variables"} > class TokenInfo { > mint: Address; > decimals: BN; > tokenProgram: Address; > } > ``` > [tab] RewardInfo > > One reward slot on a farm. > > ```typescript theme={"theme":"css-variables"} > class RewardInfo { > token: TokenInfo; // reward token mint and decimals > rewardsVault: Address; > rewardsAvailable: BN; > minClaimDurationSeconds: BN; // claim cooldown for this reward > rewardType: number; > rewardsPerSecondDecimals: number; > } > ``` > [tab] FarmIncentives > > Per-reward APY breakdown returned by the APY methods. > > ```typescript theme={"theme":"css-variables"} > type FarmIncentives = { > incentivesStats: IncentiveRewardStats[]; > totalIncentivesApy: number; > }; > > type IncentiveRewardStats = { > rewardMint: Address; > rewardDecimals: Decimal; > incentivesApy: number; > yearlyRewards: Decimal; > dailyRewards: Decimal; > hasRewardAvailable: boolean; > }; > ``` ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Repository](https://github.com/Kamino-Finance/farms-sdk) # User Position Source: https://docs.kamino.com/build/developers/rewards/data/user-position Read a wallet's farm stake, lockup and cooldown status, and pending rewards with the Kamino Farms SDK ## Reading User Position Data > [!NOTE] > > The reads below use the non-delegated helpers (`getUserForUndelegatedFarm`, `getUserStateKeyForUndelegatedFarm`). For delegated farms, position accounting lives in the parent program (klend or kvault). For the TypeScript shapes returned here, see [Position Types](#position-types). ### Get All Positions Live read of every farm a wallet is staked in, with the active stake valued in USD. ```typescript icon="typescript" getAllPositions theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { Farms, DEFAULT_PUBLIC_KEY } from '@kamino-finance/farms-sdk'; import { Kamino } from '@kamino-finance/kliquidity-sdk'; import Decimal from 'decimal.js'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const USER = address('YOUR_WALLET_ADDRESS'); // user address const rpc = createSolanaRpc(RPC_ENDPOINT); const farms = new Farms(rpc); const kamino = new Kamino('mainnet-beta', rpc); const now = new Decimal(Math.floor(Date.now() / 1000)); const sumStake = (m: Map): Decimal => [...m.values()].reduce((acc, v) => acc.add(v), new Decimal(0)); const positions = await farms.getAllFarmsForUser(USER, now); if (positions.size === 0) console.log('No farm positions for', USER); for (const [farm, userFarm] of positions) { const activeShares = sumStake(userFarm.activeStakeByDelegatee); const isStrategyFarm = userFarm.strategyId.toString() !== DEFAULT_PUBLIC_KEY.toString(); const price = isStrategyFarm ? await kamino.getStrategySharePrice(userFarm.strategyId) : null; console.log({ farm: farm.toString(), activeShares: activeShares.toString(), valueUsd: price ? '$' + activeShares.mul(price).toFixed(2) : 'n/a', }); } ``` [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > `getAllFarmsForUser` returns a `Map` with stake in share units. For USD value, multiply active shares by the share price. On a strategy farm the share price comes from the kliquidity SDK, because the stake token is a strategy share rather than an oracle-tracked asset. ### Get Position Detail Deep detail for one farm: active stake plus pending deposit and withdrawal, with their unlock timestamps. ```typescript icon="typescript" getPositionDetail theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { Farms } from '@kamino-finance/farms-sdk'; import { Kamino } from '@kamino-finance/kliquidity-sdk'; import Decimal from 'decimal.js'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const FARM = address('9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6'); // non-delegated farm const STRATEGY = address('ErNSr9mSDC9EkuvfUZQvedqTFiybvRsF838tiXn3Ektd'); // for the share price const USER = address('YOUR_WALLET_ADDRESS'); // user address const rpc = createSolanaRpc(RPC_ENDPOINT); const farms = new Farms(rpc); const kamino = new Kamino('mainnet-beta', rpc); const now = new Decimal(Math.floor(Date.now() / 1000)); const sumStake = (m: Map): Decimal => [...m.values()].reduce((acc, v) => acc.add(v), new Decimal(0)); const tsToText = (ts: { toString(): string }): string => { const secs = Number(ts.toString()); return secs > 0 ? new Date(secs * 1000).toISOString() : 'none'; }; const userFarm = await farms.getUserForUndelegatedFarm(USER, FARM, now); const active = sumStake(userFarm.activeStakeByDelegatee); const pendingDeposit = sumStake(userFarm.pendingDepositStakeByDelegatee); const pendingWithdrawal = sumStake(userFarm.pendingWithdrawalUnstakeByDelegatee); const price = await kamino.getStrategySharePrice(STRATEGY); console.log({ activeStakeEarning: active.toString(), valueUsd: '$' + active.mul(price).toFixed(2), pendingDepositWarmingUp: pendingDeposit.toString(), becomesActiveAt: tsToText(userFarm.userState.pendingDepositStakeTs), pendingWithdrawalCoolingDown: pendingWithdrawal.toString(), withdrawableAt: tsToText(userFarm.userState.pendingWithdrawalUnstakeTs), }); ``` [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > Active stake earns rewards. Pending deposit is warming up and becomes active at `pendingDepositStakeTs`. Pending withdrawal is cooling down and becomes withdrawable at `pendingWithdrawalUnstakeTs`. The stake amounts come back in share units; the unlock timestamps live on the raw `userState`. ### Get Lockup and Cooldown A wallet's deposit lockup status on a farm: the full lockup period, how much the user has left, and when it frees up. ```typescript icon="typescript" getLockupAndCooldown theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { Farms } from '@kamino-finance/farms-sdk'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const FARM = address('DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi'); // non-delegated farm const USER = address('YOUR_WALLET_ADDRESS'); // user address const rpc = createSolanaRpc(RPC_ENDPOINT); const farms = new Farms(rpc); const nowSeconds = Math.floor(Date.now() / 1000); const { lockupRemainingDuration, farmLockupOriginalDuration, farmLockupExpiry } = await farms.getLockupDurationAndExpiry(FARM, USER, nowSeconds); const status = lockupRemainingDuration <= 0 ? 'unlocked' : `locked until ${new Date(farmLockupExpiry * 1000).toISOString()}`; console.log({ farmLockupPeriodSeconds: farmLockupOriginalDuration, remainingForUserSeconds: lockupRemainingDuration, status, }); ``` [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > `getLockupDurationAndExpiry` returns three values in seconds: the farm's full lockup period, how much of it this user has left, and the unix expiry timestamp. This is the deposit lockup. It is distinct from the per-unstake withdrawal cooldown shown in the position detail, which is driven by `pendingWithdrawalUnstakeTs` once you actually unstake. Use it to enable or disable a withdraw button and show a countdown. ### Get Pending Rewards A wallet's claimable rewards on a farm, per reward token, in tokens and USD, with whether each has cleared its claim cooldown. ```typescript icon="typescript" getPendingRewards theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { Farms, fetchFarmState, DEFAULT_PUBLIC_KEY } from '@kamino-finance/farms-sdk'; import Decimal from 'decimal.js'; const RPC_ENDPOINT = 'https://api.mainnet-beta.solana.com'; const ORACLE_PRICES_URL = 'https://api.kamino.finance/oracles/prices?source=scope'; const FARM = address('DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi'); // farm address const USER = address('YOUR_WALLET_ADDRESS'); // user address const rpc = createSolanaRpc(RPC_ENDPOINT); const farms = new Farms(rpc); const now = new Decimal(Math.floor(Date.now() / 1000)); const { data: farmState } = await fetchFarmState(rpc, FARM); const { userState } = await farms.getUserStateKeyForUndelegatedFarm(USER, FARM); const rows: Array<{ mint: string; price: string }> = await (await fetch(ORACLE_PRICES_URL)).json(); const priceByMint = new Map(rows.map((r) => [r.mint, new Decimal(r.price)])); // getOraclePrices reads the farm's on-chain Scope prices, which the rewards calc needs. const oraclePrices = await farms.getOraclePrices(farmState); const { userPendingRewardAmounts, hasReward } = farms.getUserPendingRewards( userState, farmState, now, oraclePrices, ); console.log('Has claimable reward:', hasReward); farmState.rewardInfos.forEach((info, i) => { const mint = info.token.mint; if (mint.toString() === DEFAULT_PUBLIC_KEY.toString()) return; const decimals = Number(info.token.decimals); const amount = userPendingRewardAmounts[i].div(new Decimal(10).pow(decimals)); if (amount.lte(0)) return; const price = priceByMint.get(mint.toString()); const minClaim = Number(info.minClaimDurationSeconds.toString()); const sinceClaim = now.toNumber() - Number(userState.lastClaimTs[i].toString()); const claimable = sinceClaim >= minClaim ? 'Yes' : `in ~${Math.ceil((minClaim - sinceClaim) / 60)}m`; console.log({ reward: mint.toString(), pending: amount.toString(), valueUsd: price ? '$' + amount.mul(price).toFixed(2) : 'n/a', claimable, }); }); ``` [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > `getUserPendingRewards` returns one pending amount per reward slot in raw units, plus a `hasReward` flag. Humanize each amount by its reward-token decimals and value it with the oracle endpoint. `getOraclePrices(farmState)` takes the `FarmState` object, not the address. A reward is claimable once `now` minus `lastClaimTs` has cleared the reward's `minClaimDurationSeconds`. ## Position Types TypeScript shapes returned by the Farms SDK for user position reads. > [tab] UserFarm > > A wallet's position in one farm, with stake in share units, grouped by delegatee. > > ```typescript theme={"theme":"css-variables"} > type UserFarm = { > userStateAddress: Address; > farm: Address; > stakedToken: Address; > activeStakeByDelegatee: Map; > pendingDepositStakeByDelegatee: Map; > pendingWithdrawalUnstakeByDelegatee: Map; > pendingRewards: PendingReward[]; > delegateAuthority: Address; > strategyId: Address; > userState: UserState; > }; > ``` > [tab] UserState > > On-chain user account. Stake amounts are WAD-scaled; timestamps are unix seconds. > > ```typescript theme={"theme":"css-variables"} > class UserState { > owner: Address; > farmState: Address; > isFarmDelegated: number; > activeStakeScaled: BN; > pendingDepositStakeScaled: BN; > pendingDepositStakeTs: BN; > pendingWithdrawalUnstakeScaled: BN; > pendingWithdrawalUnstakeTs: BN; > lastClaimTs: BN[]; // per reward slot > rewardsIssuedUnclaimed: BN[]; // per reward slot > } > ``` > [tab] PendingReward > > One reward token's pending amount on a position. > > ```typescript theme={"theme":"css-variables"} > type PendingReward = { > rewardTokenMint: Address; > rewardTokenProgramId: Address; > rewardType: number; > cumulatedPendingRewards: Decimal; > pendingRewardsByDelegatee: Map; > }; > ``` ## Additional Resources > [card] [API Examples](https://api-docs.kamino.com/) > [card] [SDK Repository](https://github.com/Kamino-Finance/farms-sdk) # Harvest Source: https://docs.kamino.com/build/developers/rewards/operations/harvest Claim all pending rewards from a Kamino farm ## Harvest Claim every pending reward token accrued on a farm to your wallet in one call. > [!NOTE] > > `claimForUserForFarmAllRewardsIx` walks every reward slot, skips any still under its claim cooldown, and returns one harvest instruction per claimable reward, plus an idempotent ATA-create instruction if the reward token account is missing. It reads on-chain Scope prices itself, so there is nothing to refresh. If the returned array is empty, nothing is past its cooldown to claim. **Step 1** ### Import Dependencies Import the packages for Solana RPC communication, Kit transaction building, the keypair loader, and the Farms SDK. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms } from "@kamino-finance/farms-sdk"; ``` **Step 2** ### Configure Constants and Initialize Set the keypair path, RPC endpoints, and target farm. Load the signer and initialize the farms client. ```typescript theme={"theme":"css-variables"} 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 FARM = address("DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi"); // non-delegated farm const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); ``` **Step 3** ### Build Harvest Instructions Build one harvest instruction per claimable reward. The payer signs and pays fees; the rewards land in the user's wallet. ```typescript theme={"theme":"css-variables"} const instructions = await farms.claimForUserForFarmAllRewardsIx( signer, // payer signer.address, // user (owner of the position) FARM, false, // isDelegated ); if (instructions.length === 0) console.log("Nothing to claim for", signer.address); ``` > [!NOTE] > > Pass `isDelegated: false` for a non-delegated farm. For a delegated klend or kvault farm, pass `true` and the obligation as a delegatee in the optional `delegatees` argument. See [Claim user rewards](/build/developers/borrow/rewards/claim-user-rewards) for the delegated case. **Step 4** ### Build, Sign, and Send Transaction Compose the v0 transaction, sign, verify it fits the size limit, then send and confirm. ```typescript theme={"theme":"css-variables"} const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Claim successful! Signature:", signature); ``` > [!TIP] > > The harvest is complete. Every reward token past its claim cooldown has been transferred to your wallet. #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms } from "@kamino-finance/farms-sdk"; 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 FARM = address("DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi"); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); const instructions = await farms.claimForUserForFarmAllRewardsIx( signer, signer.address, FARM, false, ); if (instructions.length === 0) console.log("Nothing to claim for", signer.address); const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Claim successful! Signature:", signature); ``` # Stake Source: https://docs.kamino.com/build/developers/rewards/operations/stake Stake share tokens into a Kamino farm ## Stake Stake a farm's share token to start earning rewards. Refresh the farm (and the user, if a position already exists) so reward accounting is current, then stake. > [!NOTE] > > This flow requires a non-delegated farm. `stakeIx` needs a `stakeTokenMint`, which delegated farms (klend reserve and kvault farms) do not have. The wallet needs SOL for fees plus the farm's stake token to stake. **Step 1** ### Import Dependencies Import the packages for Solana RPC communication, Kit transaction building, the Farms SDK, and the keypair loader. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms, fetchFarmState } from "@kamino-finance/farms-sdk"; import { getScopePricesFromFarm } from "@kamino-finance/farms-sdk/dist/utils/option"; import Decimal from "decimal.js"; ``` **Step 2** ### Configure Constants and Initialize Set the keypair path, RPC endpoints, target farm, stake token mint, and amount. Load the signer and initialize the farms client. ```typescript theme={"theme":"css-variables"} 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 FARM = address("9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6"); // non-delegated farm const STAKE_MINT = address("3EmfhZ3KUaYdwKZ9CwfGoKRqQqUV1MhSCVL5Ch7szX7e"); // the farm's stake token const STAKE_AMOUNT = new Decimal(0.02); // amount of shares to stake const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); ``` **Step 3** ### Load Farm State Fetch the farm account, read its Scope prices for the refresh instructions, and convert the stake amount to raw token units. ```typescript theme={"theme":"css-variables"} const { data: farmState } = await fetchFarmState(rpc, FARM); const scopePrices = getScopePricesFromFarm(farmState); const decimals = Number(farmState.token.decimals); const amountLamports = STAKE_AMOUNT.mul(new Decimal(10).pow(decimals)); ``` > [!NOTE] > > `stakeIx` takes the raw lamport amount (the share amount times 10^decimals). The on-chain program scales it up internally. **Step 4** ### Build Stake Instructions Check whether the wallet already has a user-state account, then assemble the instruction list: create the user state if needed, refresh, and stake. ```typescript theme={"theme":"css-variables"} const existing = await farms .getUserStateKeyForUndelegatedFarm(signer.address, FARM) .catch(() => null); const instructions = [ ...(existing ? [] : [await farms.createNewUserIx(signer, FARM)]), await farms.refreshFarmIx(FARM, scopePrices), ...(existing ? [await farms.refreshUserIx(existing.key, FARM, scopePrices)] : []), await farms.stakeIx(signer, FARM, amountLamports, STAKE_MINT, scopePrices), ]; ``` > [!NOTE] > > The Farms SDK exposes bare instruction builders that do not bundle a refresh, unlike klend. Prepend `refreshFarmIx` (and `refreshUserIx` for an existing position) so reward accounting is current before you stake. A first-time staker has no user-state account yet, so `createNewUserIx` creates it in the same transaction. **Step 5** ### Build, Sign, and Send Transaction Compose the v0 transaction, sign, verify it fits the size limit, then send and confirm. ```typescript theme={"theme":"css-variables"} const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Stake successful! Signature:", signature); ``` > [!TIP] > > The stake is complete. Your shares are staked, and rewards accrue once any deposit warmup period elapses. #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms, fetchFarmState } from "@kamino-finance/farms-sdk"; import { getScopePricesFromFarm } from "@kamino-finance/farms-sdk/dist/utils/option"; 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 FARM = address("9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6"); const STAKE_MINT = address("3EmfhZ3KUaYdwKZ9CwfGoKRqQqUV1MhSCVL5Ch7szX7e"); const STAKE_AMOUNT = new Decimal(0.02); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); const { data: farmState } = await fetchFarmState(rpc, FARM); const scopePrices = getScopePricesFromFarm(farmState); const decimals = Number(farmState.token.decimals); const amountLamports = STAKE_AMOUNT.mul(new Decimal(10).pow(decimals)); const existing = await farms .getUserStateKeyForUndelegatedFarm(signer.address, FARM) .catch(() => null); const instructions = [ ...(existing ? [] : [await farms.createNewUserIx(signer, FARM)]), await farms.refreshFarmIx(FARM, scopePrices), ...(existing ? [await farms.refreshUserIx(existing.key, FARM, scopePrices)] : []), await farms.stakeIx(signer, FARM, amountLamports, STAKE_MINT, scopePrices), ]; const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Stake successful! Signature:", signature); ``` # Unstake Source: https://docs.kamino.com/build/developers/rewards/operations/unstake Unstake share tokens from a Kamino farm ## Unstake Unstaking moves stake from active into pending withdrawal and starts the farm's withdrawal cooldown. After the cooldown elapses, call [Withdraw](/build/developers/rewards/operations/withdraw-unstaked) to move the tokens back to your wallet. Refresh first, then unstake. > [!NOTE] > > This flow requires an existing position on a non-delegated farm. The wallet needs SOL for fees. **Step 1** ### Import Dependencies Import the packages for Solana RPC communication, Kit transaction building, and the Farms SDK. `UserState` and `WAD` are used to scale the unstake amount. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms, fetchFarmState, fetchUserState } from "@kamino-finance/farms-sdk"; import { getScopePricesFromFarm } from "@kamino-finance/farms-sdk/dist/utils/option"; import { WAD } from "@kamino-finance/farms-sdk/dist/utils/utils"; import Decimal from "decimal.js"; ``` **Step 2** ### Configure Constants and Initialize Set the keypair path, RPC endpoints, target farm, and amount. Load the signer and initialize the farms client. ```typescript theme={"theme":"css-variables"} 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 FARM = address("9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6"); // non-delegated farm const UNSTAKE_AMOUNT = new Decimal(0.02); // amount of shares to unstake const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); ``` **Step 3** ### Load State and Scale the Amount Fetch the farm and the user state, then convert the unstake amount to WAD-scaled shares and clamp it to the on-chain active stake. ```typescript theme={"theme":"css-variables"} const { data: farmState } = await fetchFarmState(rpc, FARM); const existing = await farms .getUserStateKeyForUndelegatedFarm(signer.address, FARM) .catch(() => null); if (!existing) console.log("No position on this farm to unstake."); const scopePrices = getScopePricesFromFarm(farmState); const decimals = Number(farmState.token.decimals); const { data: userState } = await fetchUserState(rpc, existing!.key); const activeStakeScaled = new Decimal(userState.activeStakeScaled.toString()); const requestedScaled = UNSTAKE_AMOUNT.mul(new Decimal(10).pow(decimals)).mul(WAD); const amountScaled = Decimal.min(requestedScaled, activeStakeScaled); ``` > [!NOTE] > > `unstakeIx` takes WAD-scaled shares, not raw lamports like `stakeIx`. Scale with `UNSTAKE_AMOUNT * 10^decimals * WAD`, then clamp to `userState.activeStakeScaled` so you never request more than is staked. The clamp also handles dust and an "unstake all" request. **Step 4** ### Build Unstake Instructions Refresh the farm and user so reward accounting is current, then unstake. ```typescript theme={"theme":"css-variables"} const instructions = [ await farms.refreshFarmIx(FARM, scopePrices), await farms.refreshUserIx(existing!.key, FARM, scopePrices), await farms.unstakeIx(signer, FARM, amountScaled, scopePrices), ]; ``` **Step 5** ### Build, Sign, and Send Transaction Compose the v0 transaction, sign, verify it fits the size limit, then send and confirm. ```typescript theme={"theme":"css-variables"} const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Unstake successful! Signature:", signature); ``` > [!TIP] > > The unstake is complete. Your stake is now pending withdrawal and cooling down. Once the farm's withdrawal cooldown elapses, withdraw it back to your wallet. #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms, fetchFarmState, fetchUserState } from "@kamino-finance/farms-sdk"; import { getScopePricesFromFarm } from "@kamino-finance/farms-sdk/dist/utils/option"; import { WAD } from "@kamino-finance/farms-sdk/dist/utils/utils"; 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 FARM = address("9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6"); const UNSTAKE_AMOUNT = new Decimal(0.02); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); const { data: farmState } = await fetchFarmState(rpc, FARM); const existing = await farms .getUserStateKeyForUndelegatedFarm(signer.address, FARM) .catch(() => null); if (!existing) console.log("No position on this farm to unstake."); const scopePrices = getScopePricesFromFarm(farmState); const decimals = Number(farmState.token.decimals); const { data: userState } = await fetchUserState(rpc, existing!.key); const activeStakeScaled = new Decimal(userState.activeStakeScaled.toString()); const requestedScaled = UNSTAKE_AMOUNT.mul(new Decimal(10).pow(decimals)).mul(WAD); const amountScaled = Decimal.min(requestedScaled, activeStakeScaled); const instructions = [ await farms.refreshFarmIx(FARM, scopePrices), await farms.refreshUserIx(existing!.key, FARM, scopePrices), await farms.unstakeIx(signer, FARM, amountScaled, scopePrices), ]; const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Unstake successful! Signature:", signature); ``` # Withdraw Source: https://docs.kamino.com/build/developers/rewards/operations/withdraw-unstaked Withdraw unstaked tokens from a Kamino farm to your wallet ## Withdraw The second half of unwinding a position. After you [unstake](/build/developers/rewards/operations/unstake) and the farm's withdrawal cooldown elapses, the stake sits as pending withdrawal. This moves those tokens out of the farm vault back to your token account. > [!NOTE] > > This flow requires a non-delegated farm, since the instruction needs the stake token mint. No Scope prices or refresh are needed here, because it moves already-unstaked tokens and does not touch reward accounting. The instruction only succeeds on-chain once the withdrawal cooldown has elapsed; if there is nothing past cooldown, it fails. **Step 1** ### Import Dependencies Import the packages for Solana RPC communication, Kit transaction building, the keypair loader, and the Farms SDK. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms } from "@kamino-finance/farms-sdk"; ``` **Step 2** ### Configure Constants and Initialize Set the keypair path, RPC endpoints, target farm, and stake token mint. Load the signer and initialize the farms client. ```typescript theme={"theme":"css-variables"} 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 FARM = address("DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi"); // non-delegated farm const STAKE_MINT = address("AYUjc3a3QQUiLE6jP7V29UMeUZGADdtiVxhSjoLcqYwr"); // the farm's stake token const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); ``` **Step 3** ### Build Withdraw Instruction Resolve the user-state key, then build the withdraw-unstaked instruction. The third argument is the farm address. ```typescript theme={"theme":"css-variables"} const { key: userState } = await farms.getUserStateKeyForUndelegatedFarm( signer.address, FARM, ); const instructions = [ await farms.withdrawUnstakedDepositIx(signer, userState, FARM, STAKE_MINT), ]; ``` **Step 4** ### Build, Sign, and Send Transaction Compose the v0 transaction, sign, verify it fits the size limit, then send and confirm. ```typescript theme={"theme":"css-variables"} const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Withdraw-unstaked successful! Signature:", signature); ``` > [!TIP] > > The withdrawal is complete. Your unstaked tokens have been transferred back to your wallet. #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, getSignatureFromTransaction, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, assertIsTransactionWithBlockhashLifetime, } from "@solana/kit"; import { parseKeypairFile } from "@kamino-finance/klend-sdk/dist/utils/signer"; import { Farms } from "@kamino-finance/farms-sdk"; 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 FARM = address("DXGwU8Ah7v6TBcc9ZjVmFxiLCMPgrxnsj4ZF7F8sWFxi"); const STAKE_MINT = address("AYUjc3a3QQUiLE6jP7V29UMeUZGADdtiVxhSjoLcqYwr"); const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); const farms = new Farms(rpc); const { key: userState } = await farms.getUserStateKeyForUndelegatedFarm( signer.address, FARM, ); const instructions = [ await farms.withdrawUnstakedDepositIx(signer, userState, FARM, STAKE_MINT), ]; const { value: blockhash } = await rpc .getLatestBlockhash({ commitment: "finalized" }) .send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (m) => setTransactionMessageFeePayerSigner(signer, m), (m) => setTransactionMessageLifetimeUsingBlockhash(blockhash, m), (m) => appendTransactionMessageInstructions(instructions, m), ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); assertIsTransactionWithBlockhashLifetime(signedTransaction); const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: "confirmed", skipPreflight: true, }); console.log("Withdraw-unstaked successful! Signature:", signature); ``` # Farms Source: https://docs.kamino.com/build/developers/rewards/overview Learn how to build with Kamino Farms, the rewards distribution layer for Kamino products ## Overview Kamino Farms is the rewards distribution layer for Kamino products. Farms distribute incentive tokens to depositors, suppliers, and borrowers across the protocol, including KMNO emissions on vaults and lending positions. The TypeScript SDK provides access to farm and user state, along with instructions to stake, unstake, and harvest rewards. > [!NOTE] > > Farms attached to lending positions and kvaults are **delegated**: position accounting lives in the parent program (klend or kvault), and unstake is a two-step flow gated by a cooldown. Read [Farm rewards](/curators/vaults/concepts/yield-and-fees#farm-rewards) for the conceptual model before integrating. ## Key Components of Farms Integration > [card] Farm State > > Decode a farm's reward tokens, per-second emission rates, total staked amount, cooldown period, and scope-oracle binding. > [card] User Positions > > Read a wallet's stake across one or many farms, pending rewards per reward token, and pending-unstake cooldown status. > [card] Stake & Claim > > Initialize user state, stake / unstake (with cooldown handling), and harvest accrued rewards in one or all reward tokens. ## Locating a Farm Address The SDK reads any farm given its pubkey. Three places that pubkey can come from: | Source | Where to look | | - | - | | **CDN** | `https://cdn.kamino.finance/resources.json`, under `mainnet-beta.extraFarms`. | | **Klend reserve fields** | A reserve account's `state.farmCollateral` (supply side) or `state.farmDebt` (borrow side) field. | | **Kvault state** | A kvault account's `state.vaultFarm` field. List vaults at `https://api.kamino.finance/kvaults/vaults`. | ## Integration Options > [card] TypeScript SDK > > On-chain reads and transaction building for stake, unstake, harvest, and user-state management. TS/JS only. ### Stake > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { Farms, fetchFarmState } from '@kamino-finance/farms-sdk'; > import { getScopePricesFromFarm } from '@kamino-finance/farms-sdk/dist/utils/option'; > import Decimal from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const farms = new Farms(rpc); > > const FARM = address('9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6'); > const STAKE_MINT = address('3EmfhZ3KUaYdwKZ9CwfGoKRqQqUV1MhSCVL5Ch7szX7e'); > > const { data: farmState } = await fetchFarmState(rpc, FARM); > > const scopePrices = getScopePricesFromFarm(farmState); > const amountLamports = new Decimal(0.02).mul( > new Decimal(10).pow(Number(farmState.token.decimals)), > ); > > // Refresh the farm so reward accounting is current, then stake. > const instructions = [ > await farms.refreshFarmIx(FARM, scopePrices), > await farms.stakeIx(signer, FARM, amountLamports, STAKE_MINT, scopePrices), > ]; > > console.log('Stake Instructions:', instructions); > ``` > > [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > For the full stake flow including first-time user-state creation and transaction confirmation, see [Stake](/build/developers/rewards/operations/stake). ### Unstake > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { Farms, fetchFarmState } from '@kamino-finance/farms-sdk'; > import { getScopePricesFromFarm } from '@kamino-finance/farms-sdk/dist/utils/option'; > import { WAD } from '@kamino-finance/farms-sdk/dist/utils/utils'; > import Decimal from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const farms = new Farms(rpc); > > const FARM = address('9wSacmF3KBr4HmgncxXeBhDdw4Shi2X9ETAFzWJS6pG6'); > > const { data: farmState } = await fetchFarmState(rpc, FARM); > > const scopePrices = getScopePricesFromFarm(farmState); > const { key: userStateKey } = > await farms.getUserStateKeyForUndelegatedFarm(signer.address, FARM); > > // unstakeIx takes WAD-scaled shares. Refresh the farm and user, then unstake. > const amountScaled = new Decimal(0.02) > .mul(new Decimal(10).pow(Number(farmState.token.decimals))) > .mul(WAD); > > const instructions = [ > await farms.refreshFarmIx(FARM, scopePrices), > await farms.refreshUserIx(userStateKey, FARM, scopePrices), > await farms.unstakeIx(signer, FARM, amountScaled, scopePrices), > ]; > > console.log('Unstake Instructions:', instructions); > ``` > > [View Code](https://github.com/Kamino-Finance/farms-sdk) > [!NOTE] > > Unstaking starts the withdrawal cooldown. After it elapses, withdraw the tokens back to your wallet. See [Unstake](/build/developers/rewards/operations/unstake). ## What's Covered > [card] [Farms](/build/developers/rewards/data/farm-state) > > Read farm state, discover farms, and compute or simulate incentive APY. > [card] [User Position Data](/build/developers/rewards/data/user-position) > > Fetch a wallet's stake, lockup and cooldown status, and pending rewards. > [card] [Stake](/build/developers/rewards/operations/stake) > > Initialize user state and stake share tokens into a farm. > [card] [Unstake](/build/developers/rewards/operations/unstake) > > Unstake into pending withdrawal and start the cooldown. > [card] [Withdraw](/build/developers/rewards/operations/withdraw-unstaked) > > Move unstaked tokens back to your wallet after the cooldown. > [card] [Harvest](/build/developers/rewards/operations/harvest) > > Claim all pending reward tokens in one transaction. ## Relevant Links > [card] [Farms SDK repository](https://github.com/Kamino-Finance/farms-sdk) > > TypeScript SDK source, on-chain program docs, and example scripts. > [card] [KFarms program](https://github.com/Kamino-Finance/kfarms) > > Rust source for the on-chain farms program. > [card] [NPM SDK package](https://www.npmjs.com/package/@kamino-finance/farms-sdk) > > Install the TypeScript SDK to integrate reward operations. > [card] [Farm Rewards Concepts](/curators/vaults/concepts/yield-and-fees#farm-rewards) > > Vault Farm, Autocompound, Insurance Pool farm, and cooldowns explained. # Create a distributor Source: https://docs.kamino.com/build/distributors/create-a-distributor /kamino-api.json post /distributors Registers a distributor under a unique name and returns its generated 5-character memo code. Private (authorized) API access only, please add a basic auth header to your request. # Every KLend position of the wallets tagged with a memo code Source: https://docs.kamino.com/build/distributors/every-klend-position-of-the-wallets-tagged-with-a-memo-code /kamino-api.json get /klend/distributors/{code}/positions KLend only. A capital flow counts for a code only when its own transaction carried that code as a memo (same rule as KVault distributors). USD is the capital flow value at transaction time (Multiply netting kept); unpriced flows are left out of sums and counted in unpricedFlowCount. newWalletsOnly and newWallets mean no recorded capital flow on any product before the first tagged flow (historyStatus no-prior-recorded). A UTC start and end are required (at most 90 days); unknown parameters are ignored. Load protection: 120 requests a minute per credential (429), and database queries wait up to 5 s for a free slot (503 with Retry-After when they cannot start or hit the timeout; a timed-out request is answered with 503 for 60 s). Private (authorized) API access only, please add a basic auth header to your request. # Get distributor-tagged transactions of a vault Source: https://docs.kamino.com/build/distributors/get-distributor-tagged-transactions-of-a-vault /kamino-api.json get /kvaults/vaults/{pubkey}/distributor-transactions Cursor-paginated list of deposits into and withdrawals out of a Kamino Earn vault whose transaction carried a distributor code, newest first. One row per instruction, so a transaction with several gives several rows. Private (authorized) API access only, please add a basic auth header to your request. # Get per-wallet totals for a distributor code Source: https://docs.kamino.com/build/distributors/get-per-wallet-totals-for-a-distributor-code /kamino-api.json get /kvaults/distributors/{code}/wallets For each wallet that transacted under this distributor code in the range: the total amount per token and direction, deposits and withdrawals as separate lines. Private (authorized) API access only, please add a basic auth header to your request. # Get transactions tagged with a distributor code Source: https://docs.kamino.com/build/distributors/get-transactions-tagged-with-a-distributor-code /kamino-api.json get /kvaults/distributors/{code}/transactions Cursor-paginated list of deposits and withdrawals, across every Kamino Earn vault, whose transaction carried this distributor code, newest first. One row per instruction. Private (authorized) API access only, please add a basic auth header to your request. # Get transactions tagged with a distributor code on one vault Source: https://docs.kamino.com/build/distributors/get-transactions-tagged-with-a-distributor-code-on-one-vault /kamino-api.json get /kvaults/distributors/{code}/vaults/{vault}/transactions Cursor-paginated list of deposits into and withdrawals out of one Kamino Earn vault whose transaction carried this distributor code, newest first. One row per instruction. Private (authorized) API access only, please add a basic auth header to your request. # List distributors Source: https://docs.kamino.com/build/distributors/list-distributors /kamino-api.json get /distributors Every registered distributor with its memo code, newest first. Private (authorized) API access only, please add a basic auth header to your request. # One row per wallet with tagged KLend flows of a memo code Source: https://docs.kamino.com/build/distributors/one-row-per-wallet-with-tagged-klend-flows-of-a-memo-code /kamino-api.json get /klend/distributors/{code}/wallets KLend only. A capital flow counts for a code only when its own transaction carried that code as a memo (same rule as KVault distributors). USD is the capital flow value at transaction time (Multiply netting kept); unpriced flows are left out of sums and counted in unpricedFlowCount. newWalletsOnly and newWallets mean no recorded capital flow on any product before the first tagged flow (historyStatus no-prior-recorded). A UTC start and end are required (at most 90 days); unknown parameters are ignored. Load protection: 120 requests a minute per credential (429), and database queries wait up to 5 s for a free slot (503 with Retry-After when they cannot start or hit the timeout; a timed-out request is answered with 503 for 60 s). Private (authorized) API access only, please add a basic auth header to your request. # Tagged KLend flow totals of a memo code, grouped by groupBy Source: https://docs.kamino.com/build/distributors/tagged-klend-flow-totals-of-a-memo-code-grouped-by-groupby /kamino-api.json get /klend/distributors/{code}/flows KLend only. A capital flow counts for a code only when its own transaction carried that code as a memo (same rule as KVault distributors). USD is the capital flow value at transaction time (Multiply netting kept); unpriced flows are left out of sums and counted in unpricedFlowCount. newWalletsOnly and newWallets mean no recorded capital flow on any product before the first tagged flow (historyStatus no-prior-recorded). A UTC start and end are required (at most 90 days); unknown parameters are ignored. Load protection: 120 requests a minute per credential (429), and database queries wait up to 5 s for a free slot (503 with Retry-After when they cannot start or hit the timeout; a timed-out request is answered with 503 for 60 s). Private (authorized) API access only, please add a basic auth header to your request. # Tagged KLend flows of a memo code, newest first Source: https://docs.kamino.com/build/distributors/tagged-klend-flows-of-a-memo-code-newest-first /kamino-api.json get /klend/distributors/{code}/transactions KLend only. A capital flow counts for a code only when its own transaction carried that code as a memo (same rule as KVault distributors). USD is the capital flow value at transaction time (Multiply netting kept); unpriced flows are left out of sums and counted in unpricedFlowCount. newWalletsOnly and newWallets mean no recorded capital flow on any product before the first tagged flow (historyStatus no-prior-recorded). A UTC start and end are required (at most 90 days); unknown parameters are ignored. Load protection: 120 requests a minute per credential (429), and database queries wait up to 5 s for a free slot (503 with Retry-After when they cannot start or hit the timeout; a timed-out request is answered with 503 for 60 s). Private (authorized) API access only, please add a basic auth header to your request. # Totals of the tagged KLend flows of a memo code Source: https://docs.kamino.com/build/distributors/totals-of-the-tagged-klend-flows-of-a-memo-code /kamino-api.json get /klend/distributors/{code}/summary KLend only. A capital flow counts for a code only when its own transaction carried that code as a memo (same rule as KVault distributors). USD is the capital flow value at transaction time (Multiply netting kept); unpriced flows are left out of sums and counted in unpricedFlowCount. newWalletsOnly and newWallets mean no recorded capital flow on any product before the first tagged flow (historyStatus no-prior-recorded). A UTC start and end are required (at most 90 days); unknown parameters are ignored. Load protection: 120 requests a minute per credential (429), and database queries wait up to 5 s for a free slot (503 with Retry-After when they cannot start or hit the timeout; a timed-out request is answered with 503 for 60 s). Private (authorized) API access only, please add a basic auth header to your request. # Get a wallet earn activity feed Source: https://docs.kamino.com/build/earn/get-a-wallet-earn-activity-feed /kamino-api.json get /v3/earn/users/{userPubkey}/activity Get cursor-paginated vault and filtered lending deposits, direct and withdraw-queue withdrawals, and repayments. Lending obligations that owe debt now are left out with their whole history. # Get a wallet earn summary Source: https://docs.kamino.com/build/earn/get-a-wallet-earn-summary /kamino-api.json get /v3/earn/users/{userPubkey}/summary Get live vault and lending deposits, idle eligible holdings, APYs, and wallet-global lifetime interest by token for the requested obligation types. Pass Vanilla,Lending,LendingFixedRate for Earn products. Obligations that owe debt are left out. # Get Vault APYs Source: https://docs.kamino.com/build/earn/get-vault-apys Fetch 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. > [tab] API > > **Step 1** > > ### Fetch All Vaults > > Retrieve the list of all available vaults on Kamino. > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const response = await fetch(`${API_BASE_URL}/kvaults/vaults`); > const vaults = await response.json(); > ``` > > > [!NOTE] > > > > The `/kvaults/vaults` endpoint returns all vaults with basic information including vault addresses, token mints, and strategies. > > **Step 2** > > ### Get APY for Each Vault > > Fetch APY metrics for all vaults in parallel using the vault public keys. > > ```typescript theme={"theme":"css-variables"} > // 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)}%`); > }); > ``` > > > [!NOTE] > > > > 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). > > > [!TIP] > > > > You now have APY data for all vaults across multiple timeframes. > [tab] SDK > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication and Kamino SDK. > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc } from '@solana/kit'; > import { > KaminoManager, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > ``` > > **Step 2** > > ### Initialize SDK > > Set up the RPC connection and create a Kamino Manager instance. > > ```typescript theme={"theme":"css-variables"} > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoManager = new KaminoManager(rpc, slotDuration); > ``` > > **Step 3** > > ### Load All Vaults and Their Reserves > > Retrieve all vaults, then load the reserves of every vault in one batched call. > > ```typescript theme={"theme":"css-variables"} > const vaults = await kaminoManager.getAllVaults(); > const vaultStates = await Promise.all(vaults.map((vault) => vault.getState())); > const allReservesMap = await kaminoManager.loadVaultsReserves(vaultStates); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > ``` > > > [!NOTE] > > > > `loadVaultsReserves` fetches the reserves for all vaults at once. Loading reserves vault by vault means hundreds of RPC calls, which hits the rate limits of public RPC endpoints. > > **Step 4** > > ### Get APYs for Each Vault > > Calculate the actual and theoretical APY of each vault from the shared reserves map. > > ```typescript theme={"theme":"css-variables"} > const vaultAPYs = []; > for (const vault of vaults) { > const vaultState = await vault.getState(); > const hasReserves = vaultState.vaultAllocationStrategy.some((a) => allReservesMap.has(a.reserve)); > if (!hasReserves) continue; > > const actualAPY = await kaminoManager.getVaultActualAPY(vaultState, ledgerInstant, allReservesMap); > const theoreticalAPY = await kaminoManager.getVaultTheoreticalAPY(vaultState, ledgerInstant, allReservesMap); > > vaultAPYs.push({ > address: vault.address.toString(), > name: kaminoManager.getDecodedVaultName(vaultState), > actualAPY: `${actualAPY.netAPY.mul(100).toFixed(2)}%`, > theoreticalAPY: `${theoreticalAPY.netAPY.mul(100).toFixed(2)}%`, > }); > } > > console.table(vaultAPYs); > ``` > > > [!NOTE] > > > > Each APY result contains `grossAPY` and `netAPY` (after fees), calculated from on-chain state. The actual APY is based on the amounts currently invested in each reserve. The theoretical APY assumes all of the vault's funds are invested according to its allocation weights. Vaults with no allocations yet are skipped. > > > [!TIP] > > > > You've successfully fetched vault APYs using the Kamino SDK. ## Related Resources > [card] [Lending Vaults Concepts](/products/lending-vaults/concepts) > > Learn how vaults work under the hood > [card] [Vault Data](/build/earn/vault-data-positions) > > Query vault metrics and positions > [card] [Benchmark Rate](/products/lending-vaults/benchmark-rate) > > Compare vault yields to market baseline > [card] [Earn Deposit](/build/recipes/earn/earn-via-api) > > Deposit into vaults via API # Get wallet earnings and growth history for all tokens Source: https://docs.kamino.com/build/earn/get-wallet-earnings-and-growth-history-for-all-tokens /kamino-api.json get /v3/earn/users/{userPubkey}/tokens/metrics/history Get earn history grouped by token mint across vaults and lending deposits for the requested obligation types. Lending obligations that owe debt now are left out with their whole history. Mints with no buckets in the range are omitted. # Get wallet token earnings and growth history Source: https://docs.kamino.com/build/earn/get-wallet-token-earnings-and-growth-history /kamino-api.json get /v3/earn/users/{userPubkey}/tokens/{tokenMint}/metrics/history Get total earn position value and interest earned per bucket across vaults and lending deposits for the requested obligation types. Lending obligations that owe debt now are left out with their whole history. # Earn Source: https://docs.kamino.com/build/earn/index Build products that turn idle assets into yield with Kamino Earn Overview # Earn Build products that turn idle assets into yield with Kamino. [Developer guide](/build/developers/earn) Start here ## How Earn Vaults Work Earn Vaults put deposits to work across Kamino lending reserves. Vault shares track each depositor's position as yield accrues. 01 ### Deposit Users deposit assets into a vault. 02 ### Earn Vault The vault allocates deposits across lending reserves. 03 ### Redeem Users redeem shares for their deposit plus earned yield. ## Start with Your Goal [Showcase Earn Vaults in your app Let users explore Kamino's vaults and put their assets to work. Explore Earn integration](/build/tutorials/earn) [Earn yield on balances you manage Put idle funds or user deposits to work on behalf of your users. Explore Earn tutorial](/build/earn/tutorials/earn-and-withdraw) [Generate revenue from a vault Manage a paid and access-controlled vault as a curator. Explore vault curation](/build/earn/plan-your-vault) ## Choose Your Tools Pick the right tools for building with Earn or operating a vault. ### Build with Earn [REST APIRead vault data and request unsigned transactions.](/build/api-reference/introduction) [TypeScript SDKBuild custom transactions or create a vault in code.](/build/developers/api-vs-sdk) [Rust crateBuild Rust clients and onchain integrations.](/build/developers/api-vs-sdk) ### Operate a Vault [TypeScript SDKCreate and configure a vault in code.](/build/earn/tutorials/creating-a-vault) [Web interfaceCreate and configure a vault in Kamino's curator UI.](/curators/vaults/guides/create-a-vault) [Kamino CLIManage vaults from the command line.](/curators/vaults/guides/create-a-vault#create-via-kamino-cli) ## Build the Experience Guide users from vault discovery to share redemption. Explore vaults Show vault details so users can assess their options. [Open](/build/earn/vault-data-positions) Deposit and withdraw Build flows for entering and exiting a vault. [Open](/build/earn/tutorials/earn-and-withdraw) Track a position Show each user's balance and accrued yield. [Open](/build/earn/vault-data-positions#get-user-position) Claim rewards Let users claim additional token rewards when available. [Open](/build/earn/tutorials/claim-rewards) # Plan Your Vault Source: https://docs.kamino.com/build/earn/plan-your-vault Understand the decisions a curator makes when designing and operating a Kamino lending vault A Kamino lending vault accepts a single deposit asset and allocates it across selected Kamino lending reserves. Depositors receive vault shares representing their portion of the vault and earn the yield generated by those reserves. The curator decides where capital can go and adjusts the strategy as conditions change. ![Kamino curators vault overview](https://mintcdn.com/kamino-3d73a151/Kr04J8Tty1aPhdQ2/images/curators/vaults/vault-overview.webp?fit=max\&auto=format\&n=Kr04J8Tty1aPhdQ2\&q=85\&s=68346f227fe1a3266d333da6aef2a29c) A vault does not create a new lending market. It allocates deposits across existing reserves. The yield it generates depends on how those reserves perform and how the curator distributes capital between them. By the end of this guide Curators should understand: * What a Kamino lending vault does and what vault shares represent. * The settings that determine where capital is allocated and when it moves between reserves. * What determines how much capital remains available for withdrawals. * Which fees generate curator revenue and how farm rewards reach depositors. * What the Insurance Pool and Whitelisted Reserves protect. * Which vault responsibilities can be delegated and why administrative authority is transferred to a multisig. * When changing vault conditions may require an adjustment. *** ## A Vault in One Example Planning a vault starts with understanding how depositor capital moves through it. Consider a vault that accepts USDC and allocates it between two USDC reserves in different Kamino lending markets. Depositors supply USDC and receive vault shares. The vault distributes their USDC according to the curator's allocation targets. When a depositor adds USDC, the vault issues vault shares (SPL tokens) representing their portion of its total assets. As the vault earns interest, the value of each share increases. The depositor later redeems those shares for USDC at the current exchange rate. Suppose the vault holds \$1 million USDC and the curator sets a 60% allocation to one reserve and 40% to another. The vault targets \$600,000 in the first reserve and \$400,000 in the second. Because each reserve earns a different supply rate, the vault's yield reflects the amount allocated to each one. As the vault's balance changes, the amount held in each reserve can move away from the 60/40 target allocation. A permissionless crank periodically moves available capital so each reserve moves closer to its target. The curator sets or updates the percentage assigned to each reserve instead of moving every deposit manually. When a depositor withdraws, the vault redeems their shares for USDC. It first uses unallocated USDC and any capital available from its reserves. If the full amount cannot be returned immediately, the remainder enters a withdrawal queue and is paid as liquidity becomes available. The curator can earn revenue through a performance fee on profits and an assets under management (AUM) fee on the vault's total assets. Both fees accrue in the vault's deposit asset, which is USDC in this example, and can be collected by the curator. Knowledge Check A curator should be able to: * Understand what vault shares represent. * Understand how allocation percentages determine the amount assigned to each reserve. * Understand the crank's role in moving available capital closer to the curator's target allocations. * Explain how depositors withdraw from the vault. * Understand the two fee types that generate curator revenue. > [card] [How vaults work](/curators/vaults/concepts/how-vaults-work) > > Vault mechanics, share tokens, and the deposit-to-yield lifecycle. > [card] [Create a vault](/curators/vaults/guides/create-a-vault) > > Initialize a new vault and set its deposit asset. *** ## Selecting Assets for a Vault Each Kamino vault accepts a single asset. A USDC vault accepts USDC deposits and allocates them only to USDC reserves. It cannot allocate capital to SOL or any other asset. The same asset may be available in several Kamino lending markets. Each market has its own borrowers, supply rate, utilization, and available liquidity. The curator selects which of these reserves the vault can allocate capital to. The supply rate shown for a reserve can change as borrowing demand changes. A higher rate may reflect high utilization, which also leaves less liquidity available if the vault needs to withdraw capital. Farm incentives may also increase the displayed yield only while those rewards continue. Using several reserves can spread capital across lending markets, but the number of allocations alone does not determine diversification. Reserves exposed to similar borrowers or market conditions may still carry similar risk. Worth checking * Whether the expected yield is supported by borrowing demand and how much remains if farm rewards end. * Whether the selected reserves provide enough liquidity and meaningfully different exposure. *** ## Planning the Allocation Strategy For each reserve, the curator sets rules for when capital can enter and how much it can receive. Together, these settings determine how the vault distributes capital as market conditions change. A vault can allocate the same asset across several reserves, each offering a different way to earn yield. The curator decides whether capital should be placed in a reserve immediately or moved only when a borrower is ready to use it. A **Standard** allocation places capital in a variable rate reserve, where it earns interest that changes with utilization. A **Conditional** allocation keeps that capital earning in a Standard reserve until it matches demand for a fixed rate loan. The capital then moves into the fixed rate reserve and is lent to the borrower. For each Standard allocation, the **weight** sets the share of vault capital intended for that reserve. As the vault grows, the amount assigned to the reserve grows with it. The curator can set a **vault allocation cap** to stop that amount from increasing beyond a chosen limit. This prevents the vault from placing too much of its capital in one reserve. The cap applies only to the vault and does not change the reserve's own settings. ### Allocation Settings | Setting | What it determines | | - | - | | **Type** | Whether capital enters a reserve immediately through a Standard allocation or moves when fixed rate borrowing demand appears through a Conditional allocation. | | **Weight** | The proportion of capital assigned to each Standard allocation. | | **Cap** | The maximum amount of the vault asset that can be allocated to a reserve. | | **Priority** | Which Standard allocations may supply capital when a Conditional allocation receives borrowing demand. | Worth checking * Whether the vault should hold capital in variable rate reserves, offer fixed rate loans through Conditional allocations, or support both. * How much capital the vault should make available for fixed rate borrowing demand. > [card] [Allocations](/curators/vaults/concepts/allocations) > > Weight, cap, type, and priority mechanics. > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > Set and update allocation targets. > [card] [Fixed rates](/curators/vaults/fixed-rates/index) > > Conditional allocations and fixed rate lending. *** ## Planning for Withdrawals A curator decides how much deposited capital should remain available for withdrawals instead of being allocated to lending reserves. This is the vault's **unallocated buffer**. A larger buffer supports more immediate withdrawals, but the capital it holds does not earn lending yield. The **UnallocatedWeight** allows the buffer to grow with the vault. The **UnallocatedTokensCap** stops that growth once the buffer is large enough, preventing too much depositor capital from sitting idle instead of earning yield. When a depositor withdraws, the vault uses the unallocated buffer first. If the buffer cannot cover the full amount, the vault draws from available liquidity in its reserve allocations. Any amount that cannot be returned immediately enters the withdrawal queue and is paid as liquidity becomes available. **Vault shares and reserve receipts.** Depositors normally hold vault shares, also called kTokens, representing their portion of the vault. The vault holds cTokens representing capital supplied to its lending reserves. If a withdrawal must be queued, the remaining vault shares may be exchanged for cTokens until the underlying asset becomes available. ### Withdrawal Settings | Setting | What it determines | | - | - | | **UnallocatedWeight** | The target share of vault capital kept available for withdrawals. | | **UnallocatedTokensCap** | The maximum amount of capital the vault may hold in the unallocated buffer. | Worth checking * How much withdrawal activity the vault is expected to support. * How much yield the vault can forgo to keep capital immediately available. > [card] [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals) > > Buffer sizing, withdrawal queue, and cToken mechanics. > [card] [Create a vault](/curators/vaults/guides/create-a-vault) > > Set buffer parameters during vault creation. *** ## Vault Revenue and Depositor Rewards A curator decides how the vault will generate revenue and whether depositors will receive rewards in addition to lending yield. These choices affect the return depositors keep and the income the curator earns for managing the vault. ### Setting Fees Curator revenue comes from two fees. A **performance fee** charges a percentage of the vault's profits. An **assets under management (AUM) fee** charges an annual percentage of the vault's total assets, regardless of its performance. Both accrue in the vault's deposit asset and can be collected by the curator. The vault also charges fees that do not generate curator revenue. The **withdrawal penalty** returns to the vault for the benefit of remaining depositors. The **crank fund fee** covers the protocol cost of allocating new deposits across reserves. ### Fee Settings | Fee | How it is calculated | Curator revenue? | | - | - | - | | **Performance fee** | A percentage of the vault's profits. | Yes | | **Assets under management (AUM) fee** | An annual percentage of the vault's total assets. | Yes | | **Withdrawal penalty** | The greater of a percentage fee or a fixed token amount charged when a depositor withdraws. | No. It returns to the vault for remaining depositors. | | **Crank fund fee** | A fixed amount charged for each reserve when a deposit is allocated. | No. It funds protocol operations. | ### Farm Rewards Farm rewards are separate from curator fees. Where they come from determines whether depositors claim them directly or receive them through a higher vault share value. | Reward type | Where it comes from | How depositors receive it | Curator revenue | | - | - | - | - | | **Vault Farm** | A reward token supplied by the curator or another sponsor. | Depositors claim rewards based on their vault share holdings during the reward period. | No | | **Reserve farm** | An incentive program attached to a reserve where the vault allocates capital. | Rewards are calculated for each depositor based on their vault position and the vault's allocation to that reserve. Depositors claim them separately. | No | | **Autocompound Farm** | Rewards supplied in the vault's deposit asset. | Rewards are reinvested and increase the value of vault shares. | Yes, indirectly. Reinvested rewards increase the vault's assets under management, which can increase AUM fee revenue and may also contribute to performance fees. | Knowledge Check A curator should be able to: * Identify which vault fees generate curator revenue and where the other fees go. * Distinguish which farm rewards depositors can claim directly. > [card] [Yield & fees](/curators/vaults/concepts/yield-and-fees) > > Performance fees, AUM fees, and reward mechanics. > [card] [Configure farms](/curators/vaults/guides/configure-farms) > > Set up Vault Farms, Reserve farms, and Autocompound Farms. *** ## Depositor Protections Before launch, the curator decides which depositor protections are appropriate for the vault. An **Insurance Pool** provides an added layer of coverage, while **Whitelisted Reserves** keeps allocations within a set approved by Kamino. ### Insurance Pool An Insurance Pool is capital the curator deposits into a dedicated pool attached to the vault. That capital continues earning the vault's APY while it remains locked. Kamino matches the curator's contribution up to \$250,000. A \$200,000 contribution therefore creates a \$400,000 Insurance Pool, while amounts above \$250,000 receive no additional match. If the vault incurs a loss, the Insurance Pool is used to compensate depositors before the remaining loss reaches them. Coverage is limited to the pool's balance, and compensation is coordinated manually with Kamino. Withdrawing curator capital requires a 30-day cooldown. An emergency withdrawal can bypass the cooldown, but it requires approval from both the curator and Kamino's Security Council and is reserved for compensating depositors after a loss. ### Whitelisted Reserves Whitelisted Reserves limits the vault to reserves verified by Kamino. The curator decides whether to enforce the whitelist but does not decide which reserves it contains. Before enabling it, the curator should confirm that the vault's planned allocations are included in the approved set. The protection uses two settings. One prevents the curator from creating or increasing allocations outside the whitelist. The other prevents depositor funds from entering those reserves. Both settings form part of the requirements for appearing on Kamino's interface, and neither can be disabled afterward. The whitelist does not prevent withdrawals. Existing allocations can still be reduced or removed, and depositors can withdraw when liquidity is available. ### Comparing Vault Safeguards | If the curator's priority is... | Safeguard to consider | What this requires | | - | - | - | | Providing capital-backed coverage if the vault suffers a loss | Insurance Pool | Curator capital remains locked, earns the vault APY, and is used to compensate depositors after a loss. | | Preventing the vault from entering reserves outside Kamino's approved set | Whitelisted Reserves | The allocation strategy is limited to reserves Kamino has approved. | | Preserving access to reserves outside the approved set | Insurance Pool without Whitelisted Reserves | The vault retains broader allocation flexibility but does not meet the safeguard requirements for Kamino interface listing. | | Restricting reserve access without committing curator capital | Whitelisted Reserves without an Insurance Pool | Allocations are restricted, but depositors do not receive capital-backed loss coverage and the vault does not meet the safeguard requirements for Kamino interface listing. | | Meeting the safeguard requirements for Kamino interface listing | Both safeguards | Curator capital is committed and allocations remain within the approved reserve set. Multisig ownership is also required. | Worth checking * How much curator capital can be committed to an Insurance Pool and remain subject to the 30-day withdrawal restriction. * Whether the planned allocation strategy can operate within Kamino's approved reserve set. > [card] [Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) > > Fund the pool, understand cooldowns, and coordinate payouts. > [card] [Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) > > Enable the whitelist and confirm eligible reserves. *** ## Vault Roles and Permissions Before launch, the curator decides who will manage the vault and which responsibilities can be delegated. These choices determine who can change the vault's configuration once it begins operating. ### Assigning Vault Roles A vault separates full administrative authority from routine allocation management. The curator decides which actions should remain with the primary admin and which can be delegated to another wallet or automated service. The **Vault Admin** can change the vault's settings, add or remove reserves, update allocations, and set fees. The **Allocation Admin** can adjust the weights, caps, types, and priorities of existing allocations, but cannot add reserves or change the vault's broader configuration. This allows routine allocation changes without granting full authority over the vault. The **Farm Authority** manages the vault farm during its creation. Once the farm is created, this authority transfers to the protocol and is no longer managed by the curator. ### Planning Multisig Ownership For a production vault, the Vault Admin is transferred to a Squads multisig before deposits open. The curator decides who will hold signing authority and how many approvals will be required to change the vault. Once the multisig becomes Vault Admin, changes are submitted as proposals and executed only after the approval threshold is met. This prevents a single wallet from changing the vault and makes administrative decisions visible to the other signers. Multisig ownership is also required for a vault to appear on Kamino's interface. ### Authority by Action | Action | Authority | | - | - | | Change vault settings or fees | Vault Admin | | Add or remove a reserve | Vault Admin | | Update an existing allocation | Vault Admin or Allocation Admin | | Transfer administrative authority | Vault Admin | | Manage the vault farm during creation | Farm Authority | Knowledge Check A curator should be able to: * Understand which allocation changes can be delegated without granting full administrative authority. * Understand why administrative authority is transferred to a multisig before launch. > [card] [Roles & ownership](/curators/vaults/concepts/roles-and-ownership) > > Vault Admin, Allocation Admin, and Farm Authority. > [card] [Transfer admin](/curators/vaults/guides/transfer-admin) > > Move ownership from a hot wallet to Squads. *** ## Ongoing Vault Management Once the vault is live, the curator should watch for conditions that suggest its allocation strategy or withdrawal settings need to change. ### Adjusting the Vault | Issue | What is happening | Response | | - | - | - | | Capital remains far from its target allocations | To restore the target, the crank must withdraw capital from an overallocated reserve and move it into an underallocated reserve. It may be unable to complete that move if borrowers are using the capital in the first reserve or the second allocation has reached its cap. | Check the available liquidity in the first reserve and the cap on the second allocation. Revise the target or cap if the current configuration cannot be reached. **Vault Admin or Allocation Admin.** | | The withdrawal buffer is repeatedly exhausted | Depositors are withdrawing capital faster than the buffer is being replenished. The vault must draw from its reserve allocations, and withdrawals may be queued if that capital is unavailable. | Increase the UnallocatedWeight or UnallocatedTokensCap so more capital remains available. **Vault Admin.** | | An allocation is earning less than expected | Borrowing demand in that reserve may have fallen, reducing the interest earned by the vault. | Reduce its target weight and direct capital toward another suitable reserve. **Vault Admin or Allocation Admin.** | | A reserve has limited available liquidity | Most of the reserve's capital is already being used by borrowers. The vault may be unable to withdraw its allocation immediately. | Reduce the allocation weight or cap to limit further exposure. **Vault Admin or Allocation Admin.** | | An allocation reaches its cap as the vault grows | The reserve cannot receive more of the vault's capital, even if its target weight assigns it a larger amount. Additional capital must remain available or move to another eligible allocation. | Increase the cap if the reserve can support more exposure. Otherwise, direct additional capital elsewhere. **Vault Admin or Allocation Admin.** | ### Responding to Events | Issue | What is happening | Response | | - | - | - | | A reserve shows signs of a security issue | The vault may still be directing depositor capital into a reserve that is no longer considered suitable. Any loss in that reserve can reduce the value of the vault's holdings. | Set the allocation cap to zero to stop additional capital from entering; for a Standard allocation, its weight can also be set to zero. Remove the allocation once available capital has been withdrawn. **Vault Admin or Allocation Admin** can stop further allocation. Only the **Vault Admin** can remove the reserve. | | A reserve loss reduces the vault's assets | The vault's claim on that reserve is now worth less. This reduces the value of vault shares and may leave depositors with a loss. | Stop further allocation, assess the loss with Kamino, then use the Insurance Pool to compensate affected depositors. **Vault Admin or Allocation Admin** stops further allocation. Releasing Insurance Pool funds immediately requires the curator's designated signer and **Kamino's Security Council**. | | An unexpected allocation change appears | An Allocation Admin wallet or automated service may have changed a weight, cap, type, or priority without approval. It cannot add a new reserve or change other vault settings. | Replace or revoke the Allocation Admin, restore the intended configuration, then sync the vault toward its targets. **Vault Admin.** | | An unfamiliar Vault Admin proposal appears in Squads | A multisig signer may be compromised or someone may be attempting an unauthorized vault change. The proposal cannot execute unless it receives the required approvals. | Do not approve the proposal. Review its source and remove any compromised signer before another vault change is submitted. **Squads multisig members.** | Vaults do not have the same Emergency Council used by lending markets. Their response model relies on delegated allocation authority, the Vault Admin multisig, and the Insurance Pool's separate two-party withdrawal authority. Knowledge Check A curator should be able to: * Identify when allocation settings or the withdrawal buffer need to change as vault conditions evolve. * Understand which authority can make each adjustment or respond to an unexpected event. *** ## Pre-launch Checklist ### Vault Strategy * [ ] The vault asset and eligible reserves have been selected. * [ ] Each allocation is designated as Standard or Conditional. * [ ] Target weights, allocation caps, and priorities have been set. ### Withdrawals and Revenue * [ ] The unallocated buffer has been sized for expected withdrawal activity. * [ ] Performance and AUM fees have been set. * [ ] Any Vault Farms or Autocompound Farms have been planned. ### Safeguards and Authority * [ ] The Insurance Pool commitment has been decided. * [ ] The planned allocations are compatible with Whitelisted Reserves. * [ ] Vault Admin will be transferred to the intended multisig. * [ ] Allocation Admin responsibilities have been assigned. ### Ongoing Management * [ ] The conditions that would require allocation or buffer changes have been defined. * [ ] The authority responsible for each change has been confirmed. * [ ] The response to a reserve loss or unexpected administrative change has been reviewed. # Earn Deposit with the API Source: https://docs.kamino.com/build/earn/recipes/earn-via-api The API generates the unsigned transaction, and the client signs it securely ## Earn Deposit with API **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={"theme":"css-variables"} 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 2** ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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 3** ### Call Kamino API Make a POST request to the Kamino API to build the deposit transaction. ```typescript theme={"theme":"css-variables"} 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(); console.log('API error:', error.message); } const { transaction: encodedTransaction } = await response.json(); ``` > [!NOTE] > > The API returns a pre-built transaction encoded in base64 format. This transaction includes Address Lookup Tables (ALTs) for efficiency. **Step 4** ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` **Step 5** ### Resolve Address Lookup Tables Fetch and resolve the Address Lookup Tables from the blockchain. ```typescript theme={"theme":"css-variables"} 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) ); ``` > [!NOTE] > > `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. > [!NOTE] > > A fresh blockhash is fetched and set to ensure the transaction remains valid. **Step 6** ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={"theme":"css-variables"} 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); ``` > [!TIP] > > 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. # Earn Withdraw with the API Source: https://docs.kamino.com/build/earn/recipes/earn-withdraw-via-api The API generates the unsigned transaction, and the client signs it securely ## Earn Withdraw with API **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={"theme":"css-variables"} 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 2** ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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 3** ### Call Kamino API Make a POST request to the Kamino API to build the withdrawal transaction. ```typescript theme={"theme":"css-variables"} 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(); console.log('API error:', error.message); } const { transaction: encodedTransaction } = await response.json(); ``` > [!NOTE] > > The API returns a pre-built transaction encoded in base64 format. This transaction includes Address Lookup Tables (ALTs) for efficiency. **Step 4** ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` **Step 5** ### Resolve Address Lookup Tables Fetch and resolve the Address Lookup Tables from the blockchain. ```typescript theme={"theme":"css-variables"} 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) ); ``` > [!NOTE] > > `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. > [!NOTE] > > A fresh blockhash is fetched and set to ensure the transaction remains valid. **Step 6** ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={"theme":"css-variables"} 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); ``` > [!TIP] > > 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. # Claim Rewards Source: https://docs.kamino.com/build/earn/tutorials/claim-rewards Claim all rewards earned from Kamino vaults ## Claiming Rewards Retrieve and claim all pending rewards from a vault position. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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'); ``` > [!NOTE] > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. **Step 3** ### Load the Vault Initialize the vault and load its state and reserves once. Both the rewards check and the claim instructions use them. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'), slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const ledgerInstant = await getCurrentLedgerInstant(rpc); ``` **Step 4** ### Check Pending Rewards List the rewards your position has earned, per reward token. ```typescript theme={"theme":"css-variables"} const pending = await manager.getAllPendingRewardsForUserInVault( signer.address, vault, vaultReservesMap, ledgerInstant ); for (const [rewardMint, amount] of pending.totalPendingRewards) { if (amount.isZero()) continue; console.log(`Pending ${amount.toString()} lamports of reward token ${rewardMint}`); } ``` > [!NOTE] > > A position earns rewards from the vault's farm, the vault's delegated farm, and the farms of the reserves the vault allocates to. Amounts are in lamports, so divide by `10^decimals` of the reward token. Unused reward slots return `0` and are skipped. **Step 5** ### Generate Claim Rewards Instructions Build the instructions that claim every pending reward in one transaction. ```typescript theme={"theme":"css-variables"} const instructions = await manager.getClaimAllRewardsForVaultIxs( signer, vault, vaultReservesMap, ledgerInstant ); if (!instructions.length) { console.log('No rewards to claim'); } ``` **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` **Step 7** ### Build and Sign Transaction Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} 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); ``` **Step 8** ### Send and Confirm Transaction Send the claim transaction and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Claim rewards successful! Signature:', signature); ``` > [!TIP] > > Once the claim transaction is confirmed, the reward tokens are sent to your wallet. # Create a Vault Source: https://docs.kamino.com/build/earn/tutorials/creating-a-vault Create and configure Kamino vaults with custom fee structures to earn revenue > [!NOTE] > > Learn how to create a Kamino vault with [custom fee structures](#configure-vault), deposit limits, and allocation strategies. The SDK manages vault initialization, metadata setup, and lookup table creation to optimize future transactions. ## Creating a Vault Initialize a new vault with custom configuration and prepare it for user deposits. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Instruction, } from '@solana/kit'; import { KaminoManager, KaminoVault, KaminoVaultConfig, getMedianSlotDurationInMsFromLastEpochs, sleep, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Admin Keypair and Initialize Manager Load the admin keypair from file and initialize the Kamino manager with proper slot timing. ```typescript theme={"theme":"css-variables"} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const adminSigner = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const kaminoManager = new KaminoManager(rpc, slotDuration); ``` > [!NOTE] > > `parseKeypairFile` loads an existing keypair from a JSON file that will become the vault admin. The admin wallet needs SOL for rent and fees, plus a small amount of the vault token: creation takes an initial deposit of 1,000 lamports (0.001 USDC here) from it. **Step 3** ### Configure Vault Create a vault configuration with the core identity and fee structure. ```typescript theme={"theme":"css-variables"} const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(15.0), managementFeeRatePercentage: new Decimal(2.0), name: 'MyCustomVault', vaultTokenSymbol: 'USDC', vaultTokenName: 'MyCustomVaultToken', minDepositAmount: 1000, minWithdrawAmount: 10, minInvestAmount: 0, minInvestDelaySlots: 0, withdrawalPenaltyBps: 1, withdrawalPenaltyLamports: 1, crankFundFeePerReserve: 1, }); ``` > [!NOTE] > > The parameters from `minDepositAmount` down are optional. The values shown are the defaults, so omit them to keep the defaults. All parameters can be changed after creation. Unallocated weight and cap can only be set after creation, see the [Configure Vault Parameters](#configure-vault-parameters-post-creation) step below. **Vault Configuration Parameters** | Parameter | Type | Default | Description | | - | - | - | - | | `admin` | `TransactionSigner` | | Keypair that owns and manages the vault | | `tokenMint` | `Address` | | SPL token mint address (e.g., USDC) | | `tokenMintProgramId` | `Address` | | Token program of the mint (`TOKEN_PROGRAM_ADDRESS`, or the Token-2022 program for Token-2022 mints) | | `performanceFeeRatePercentage` | `Decimal` | | Percentage of earned yield collected as fees | | `managementFeeRatePercentage` | `Decimal` | | Annual percentage fee on total assets | | `name` | `string` | | Vault name stored on-chain (max 40 characters) | | `vaultTokenSymbol` | `string` | | Symbol for vault share token (max 5 characters) | | `vaultTokenName` | `string` | | Display name for vault share token (max 10 characters) | | `minDepositAmount` | `number` | 1000 | Optional. Minimum deposit per transaction (lamports) | | `minWithdrawAmount` | `number` | 10 | Optional. Minimum withdrawal per transaction (lamports) | | `minInvestAmount` | `number` | 0 | Optional. Minimum amount moved in a single investment (lamports) | | `minInvestDelaySlots` | `number` | 0 | Optional. Slots between investments in a reserve | | `withdrawalPenaltyBps` | `number` | 1 | Optional. Percentage-based withdrawal fee (basis points) | | `withdrawalPenaltyLamports` | `number` | 1 | Optional. Absolute withdrawal fee (lamports) | | `crankFundFeePerReserve` | `number` | 1 | Optional. Fee per reserve to fund crank operations (lamports) | | `allowAllocationsInWhitelistedReservesOnly` | `boolean` | false | Optional. Only allow allocations to whitelisted reserves | | `allowInvestInWhitelistedReservesOnly` | `boolean` | false | Optional. Only allow investing in whitelisted reserves | **Step 4** ### Generate Vault Creation Instructions Pass the vault configuration to the Kamino manager to generate all required initialization instructions. ```typescript theme={"theme":"css-variables"} const { vault: vaultSigner, initVaultIxs: instructions } = await kaminoManager.createVaultIxs(kaminoVaultConfig); console.log('New vault address:', vaultSigner.address); ``` > [!NOTE] > > `createVaultIxs` returns a new vault keypair plus instruction bundles for initializing the vault, creating and filling its lookup table, creating its two farms (the Vault Farm for rewards and the First Loss Capital Farm), registering the farms on the vault, and setting the share token metadata. They are sent across four transactions in the steps below. **Step 5** ### Create a Send Function Vault creation sends several transactions, so define one function that builds, signs, and sends each of them. ```typescript theme={"theme":"css-variables"} async function sendTransaction(ixs: Instruction[], label: string) { const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(ixs, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`${label}:`, getSignatureFromTransaction(signedTransaction)); } ``` > [!NOTE] > > `signTransactionMessageWithSigners` signs with every signer in the instructions, including the new vault keypair. The blockhash is fetched inside the function so each transaction gets a fresh one. **Step 6** ### Initialize the Vault Send the first transaction: it creates the vault, applies the configuration, and creates the vault's lookup table. ```typescript theme={"theme":"css-variables"} await sendTransaction( [ ...instructions.createAtaIfNeededIxs, ...instructions.initVaultIxs, instructions.createLUTIx, ...instructions.cleanupIxs, ], 'Vault initialized' ); ``` > [!NOTE] > > The share token metadata instruction is sent later, in the last transaction. Adding it here takes this transaction over Solana's 1,232-byte limit. **Step 7** ### Create and Attach Farms Create the Vault Farm and the First Loss Capital Farm, and register each one on the vault. Each farm is one transaction. ```typescript theme={"theme":"css-variables"} const vaultFarm = instructions.createVaultFarms.createVaultFarmIxs; await sendTransaction( [...vaultFarm.setupFarmIxs, ...vaultFarm.updateFarmIxs, instructions.setFarmToVaultIxs.setFarmToVaultIx], 'Vault Farm created' ); const flcFarm = instructions.createVaultFarms.createFLCVaultFarmIxs; const setFlcFarm = instructions.setFarmToVaultIxs.setFLCFarmToVaultIx; if (flcFarm && setFlcFarm) { await sendTransaction( [...flcFarm.setupFarmIxs, ...flcFarm.updateFarmIxs, setFlcFarm], 'First Loss Capital Farm created' ); } ``` > [!NOTE] > > If you skip this step, you can create farms later with `kaminoManager.createVaultFarmIxs` and register them with `kaminoManager.updateVaultFarmIxs` (Vault Farm) or `kaminoManager.updateVaultFirstLossCapitalFarmIxs` (First Loss Capital Farm). See [Configure farms](/curators/vaults/guides/configure-farms) for the full post-creation flow. **Step 8** ### Fill the Lookup Table and Set Share Metadata Add the vault's accounts to its lookup table and set the share token metadata. ```typescript theme={"theme":"css-variables"} await sleep(2000); await sendTransaction( [...instructions.populateLUTIxs, instructions.initSharesMetadataIx], 'Lookup table filled and share metadata set' ); ``` > [!NOTE] > > A new lookup table can only be extended from the slot after it was created, so this transaction goes last. The lookup table keeps deposit and withdraw transactions for this vault small. **Step 9** ### Verify the Setup Check that every part of the vault was set up. ```typescript theme={"theme":"css-variables"} const vault = new KaminoVault(rpc, vaultSigner.address, slotDuration); const status = await kaminoManager.getVaultSetupStatus(vault, kaminoVaultConfig); if (status.allSet) { console.log('Vault created and fully set up:', vaultSigner.address); } else { console.log('Setup incomplete:', status); } ``` > [!NOTE] > > If a transaction failed, `kaminoManager.finishVaultSetup(vault, kaminoVaultConfig)` returns only the missing instructions, so you can send them without starting over. **Step 10** ### Configure Vault Parameters (Post-Creation) Set the parameters that are only available after creation (unallocated weight and cap), or update any parameter set during creation. ```typescript theme={"theme":"css-variables"} const vaultState = await vault.getState(); const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); const { updateVaultConfigIx: unallocWeightIx } = await kaminoManager.updateVaultUnallocatedWeightIxs(vault, 500, vaultReservesMap, adminSigner); const { updateVaultConfigIx: unallocCapIx } = await kaminoManager.updateVaultUnallocatedTokensCapIxs(vault, 2000000, vaultReservesMap, adminSigner); await sendTransaction([unallocWeightIx, unallocCapIx], 'Unallocated weight and cap set'); ``` > [!NOTE] > > Every creation parameter has an update method with the same arguments, for example `kaminoManager.updateVaultMinDepositAmountIxs(vault, 1000, vaultReservesMap, adminSigner)`. Each returns `{ updateVaultConfigIx }`. The new vault holds no allocations yet: add reserves with `kaminoManager.updateVaultReserveAllocationIxs` before it can earn. **Post-Creation Parameters** | Method | Parameter | Default | Description | | - | - | - | - | | `updateVaultMinDepositAmountIxs` | `minDepositAmount` | 1000 | Minimum deposit per transaction (lamports) | | `updateVaultMinWithdrawAmountIxs` | `minWithdrawAmount` | 10 | Minimum withdrawal per transaction (lamports) | | `updateVaultMinInvestAmountIxs` | `minInvestAmount` | 0 | Minimum amount moved in a single investment (lamports) | | `updateVaultMinInvestDelaySlotsIxs` | `minInvestDelaySlots` | 0 | Slots between investments in a reserve | | `updateVaultWithdrawalPenaltyBpsIxs` | `withdrawalPenaltyBps` | 1 | Percentage-based withdrawal fee (basis points); returned to vault | | `updateVaultWithdrawalPenaltyLamportsIxs` | `withdrawalPenaltyLamports` | 1 | Absolute withdrawal fee (lamports); system takes MAX of BPS and lamports | | `updateVaultCrankFundFeePerReserveIxs` | `crankFundFeePerReserve` | 1 | Fee per reserve to fund crank operations (lamports) | | `updateVaultUnallocatedWeightIxs` | `unallocatedWeight` | 500 | Relative weight for idle funds in total weight calculation | | `updateVaultUnallocatedTokensCapIxs` | `unallocatedTokensCap` | 2000000 | Maximum absolute amount to keep unallocated (lamports) | #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Instruction, } from '@solana/kit'; import { KaminoManager, KaminoVault, KaminoVaultConfig, getMedianSlotDurationInMsFromLastEpochs, sleep, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { Decimal } from 'decimal.js'; const KEYPAIR_FILE = '/path/to/your/keypair.json'; const adminSigner = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const kaminoManager = new KaminoManager(rpc, slotDuration); const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(15.0), managementFeeRatePercentage: new Decimal(2.0), name: 'MyCustomVault', vaultTokenSymbol: 'USDC', vaultTokenName: 'MyCustomVaultToken', minDepositAmount: 1000, minWithdrawAmount: 10, minInvestAmount: 0, minInvestDelaySlots: 0, withdrawalPenaltyBps: 1, withdrawalPenaltyLamports: 1, crankFundFeePerReserve: 1, }); const { vault: vaultSigner, initVaultIxs: instructions } = await kaminoManager.createVaultIxs(kaminoVaultConfig); console.log('New vault address:', vaultSigner.address); async function sendTransaction(ixs: Instruction[], label: string) { const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(ixs, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`${label}:`, getSignatureFromTransaction(signedTransaction)); } await sendTransaction( [ ...instructions.createAtaIfNeededIxs, ...instructions.initVaultIxs, instructions.createLUTIx, ...instructions.cleanupIxs, ], 'Vault initialized' ); const vaultFarm = instructions.createVaultFarms.createVaultFarmIxs; await sendTransaction( [...vaultFarm.setupFarmIxs, ...vaultFarm.updateFarmIxs, instructions.setFarmToVaultIxs.setFarmToVaultIx], 'Vault Farm created' ); const flcFarm = instructions.createVaultFarms.createFLCVaultFarmIxs; const setFlcFarm = instructions.setFarmToVaultIxs.setFLCFarmToVaultIx; if (flcFarm && setFlcFarm) { await sendTransaction( [...flcFarm.setupFarmIxs, ...flcFarm.updateFarmIxs, setFlcFarm], 'First Loss Capital Farm created' ); } await sleep(2000); await sendTransaction( [...instructions.populateLUTIxs, instructions.initSharesMetadataIx], 'Lookup table filled and share metadata set' ); const vault = new KaminoVault(rpc, vaultSigner.address, slotDuration); const status = await kaminoManager.getVaultSetupStatus(vault, kaminoVaultConfig); if (status.allSet) { console.log('Vault created and fully set up:', vaultSigner.address); } else { console.log('Setup incomplete:', status); } const vaultState = await vault.getState(); const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); const { updateVaultConfigIx: unallocWeightIx } = await kaminoManager.updateVaultUnallocatedWeightIxs(vault, 500, vaultReservesMap, adminSigner); const { updateVaultConfigIx: unallocCapIx } = await kaminoManager.updateVaultUnallocatedTokensCapIxs(vault, 2000000, vaultReservesMap, adminSigner); await sendTransaction([unallocWeightIx, unallocCapIx], 'Unallocated weight and cap set'); ``` # Earn Vaults: Deposit and Withdraw Source: https://docs.kamino.com/build/earn/tutorials/earn-and-withdraw Deposit assets into Kamino Earn Vaults and withdraw your shares ## Deposit to Earn Vault Deposit assets to start earning yield. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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'); ``` > [!NOTE] > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. **Step 3** ### Load the Vault Initialize the vault and load its state, reserves, and farm state once. The deposit instructions need all three. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const farmState = await manager.loadVaultFarmState(vaultState); ``` **Step 4** ### Set Slippage Protection Estimate the shares the deposit will mint, minus a slippage tolerance. The deposit reverts if fewer shares would be minted. ```typescript theme={"theme":"css-variables"} const depositAmount = new Decimal(1.0); // 1 USDC const minSharesOut = manager.estimateSharesFromTokens( vaultState, depositAmount, await getCurrentLedgerInstant(rpc), vaultReservesMap, 10 // 0.1% slippage ); ``` > [!NOTE] > > The deposit amount is in tokens (`1.0` is 1 USDC), not lamports. **Step 5** ### Build Deposit Instructions Generate the deposit instructions, plus the instructions that stake the new shares in the vault's farm. ```typescript theme={"theme":"css-variables"} const bundle = await vault.depositIxs( signer, depositAmount, vaultReservesMap, farmState, null, // first-loss capital farm undefined, // payer undefined, // memo minSharesOut ); const instructions = [...bundle.depositIxs, ...bundle.stakeInFarmIfNeededIxs]; ``` > [!NOTE] > > If the vault has a rewards farm, `stakeInFarmIfNeededIxs` stakes the minted shares in it so the position earns farm rewards. Shares staked here are unstaked automatically when you withdraw. **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` > [!NOTE] > > Every vault has its own lookup table. Compressing with it cuts the deposit from about 1,021 to 528 bytes, well under Solana's 1,232-byte transaction limit. **Step 7** ### Build and Sign Transaction Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} 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); ``` **Step 8** ### Send and Confirm Transaction Send the deposit transaction and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deposit successful! Signature:', signature); ``` > [!TIP] > > 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. ## Withdraw from Earn Vault Withdraw your vault shares to receive the underlying tokens plus accrued interest. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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'); ``` > [!NOTE] > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. **Step 3** ### Load the Vault Initialize the vault and load its state, reserves, and farm state once. The withdraw instructions need all three. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const farmState = await manager.loadVaultFarmState(vaultState); const ledgerInstant = await getCurrentLedgerInstant(rpc); ``` **Step 4** ### Convert Tokens to Shares Convert the token amount you want back into vault shares, capped at the shares you hold. ```typescript theme={"theme":"css-variables"} const withdrawAmount = new Decimal(1.0); // 1 USDC const userShares = await vault.getUserShares(signer.address); const tokensPerShare = await manager.getTokensPerShareSingleVault(vault, ledgerInstant, vaultReservesMap, ledgerInstant); const sharesToWithdraw = Decimal.min(withdrawAmount.div(tokensPerShare), userShares.totalShares); ``` > [!NOTE] > > `withdrawIxs` takes an amount of **vault shares**, not tokens. Shares grow in value as interest accrues, so one share is worth more than one token. To withdraw everything, pass `userShares.totalShares`. **Step 5** ### Build Withdraw Instructions Generate the unstake and withdraw instructions. ```typescript theme={"theme":"css-variables"} const bundle = await vault.withdrawIxs( signer, sharesToWithdraw, ledgerInstant, vaultReservesMap, farmState, null // first-loss capital farm ); const instructions = [...bundle.unstakeFromFarmIfNeededIxs, ...bundle.withdrawIxs, ...bundle.postWithdrawIxs]; ``` > [!NOTE] > > Deposits stake shares in the vault's farm, so `unstakeFromFarmIfNeededIxs` must come before `withdrawIxs`. Without it, withdrawing staked shares fails with `CannotWithdrawZeroShares`. **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` > [!NOTE] > > Some vaults need the lookup table for a withdraw to fit in one transaction. Without it, a withdraw from one vault we tested was 1,274 bytes, over Solana's 1,232-byte limit. **Step 7** ### Build and Sign Transaction Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} 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); ``` **Step 8** ### Send and Confirm Transaction Send the withdraw transaction and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Withdraw successful! Signature:', signature); ``` > [!TIP] > > Once the withdraw transaction is confirmed, your vault shares are burned and you receive the underlying tokens plus any accrued interest. > [accordion] What Happens When You Deposit? > > 1. You deposit USDC (or another token) into the vault > 2. You receive vault share tokens (like kVUSDC or similar). If the vault has a rewards farm, the shares are staked in it automatically so they also earn farm rewards > 3. These shares represent your proportional ownership of the vault > 4. The shares appreciate in value as the vault earns yield > [accordion] What Happens When You Withdraw? > > 1. Your shares are unstaked from the vault's farm (if staked) and burned > 2. You receive back the underlying tokens (USDC) based on the current exchange rate # Vault Data and Metrics Source: https://docs.kamino.com/build/earn/vault-data-positions Learn how to retrieve vault TVL, APY, farm rewards, allocation weights, and user share balances using the Kamino SDK and API > [card] [Earn Vaults](/build/earn/index) > > Earn interest on assets ## Get Vault Information Retrieve vault holdings, APY and exchange rate information. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > await getMedianSlotDurationInMsFromLastEpochs() > ); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const apys = await vault.getAPYs(ledgerInstant); > > console.log({ > holdings: (await vault.getVaultHoldings(ledgerInstant)).asJSON(), > actualAPY: apys.actualAPY.netAPY.toString(), > theoreticalAPY: apys.theoreticalAPY.netAPY.toString(), > exchangeRate: (await vault.getExchangeRate(ledgerInstant)).toString(), > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-01-get-vault-info-example/index.ts) ## Get User Position Check a user's share balance and token value for a specific vault. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const vault = new KaminoVault( > rpc, > address('A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'), > await getMedianSlotDurationInMsFromLastEpochs() > ); > > const user = address('883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62'); > > const shares = await vault.getUserShares(user); > const rate = await vault.getExchangeRate(await getCurrentLedgerInstant(rpc)); > > console.log({ > unstakedShares: shares.unstakedShares.toString(), > stakedShares: shares.stakedShares.toString(), > totalShares: shares.totalShares.toString(), > tokens: shares.totalShares.mul(rate).toString(), // the user's position in tokens > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-02-get-user-vault-position-example/index.ts) ## Get All User Positions Fetch a user's share balances across all vaults they participate in. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoManager, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const manager = new KaminoManager( > createSolanaRpc('https://api.mainnet-beta.solana.com'), > await getMedianSlotDurationInMsFromLastEpochs() > ); > > const user = address('883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62'); > const userSharesAllVaults = await manager.getUserSharesBalanceAllVaults(user); > > userSharesAllVaults.forEach((shares, vault) => { > if (shares.totalShares.gt(0)) { > console.log(`User shares in ${vault}:`, shares.totalShares.toString()); > } > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-03-get-user-all-vaults-positions-example/index.ts) ## Deposit to Vault Generate deposit instructions to add tokens to a vault. To sign and send them, follow the [deposit guide](/build/developers/earn/operations/deposit). > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address, createNoopSigner } from '@solana/kit'; > import { KaminoManager, KaminoVault, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > > const { depositIxs, stakeInFarmIfNeededIxs } = await vault.depositIxs( > createNoopSigner(address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY')), // user > new Decimal(100.0), > vaultReservesMap, > farmState, > null > ); > > console.log('Deposit Instructions:', [...depositIxs, ...stakeInFarmIfNeededIxs]); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-04-user-deposit-example/index.ts) ## Withdraw from Vault Generate withdrawal instructions to remove shares from a vault. To sign and send them, follow the [withdraw guide](/build/developers/earn/operations/withdraw). > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address, createNoopSigner } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'), > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > > const { unstakeFromFarmIfNeededIxs, withdrawIxs, postWithdrawIxs } = await vault.withdrawIxs( > createNoopSigner(address('883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62')), // user > new Decimal(1.5), // withdraw 1.5 shares > await getCurrentLedgerInstant(rpc), > vaultReservesMap, > farmState, > null > ); > > console.log('Withdraw Instructions:', [...unstakeFromFarmIfNeededIxs, ...withdrawIxs, ...postWithdrawIxs]); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-05-user-withdraw-example/index.ts) ## Get Vault Allocations View how vault assets are allocated across different reserves with target weights. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoVault, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const vault = new KaminoVault( > createSolanaRpc('https://api.mainnet-beta.solana.com'), > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > await getMedianSlotDurationInMsFromLastEpochs() > ); > > const allocations = await vault.getVaultAllocations(); > > for (const [address, overview] of allocations) { > console.log( > `Reserve: ${address}: weight ${overview.targetWeight.toString()}, allocation: ${overview.ctokenAllocationLamports.toString()}` > ); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-06-get-vault-advanced-info-allocations-example/index.ts) ## Get Vault Incentives Access comprehensive vault incentive data including farm and reserve rewards. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { Farms } from '@kamino-finance/farms-sdk'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoManager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const vaultTokenPrice = new Decimal(1.0); // as it is an USDC vault the token price is 1 > const vaultOverview = await kaminoManager.getVaultOverview( > vault, > vaultTokenPrice, > ledgerInstant, > vaultReservesMap, > await kaminoManager.loadKaminoMarketsForVaultReserves(vaultReservesMap), > await kaminoManager.loadVaultFarmStates([vaultState], vaultReservesMap), > new Farms(rpc), > await kaminoManager.loadKVaultGlobalConfig(), > ledgerInstant > ); > > console.log('delegated farm incentives', vaultOverview.delegatedFarmIncentives); > console.log('reserves farm incentives', vaultOverview.reservesFarmsIncentives); > console.log('vault farm incentives', vaultOverview.vaultFarmIncentives); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-07-get-vault-advanced-info-incentives-example/index.ts) ## Get Vault Metrics History Retrieve historical vault-level performance metrics including TVL, APY, and farm rewards APY over time. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address > > const API_BASE_URL = 'https://api.kamino.finance'; > > const params = new URLSearchParams({ > start: '2024-06-01T00:00:00.000Z', > end: '2025-01-01T00:00:00.000Z', > }).toString(); > > const url = `${API_BASE_URL}/kvaults/vaults/${kvaultPubkey}/metrics/history?${params}`; > const res = await fetch(url); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > const data = await res.json(); > > for (const item of data) { > console.log({ > tvl: item.tvl, > apy: item.apy, > apyFarmRewards: item.apyFarmRewards, > }); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-10-get-vault-historical-info-example/index.ts) ## Get User Position History Retrieve historical performance metrics for a user's position in a specific vault. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const kvaultPubkey = 'A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'; > const ownerPubkey = '883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62'; // user > > const API_BASE_URL = 'https://api.kamino.finance'; > > const params = new URLSearchParams({ > start: '2024-01-01T00:00:00.000Z', > end: '2025-10-01T00:00:00.000Z', > }).toString(); > > const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/history?${params}`; > const res = await fetch(url); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > const data = await res.json(); > > for (const item of data) { > console.log({ > createdOn: item.createdOn, > sharesAmount: item.sharesAmount, > usdAmount: item.usdAmount, > apy: item.apy, > cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, > }); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-08-get-user-vault-position-historical-info-example/index.ts) ## Get All User Position History Fetch cumulative historical metrics for a user across all their vault positions. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address > > const API_BASE_URL = 'https://api.kamino.finance'; > > const params = new URLSearchParams({ > start: '2024-01-01T00:00:00.000Z', > end: '2025-11-20T00:00:00.000Z', > }).toString(); > > const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/metrics/history?${params}`; > const res = await fetch(url); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > const data = await res.json(); > > for (const item of data) { > console.log({ > createdOn: item.createdOn, > usdAmount: item.usdAmount, > solAmount: item.solAmount, > weightedApy: item.weightedApy, > cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, > }); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-09-get-user-all-vaults-positions-historical-info-example/index.ts) ## Get User Vault Position History Access historical metrics for a user's position in a specific vault over time. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address > const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address > > const API_BASE_URL = 'https://api.kamino.finance'; > > const params = new URLSearchParams({ > start: '2024-01-01T00:00:00.000Z', > end: '2025-01-01T00:00:00.000Z', > }).toString(); > > const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/history?${params}`; > const res = await fetch(url); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > const data = await res.json(); > > for (const item of data) { > console.log({ > createdOn: item.createdOn, > sharesAmount: item.sharesAmount, > usdAmount: item.usdAmount, > apy: item.apy, > cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, > }); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-10-get-vault-historical-info-example/index.ts) ## Get User P\&L Calculate a user's profit and loss for their position in a vault. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address > const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address > > const API_BASE_URL = 'https://api.kamino.finance'; > > const url = `${API_BASE_URL}/kvaults/${kvaultPubkey}/users/${ownerPubkey}/pnl`; > const res = await fetch(url); > if (!res.ok) { > console.log(`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, > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-11-get-vault-user-pnl-example/index.ts) ## Vault Revenue Share Earn revenue by deploying vaults with custom fee structures. Set performance fees on profits and management fees on assets under management. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { address, generateKeyPairSigner } from '@solana/kit'; > import { KaminoVaultConfig } from '@kamino-finance/klend-sdk'; > import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; > import { Decimal } from 'decimal.js'; > > const adminSigner = await generateKeyPairSigner(); > const tokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC > > const kaminoVaultConfig = new KaminoVaultConfig({ > admin: adminSigner, > tokenMint: tokenMint, > tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, > performanceFeeRatePercentage: new Decimal(10.0), // 10% performance fee on profits > managementFeeRatePercentage: new Decimal(1.0), // 1% annual management fee on AUM > name: 'Revenue Share Vault', > vaultTokenSymbol: 'kUSDC', > vaultTokenName: 'kUSDC receipt', > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) # Get farm management history Source: https://docs.kamino.com/build/farms/get-farm-management-history /kamino-api.json get /farms/{farmPubkey}/management-history Get management instructions for a specific farm (with pagination). # Get farm transactions Source: https://docs.kamino.com/build/farms/get-farm-transactions /kamino-api.json get /farms/{farmPubkey}/transactions Get transactions for a specific farm (with pagination). # Get user farms transactions Source: https://docs.kamino.com/build/farms/get-user-farms-transactions /kamino-api.json get /farms/users/{pubkey}/transactions Get all farms program transactions for a given user (with pagination). # Build Source: https://docs.kamino.com/build/index Integrate Kamino for yield or crypto loans # Build on Kamino Deposit to earn, lend or borrow programmatically, and use our APIs to read market data and user positions. Available via TypeScript SDK, REST APIs and full working examples. [ Get Started ](/build/developers/overview) ![Build on Kamino section background illustration](https://mintcdn.com/kamino-3d73a151/lP5bd214efImJ7R7/images/bg-hero.png?fit=max\&auto=format\&n=lP5bd214efImJ7R7\&q=85\&s=438df1f8f5bc6c92ac322c32ca8bc060) ## Integration Guides > [card] [Earn - Kamino Vaults](/build/earn) > > Lending strategies to earn yield > > * Vault and user data > * Current & historical data > * Deposit & Withdraw txn > * Deploy vaults > [card] [Borrow - Kamino Lend](/build/borrow) > > Flexible lending and borrowing > > * User and PnL data > * Historical yield & liquidity > * Deposit & Withdraw txn > * Borrow & Repay txn > [card] [API Reference](/build/api-reference/introduction) > > APIs for data & transactions > > * Current & historical data > * Build transactions > * Earn vaults > * Borrow lend ## Quick Snippets > [tab] Deposit on Earn > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address, generateKeyPairSigner } from '@solana/kit'; > import { KaminoManager, KaminoVault, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > import { Decimal } from 'decimal.js'; > > const signer = await generateKeyPairSigner(); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault(rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), slotDuration); > > const vaultState = await vault.getState(); > const { depositIxs } = await vault.depositIxs( > signer, > new Decimal(100.0), > await manager.loadVaultReserves(vaultState), > await manager.loadVaultFarmState(vaultState), > null > ); > ``` > [tab] Borrow > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address, generateKeyPairSigner } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import BN from 'bn.js'; > > const signer = await generateKeyPairSigner(); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const market = await KaminoMarket.load( > rpc, > address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'), > await getMedianSlotDurationInMsFromLastEpochs() > ); > const usdtReserve = market!.getExistingFloatRateReserveByMint(address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB')); > > const borrowAction = await KaminoAction.buildBorrowTxns({ > kaminoMarket: market!, > amount: new BN(1_000_000), > reserveAddress: usdtReserve.address, > owner: signer, > obligation: new VanillaObligation(PROGRAM_ID), > useV2Ixs: true, > scopeRefreshConfig: undefined, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > > ``` > [tab] Get Earn balances > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), > await getMedianSlotDurationInMsFromLastEpochs() > ); > > const user = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > const shares = await vault.getUserShares(user); > const rate = await vault.getExchangeRate(await getCurrentLedgerInstant(rpc)); > > console.log({ > shares: shares.totalShares.toString(), > tokens: shares.totalShares.mul(rate).toString(), > }); > ``` > [tab] Get Loan health > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoMarket, VanillaObligation, PROGRAM_ID, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > > const userAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > const obligation = await market!.getObligationByWallet(userAddress, new VanillaObligation(PROGRAM_ID)); > > console.log('Loan-to-Value:', obligation!.loanToValue().toFixed(4)); > > ``` > [tab] Get Market data > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const market = await KaminoMarket.load( > createSolanaRpc('https://api.mainnet-beta.solana.com'), > address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'), > await getMedianSlotDurationInMsFromLastEpochs() > ); > > console.log({ > totalDepositsUsd: market!.getTotalDepositTVL().toFixed(2), > totalBorrowsUsd: market!.getTotalBorrowTVL().toFixed(2), > }); > > ``` ## Earn Tutorials Quick tutorials for depositing into Earn vaults. > [card] [Earn via API](/build/recipes/earn/earn-via-api) > > Deposit to vaults using REST API > [card] [Earn via SDK](/build/recipes/earn/earn-via-sdk) > > Deposit to vaults using TypeScript SDK > [card] [Earn with Privy Wallet](/build/recipes/earn/earn-with-privy) > > Integrate deposits with Privy embedded wallets ## Deploy an Earn Vault and Get Revenue Share Any builder can deploy a private or public Earn Vault and get revenue share in just a few lines of code. ```typescript theme={"theme":"css-variables"} const tokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const kaminoManager = new KaminoManager(rpc, slotDuration); const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: tokenMint, tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(10.0), managementFeeRatePercentage: new Decimal(1.0), name: 'Earn USDC Vault', vaultTokenSymbol: 'kUSDC', vaultTokenName: 'kUSDC receipt', }); const { vault: vaultSigner, initVaultIxs: instructions } = await kaminoManager.createVaultIxs(kaminoVaultConfig); ``` [Start Earning ](/build/earn) ## Kamino management portal No code solution to deploy markets, vaults and rewards. > [card] [Earn Vaults](https://kamino.com/curators/vaults) > > Deploy custom earn vault and earn revenue share. > [card] [Borrow markets](https://kamino.com/curators/markets) > > Choose collateral, debt, interest rate and oracle. > [card] [Incentive campaigns](https://manage.kamino.com) > > Incentive campaigns, points and more. [manage.kamino.com ](https://manage.kamino.com) ## Developer Tools > [card] [TypeScript SDK](https://github.com/Kamino-Finance/klend-sdk) > [card] [Earn Code Examples](/build/earn/index) > [card] [Borrow Code Examples](/build/borrow/index) > [card] [Smart Contract Repo](https://github.com/Kamino-Finance/klend) Found a vulnerability? Kamino's [Bug Bounty program](/security/bug-bounty) on Sherlock offers rewards up to 1,000,000 USDC. # Get instructions to deposit into a kvault Source: https://docs.kamino.com/build/kamino-earn-deposit/get-instructions-to-deposit-into-a-kvault /ktx-api.json post /ktx/kvault/deposit-instructions Instructions to deposit tokens into a specified Kamino Earn Vault. Additionally includes lookup tables to use to compress transaction size. An optional `memo` is added as an SPL memo instruction. # Get transaction to deposit into a kvault Source: https://docs.kamino.com/build/kamino-earn-deposit/get-transaction-to-deposit-into-a-kvault /ktx-api.json post /ktx/kvault/deposit Deposit tokens into a specified Kamino Earn Vault. An optional `memo` is added to the transaction as an SPL memo instruction. # Get all user KVault positions Source: https://docs.kamino.com/build/kamino-earn-user/get-all-user-kvault-positions /kamino-api.json get /kvaults/users/{pubkey}/positions Get a list of user positions for each Kamino Earn Vault the user has currently deposited into. Returns staked and unstaked shares. # Get historical user metrics for a single KVault Source: https://docs.kamino.com/build/kamino-earn-user/get-historical-user-metrics-for-a-single-kvault /kamino-api.json get /kvaults/users/{userPubkey}/vaults/{vaultPubkey}/metrics/history Get historical timeseries for one vault position. Automatic selection picks minute rows for ranges up to 2 days, hourly rows for ranges under 32 days, and daily rows otherwise, returning finer rows for positions younger than those windows, measured from the first resampled bucket. frequency=minute is limited to ranges of at most 32 days. frequency=day&view=chart returns only UTC daily bucket timestamps, USD balances and cumulative USD interest. The newest daily bucket may be partial; use the summary endpoint for the latest balance. Open-ended histories can be up to five minutes plus processing time old. # Get historical user metrics for all KVault positions Source: https://docs.kamino.com/build/kamino-earn-user/get-historical-user-metrics-for-all-kvault-positions /kamino-api.json get /kvaults/users/{pubkey}/metrics/history Get historical timeseries of total usd/sol/interest/apy for all user Kamino Earn Vault positions # Get season user rewards Source: https://docs.kamino.com/build/kamino-earn-user/get-season-user-rewards /kamino-api.json get /kvaults/users/{pubkey}/rewards Get user season points rewards for each Kamino Earn Vault which the user has invested in # Get user KVault PnL Source: https://docs.kamino.com/build/kamino-earn-user/get-user-kvault-pnl /kamino-api.json get /kvaults/users/{userPubkey}/vaults/{vaultPubkey}/pnl Get current PnL and cost basis of user vault position # Get user KVault PnL history Source: https://docs.kamino.com/build/kamino-earn-user/get-user-kvault-pnl-history /kamino-api.json get /kvaults/users/{userPubkey}/vaults/{vaultPubkey}/pnl/history Get PnL and cost basis history of user vault position # Get user KVault transactions Source: https://docs.kamino.com/build/kamino-earn-user/get-user-kvault-transactions /kamino-api.json get /kvaults/users/{pubkey}/transactions Get all Kamino Earn Vault transactions for a given user # Get user position for a specific KVault Source: https://docs.kamino.com/build/kamino-earn-user/get-user-position-for-a-specific-kvault /kamino-api.json get /kvaults/users/{userPubkey}/positions/{vaultPubkey} Get a single user position for a Kamino Earn Vault the user currently has currently deposited into. Returns staked and unstaked shares. # Get icon for KVault token Source: https://docs.kamino.com/build/kamino-earn-vault-metadata/get-icon-for-kvault-token /kamino-api.json get /kvaults/mints/{pubkey}/metadata/image.svg Get the SVG icon for a given Kamino Earn Vault receipt token mint # Get metadata for KVault token Source: https://docs.kamino.com/build/kamino-earn-vault-metadata/get-metadata-for-kvault-token /kamino-api.json get /kvaults/mints/{pubkey}/metadata Get metadata for a given Kamino Earn Vault receipt token mint # Bulk get KVault transactions Source: https://docs.kamino.com/build/kamino-earn-vaults/bulk-get-kvault-transactions /kamino-api.json post /kvaults/transactions Bulk get all Kamino Earn Vault transactions with paginated access (max 1000 transactions returned in each response). Private (authorized) API access only, please add a basic auth header to your request. # Compare historical KVault returns Source: https://docs.kamino.com/build/kamino-earn-vaults/compare-historical-kvault-returns /kamino-api.json get /kvaults/vaults/{pubkey}/returns-comparison Compare KVault historical returns with SOFR and the DeFi USD benchmark. Benchmark series are forward-filled for up to 7 days and return null beyond that. # Get all kvaults Source: https://docs.kamino.com/build/kamino-earn-vaults/get-all-kvaults /kamino-api.json get /kvaults/vaults Get Kamino Earn Vaults. Omit type for all on-chain vaults. Use live or privateCredit for CDN-listed vaults. # Get current KVault allocations Source: https://docs.kamino.com/build/kamino-earn-vaults/get-current-kvault-allocations /kamino-api.json get /kvaults/vaults/{pubkey}/allocations Get current reserve allocations, utilization, supply APYs, and market collateral for a Kamino Earn Vault # Get current KVault metrics Source: https://docs.kamino.com/build/kamino-earn-vaults/get-current-kvault-metrics /kamino-api.json get /kvaults/vaults/{pubkey}/metrics Get current Kamino Earn Vault metrics for a given vault # Get current metrics for multiple KVaults Source: https://docs.kamino.com/build/kamino-earn-vaults/get-current-metrics-for-multiple-kvaults /kamino-api.json get /kvaults/vaults/metrics Get current Kamino Earn Vault metrics with cursor pagination or an address filter # Get currently queued withdraw-ticket redemptions for a vault Source: https://docs.kamino.com/build/kamino-earn-vaults/get-currently-queued-withdraw-ticket-redemptions-for-a-vault /kamino-api.json get /kvaults/vaults/{pubkey}/enqueued-withdraw-transactions Returns `enqueueToWithdraw` klend transactions that were triggered by a kvault `redeemInKind` on this vault and whose underlying withdraw ticket is still queued on-chain (i.e. has not been fully redeemed or cancelled). # Get historical KVault allocation volume Source: https://docs.kamino.com/build/kamino-earn-vaults/get-historical-kvault-allocation-volume /kamino-api.json get /kvaults/vaults/{pubkey}/allocation-volume/history Get historical Kamino Earn Vault allocation volume for a given vault and date range (max 1 year) # Get historical KVault metrics Source: https://docs.kamino.com/build/kamino-earn-vaults/get-historical-kvault-metrics /kamino-api.json get /kvaults/vaults/{pubkey}/metrics/history Get historical Kamino Earn Vault metrics for a given vault, between an optional range of dates # Get historical metrics for multiple KVaults Source: https://docs.kamino.com/build/kamino-earn-vaults/get-historical-metrics-for-multiple-kvaults /kamino-api.json get /kvaults/vaults/metrics/history Get historical Kamino Earn Vault metrics for multiple vaults between an optional range of dates. The response is keyed by vault public key; unknown vaults are omitted. # Get KVault account data Source: https://docs.kamino.com/build/kamino-earn-vaults/get-kvault-account-data /kamino-api.json get /kvaults/vaults/account-data Fetch base64-encoded account data for Kamino Earn Vaults together with the lending markets, reserves and farms they allocate into, so clients can hydrate SDK objects without any getProgramAccounts calls. Omit the vaults parameter to include every vault; unknown vaults are omitted from the response. # Get KVault allocation transactions Source: https://docs.kamino.com/build/kamino-earn-vaults/get-kvault-allocation-transactions /kamino-api.json get /kvaults/vaults/{pubkey}/allocation-transactions Get cursor-paginated Kamino Earn Vault allocation transactions. Positive token amounts are reserve deposits and negative amounts are reserve withdrawals. # Get KVault by address Source: https://docs.kamino.com/build/kamino-earn-vaults/get-kvault-by-address /kamino-api.json get /kvaults/vaults/{pubkey} Get a single Kamino Earn Vault by the KVault account address # Get KVault transactions by vault Source: https://docs.kamino.com/build/kamino-earn-vaults/get-kvault-transactions-by-vault /kamino-api.json post /kvaults/vaults/{pubkey}/transactions Get Kamino Earn Vault transactions for a given vault address, one row per instruction. `end` defaults to the current time. Request the next page with `paginationToken` while `hasMore` is true. # Get lifetime earnings of KVault users Source: https://docs.kamino.com/build/kamino-earn-vaults/get-lifetime-earnings-of-kvault-users /kamino-api.json post /kvaults/vaults/{pubkey}/users/lifetime-earnings Get the lifetime earnings of up to 100 wallets in one Kamino Earn Vault, across every position each wallet opened and closed. Earnings are tokens withdrawn minus tokens deposited plus the value of the open position, net of vault fees and withdrawal penalties, so they can be negative. Every value is measured at the latest vault snapshot (`asOf`), taken every 15 minutes; deposits and withdrawals after it are not counted yet. Wallets without vault activity return zeros. Returns 503 when the vault has no snapshot from the last 24 hours. Private (authorized) API access only, please add a basic auth header to your request. # Get stats for a KVault Source: https://docs.kamino.com/build/kamino-earn-vaults/get-stats-for-a-kvault /kamino-api.json get /kvaults/vaults/{pubkey}/stats Get derived stats for a Kamino Earn Vault computed from the current on-chain state: supply APY breakdown (base gross/net, vault farm incentives, reserve farm incentives), per-token vault farm rewards, holdings, share price, utilization, instant liquidity and the per-reserve allocation breakdown. Returns 404 when the vault does not exist. # Get stats for multiple KVaults Source: https://docs.kamino.com/build/kamino-earn-vaults/get-stats-for-multiple-kvaults /kamino-api.json get /kvaults/vaults/batch/stats Get derived stats for Kamino Earn Vaults computed from the current on-chain state: supply APY breakdown (base gross/net, vault farm incentives, reserve farm incentives), per-token vault farm rewards, holdings, share price, utilization, instant liquidity and the per-reserve allocation breakdown. The response is keyed by vault public key; unknown vaults are omitted. Omit the vaults parameter to include every vault. # Get the live withdraw queue of a KVault Source: https://docs.kamino.com/build/kamino-earn-vaults/get-the-live-withdraw-queue-of-a-kvault /kamino-api.json get /kvaults/vaults/{pubkey}/withdraw-queue Returns the on-chain withdraw queue of every allocation reserve of a Kamino Earn Vault: market ticket flags, queue counters, queued and available liquidity, and the open withdraw tickets of every owner on the reserve, not only those issued through this vault. Fully redeemed tickets are closed on-chain and do not appear; use `/kvaults/vaults/:pubkey/enqueued-withdraw-transactions` for history. `wallet` filters the returned tickets only, `position` and the amounts ahead always count the whole reserve queue. Returns 404 when the vault does not exist. # Get the share distribution of a KVault Source: https://docs.kamino.com/build/kamino-earn-vaults/get-the-share-distribution-of-a-kvault /kamino-api.json get /kvaults/vaults/{pubkey}/holders Get the holders of a Kamino Earn Vault ordered by position size, largest first. Shares held in the wallet and shares staked in the vault farm are reported separately and as a total. Read from the most recent vault state snapshot, whose timestamp and total shares issued are returned alongside the holders so each position can be expressed as a share of the vault. Private (authorized) API access only, please add a basic auth header to your request. # Get instructions to withdraw from a kvault Source: https://docs.kamino.com/build/kamino-earn-withdraw/get-instructions-to-withdraw-from-a-kvault /ktx-api.json post /ktx/kvault/withdraw-instructions Instructions to withdraw tokens from a specified Kamino Earn Vault. Includes lookup tables for transaction compression. An optional `memo` is added as an SPL memo instruction. # Get transaction to withdraw from a kvault Source: https://docs.kamino.com/build/kamino-earn-withdraw/get-transaction-to-withdraw-from-a-kvault /ktx-api.json post /ktx/kvault/withdraw Withdraw tokens from a specified Kamino Earn Vault. An optional `memo` is added as an SPL memo instruction. # Get all obligations with open borrow orders in a market Source: https://docs.kamino.com/build/kamino-lend-borrow-orders/get-all-obligations-with-open-borrow-orders-in-a-market /kamino-api.json get /v2/kamino-market/{pubkey}/obligations-with-open-borrow-orders Returns all obligations in the given market that have an active (unfilled or partially filled) borrow order. # Get borrow order fills for an obligation Source: https://docs.kamino.com/build/kamino-lend-borrow-orders/get-borrow-order-fills-for-an-obligation /kamino-api.json get /v2/kamino-market/obligations/{pubkey}/borrow-order-fills Returns the fill history for the active borrow order of an obligation, in chronological order. # Get instructions to borrow liquidity from a klend reserve Source: https://docs.kamino.com/build/kamino-lend-borrow/get-instructions-to-borrow-liquidity-from-a-klend-reserve /ktx-api.json post /ktx/klend/borrow-instructions Instructions to borrow liquidity from the specified Kamino Lend market reserve. Additionally includes lookup tables to use to compress transaction size # Get transaction to borrow liquidity from a klend reserve Source: https://docs.kamino.com/build/kamino-lend-borrow/get-transaction-to-borrow-liquidity-from-a-klend-reserve /ktx-api.json post /ktx/klend/borrow Borrow liquidity from the specified Kamino Lend market reserve # Get instructions to deposit into a klend reserve Source: https://docs.kamino.com/build/kamino-lend-deposit/get-instructions-to-deposit-into-a-klend-reserve /ktx-api.json post /ktx/klend/deposit-instructions Instructions to deposit tokens into the specified Kamino Lend market reserve. Additionally includes lookup tables to use to compress transaction size # Get transaction to deposit into a klend reserve Source: https://docs.kamino.com/build/kamino-lend-deposit/get-transaction-to-deposit-into-a-klend-reserve /ktx-api.json post /ktx/klend/deposit Deposit tokens into the specified Kamino Lend market reserve. An optional `memo` is added to the transaction as an SPL memo instruction. # Get all Kamino Markets config Source: https://docs.kamino.com/build/kamino-lend-markets/get-all-kamino-markets-config /kamino-api.json get /v2/kamino-market Get all Kamino Lending markets configuration for a specific program ID. This is the V2 endpoint that allows filtering by program ID instead of cluster. # Get charts for a market Source: https://docs.kamino.com/build/kamino-lend-markets/get-charts-for-a-market /kamino-api.json get /markets/{marketPubkey}/charts Get historical total borrowed, total supplied, and obligation counts for a market. # Get collateral reserves with borrowable reserves Source: https://docs.kamino.com/build/kamino-lend-markets/get-collateral-reserves-with-borrowable-reserves /kamino-api.json get /markets/collateral-reserves Derive one Borrow market row per collateral reserve and debt category from each configured Kamino Lend market. # Get Kamino Market config Source: https://docs.kamino.com/build/kamino-lend-markets/get-kamino-market-config /kamino-api.json get /v2/kamino-market/{pubkey} Get configuration for a specific Kamino Lending market by market address. Optionally filter by program ID. # Get KLend Market metrics history Source: https://docs.kamino.com/build/kamino-lend-markets/get-klend-market-metrics-history /kamino-api.json get /kamino-market/{pubkey}/metrics/history Get historical metrics (TVL and number of obligations) for a Kamino Lending market over a specified time range. # Get KLend market reserves account data Source: https://docs.kamino.com/build/kamino-lend-markets/get-klend-market-reserves-account-data /kamino-api.json get /kamino-market/reserves/account-data Fetch reserve account data for given Klend markets. Returns base64-encoded account data for all reserves in the specified markets. # Get KLend reserve history Source: https://docs.kamino.com/build/kamino-lend-markets/get-klend-reserve-history /kamino-api.json get /kamino-market/{marketPubkey}/reserves/{reservePubkey}/metrics/history Get historical metrics for a specific reserve in a Kamino Lending market over a specified time range with configurable frequency (hour or day). Without a frequency, ranges shorter than 32 days are hourly and longer ranges are daily. APYs, amounts and capped available liquidity are means of raw snapshots in each UTC bucket. Other metrics retain the last snapshot. # Get max leverage per Multiply pair Source: https://docs.kamino.com/build/kamino-lend-markets/get-max-leverage-per-multiply-pair /kamino-api.json get /markets/multiply-pairs Return the protocol risk ceiling of every Multiply pair configured in the Kamino CDN, including hidden pairs and pairs in hidden or deprecated markets. Values are raw protocol limits under the elevation group the pair auto-selects, with no safety factor applied. # Get metadata for a market Source: https://docs.kamino.com/build/kamino-lend-markets/get-metadata-for-a-market /kamino-api.json get /markets/{marketPubkey}/metadata Get metadata (name, description, curation status, and reserve public keys) for a single Kamino Lend market. # Get metadata for multiple markets Source: https://docs.kamino.com/build/kamino-lend-markets/get-metadata-for-multiple-markets /kamino-api.json get /markets/batch/metadata Get metadata (name, description, curation status, and reserve public keys) for Kamino Lend markets. When market is omitted, all configured markets are returned. The response is keyed by market public key; unknown markets are omitted. # Get metrics for leverage/multiply vaults Source: https://docs.kamino.com/build/kamino-lend-markets/get-metrics-for-leveragemultiply-vaults /kamino-api.json get /kamino-market/{pubkey}/leverage/metrics Get aggregated metrics for all leverage and multiply positions in a Kamino Lending market, including average leverage, total borrowed, total deposited, and number of obligations. # Get metrics for market reserves Source: https://docs.kamino.com/build/kamino-lend-markets/get-metrics-for-market-reserves /kamino-api.json get /kamino-market/{pubkey}/reserves/metrics Get current metrics for all reserves in a Kamino Lending market, including APY, TVL, borrow/supply amounts, and LTV ratios. # Get instructions to repay debt of a klend reserve Source: https://docs.kamino.com/build/kamino-lend-repay/get-instructions-to-repay-debt-of-a-klend-reserve /ktx-api.json post /ktx/klend/repay-instructions Instructions to repay a debt position for the specified Kamino Lend market reserve. Additionally includes lookup tables to use to compress transaction size # Get transaction to repay debt of a klend reserve Source: https://docs.kamino.com/build/kamino-lend-repay/get-transaction-to-repay-debt-of-a-klend-reserve /ktx-api.json post /ktx/klend/repay Repay a debt position for the specified Kamino Lend market reserve # Get charts for a reserve Source: https://docs.kamino.com/build/kamino-lend-reserves/get-charts-for-a-reserve /kamino-api.json get /reserves/{reservePubkey}/charts Get the current raw borrow rate curve and historical base supply and borrow APYs for a reserve. # Get stats for a reserve Source: https://docs.kamino.com/build/kamino-lend-reserves/get-stats-for-a-reserve /kamino-api.json get /reserves/{reservePubkey}/stats Get current raw and cap-aware reserve liquidity, borrowing caps and counters, base APYs with historical averages, underlying token yield and UI-matching APY breakdowns, utilization with historical averages, auto-deleveraging settings, reserve farm rewards, pair-specific incentives, partner points programs and the Scope oracle composition of the price and TWAP chains for one reserve. Pair-specific incentives and points programs are not included in the APY breakdown totals. # Get stats for multiple reserves Source: https://docs.kamino.com/build/kamino-lend-reserves/get-stats-for-multiple-reserves /kamino-api.json get /reserves/batch/stats Get current raw and cap-aware reserve liquidity, borrowing caps and counters, base APYs with historical averages, underlying token yield and UI-matching APY breakdowns, utilization with historical averages, auto-deleveraging settings, reserve farm rewards, pair-specific incentives, partner points programs and the Scope oracle composition of the price and TWAP chains. Pair-specific incentives and points programs are not included in the APY breakdown totals. Select reserves directly with the reserve query parameter or expand all reserves from lending markets with the market query parameter. The response is keyed by reserve public key; unknown reserves and markets are omitted. # Get bulk market transactions Source: https://docs.kamino.com/build/kamino-lend-transactions/get-bulk-market-transactions /kamino-api.json post /v2/kamino-market/{pubkey}/transactions Get bulk Kamino Lend transactions for a given market, filtered by instruction name and date range. Private (authorized) API access only, please add a basic auth header to your request. # Get bulk market transactions (v3) Source: https://docs.kamino.com/build/kamino-lend-transactions/get-bulk-market-transactions-v3 /kamino-api.json post /v3/kamino-market/{pubkey}/transactions Get bulk Kamino Lend transactions for a given market, filtered by instruction name and date range. Returns obligation transactions and withdraw-queue transactions as sibling arrays; exactly one is populated per request depending on the ix name. Private (authorized) API access only, please add a basic auth header to your request. # Get obligation transactions Source: https://docs.kamino.com/build/kamino-lend-transactions/get-obligation-transactions /kamino-api.json get /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/transactions Get all Kamino Lend transactions for a given obligation. # Get paginated user transaction history Source: https://docs.kamino.com/build/kamino-lend-transactions/get-paginated-user-transaction-history /kamino-api.json get /v3/kamino-market/users/{userPubkey}/transaction-history Newest first across all markets. Long no-op rollover runs are collapsed. Limits count instructions; all legs of an instruction are returned together. # Get user transactions Source: https://docs.kamino.com/build/kamino-lend-transactions/get-user-transactions /kamino-api.json get /v2/kamino-market/{marketPubkey}/users/{userPubkey}/transactions Get all Kamino Lend transactions for a given user. # Get user transactions across all markets Source: https://docs.kamino.com/build/kamino-lend-transactions/get-user-transactions-across-all-markets /kamino-api.json get /v2/kamino-market/users/{userPubkey}/transactions Get all Kamino Lend transactions for a given user across all markets. # Get user transactions across all markets (v3) Source: https://docs.kamino.com/build/kamino-lend-transactions/get-user-transactions-across-all-markets-v3 /kamino-api.json get /v3/kamino-market/users/{userPubkey}/transactions Get all Kamino Lend transactions for a given user across all markets, including withdraw-queue transactions. # Get user transactions (v3) Source: https://docs.kamino.com/build/kamino-lend-transactions/get-user-transactions-v3 /kamino-api.json get /v3/kamino-market/{marketPubkey}/users/{userPubkey}/transactions Get all Kamino Lend transactions for a given user in a market, including withdraw-queue transactions. # Get all user obligations Source: https://docs.kamino.com/build/kamino-lend-user-loans/get-all-user-obligations /kamino-api.json get /kamino-market/{marketPubkey}/users/{userPubkey}/obligations Get all obligations (loans) for a specific user wallet in a Kamino Lending market. # Get information about a loan (obligation) Source: https://docs.kamino.com/build/kamino-lend-user-loans/get-information-about-a-loan-obligation /kamino-api.json get /klend/loans/{pubkey} Fetches information about a loan # Get KLend obligation history Source: https://docs.kamino.com/build/kamino-lend-user-loans/get-klend-obligation-history /kamino-api.json get /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/metrics/history Get historical metrics for a specific obligation in a Kamino Lending market. This V2 endpoint supports using stake rate for obligation value calculation when `useStakeRateForObligation` is true. Points are hourly for ranges shorter than 32 days and daily otherwise. Hourly data is kept for 34 days, so ranges starting more than 33 days ago are returned daily. # Get obligation analytics history Source: https://docs.kamino.com/build/kamino-lend-user-loans/get-obligation-analytics-history /kamino-api.json get /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/analytics/history Get precomputed position values and signed APY components relative to equity in [start, end). Omit start for full history; end defaults to now. Daily history may end with the latest hourly bucket from today or yesterday when that day is not yet covered by a daily row. Finalized data typically lags by 1-2 hours. # Get profit and loss for an obligation Source: https://docs.kamino.com/build/kamino-lend-user-loans/get-profit-and-loss-for-an-obligation /kamino-api.json get /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/pnl Get profit and loss (PnL) for a specific obligation. For xSOL pairs, `useStakeRate` can be set to true to calculate the PnL using the stake rate. # Get profit and loss history for an obligation Source: https://docs.kamino.com/build/kamino-lend-user-loans/get-profit-and-loss-history-for-an-obligation /kamino-api.json get /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/pnl/history Returns transaction and periodic mark-to-market PnL for the current obligation. Snapshots are hourly for positions younger than 32 days and daily otherwise, timestamped at observation time. Hourly snapshots are kept for 34 days, so positions opened more than 33 days ago are marked daily. Periodic points that cannot be valued are omitted. Optional start (inclusive) and end (exclusive) filter the history; totals always describe the current position. For xSOL pairs, useStakeRate uses stake-rate pricing. # Get instructions to withdraw from a klend reserve Source: https://docs.kamino.com/build/kamino-lend-withdraw/get-instructions-to-withdraw-from-a-klend-reserve /ktx-api.json post /ktx/klend/withdraw-instructions Instructions to withdraw tokens from the specified Kamino Lend market reserve. Additionally includes lookup tables to use to compress transaction size # Get transaction to withdraw from a klend reserve Source: https://docs.kamino.com/build/kamino-lend-withdraw/get-transaction-to-withdraw-from-a-klend-reserve /ktx-api.json post /ktx/klend/withdraw Withdraw tokens from the specified Kamino Lend market reserve # Get a KLend deposit position history Source: https://docs.kamino.com/build/kamino-lend-yield/get-a-klend-deposit-position-history /kamino-api.json get /v3/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/deposits/{reservePubkey}/metrics/history Get value, APY, and lifetime cumulative interest snapshots for one reserve deposit in an obligation. # Get interest fees earned per obligation Source: https://docs.kamino.com/build/kamino-lend-yield/get-interest-fees-earned-per-obligation /kamino-api.json get /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/interest-fees Get historical interest fees earned for a specific obligation. Returns total fees earned and historical fee breakdown by token. # Get interest fees paid per obligation Source: https://docs.kamino.com/build/kamino-lend-yield/get-interest-fees-paid-per-obligation /kamino-api.json get /v2/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/interest-paid Get historical interest fees paid for a specific obligation. Returns total fees paid and historical fee breakdown by token. # Get KLend reserve borrow APY and median staking APY history Source: https://docs.kamino.com/build/kamino-lend-yield/get-klend-reserve-borrow-apy-and-median-staking-apy-history /kamino-api.json get /kamino-market/{marketPubkey}/reserves/{reservePubkey}/borrow-and-staking-apys/history/median Get historical borrow interest APY and median staking APY data for reserves that contain LST tokens with staking yield. Uses median staking APY values. Hourly and daily borrow APYs are means of raw snapshots in each UTC bucket. # Get KLend reserve borrow APY and staking APY history Source: https://docs.kamino.com/build/kamino-lend-yield/get-klend-reserve-borrow-apy-and-staking-apy-history /kamino-api.json get /kamino-market/{marketPubkey}/reserves/{reservePubkey}/borrow-and-staking-apys/history Get historical borrow interest APY and staking APY data for reserves that contain LST tokens with staking yield. Used for Multiply underlying APY calculations. Hourly and daily borrow APYs are means of raw snapshots in each UTC bucket. # Get KLend reward history Source: https://docs.kamino.com/build/kamino-lend-yield/get-klend-reward-history /kamino-api.json get /klend/{depositReservePubkey}/{borrowReservePubkey}/rewards/history Fetches historical KLend reward metrics for a specific deposit and borrow reserve pair # Get KLend rewards Source: https://docs.kamino.com/build/kamino-lend-yield/get-klend-rewards /kamino-api.json get /klend/rewards Fetches all active KLend reward metrics for a specific points source # Get stored interest fees earned per obligation Source: https://docs.kamino.com/build/kamino-lend-yield/get-stored-interest-fees-earned-per-obligation /kamino-api.json get /v3/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/interest-fees Get historical interest fees earned for a specific obligation from stored cumulative interest snapshots. # Get stored interest fees paid per obligation Source: https://docs.kamino.com/build/kamino-lend-yield/get-stored-interest-fees-paid-per-obligation /kamino-api.json get /v3/kamino-market/{marketPubkey}/obligations/{obligationPubkey}/interest-paid Get historical interest fees paid for a specific obligation from stored cumulative interest snapshots. # Get user KLend rewards Source: https://docs.kamino.com/build/kamino-lend-yield/get-user-klend-rewards /kamino-api.json get /klend/users/{pubkey}/rewards Fetches KLend reward data for a specific user and points source # Get Liquidity transactions by shareholder wallet address Source: https://docs.kamino.com/build/kamino-liquidity/get-liquidity-transactions-by-shareholder-wallet-address /kamino-api.json get /v2/shareholders/{pubkey}/transactions Get all Kamino Liquidity strategy transactions for a provided shareholder wallet address. # Get Swap transactions by user wallet address Source: https://docs.kamino.com/build/kamino-swap/get-swap-transactions-by-user-wallet-address /kamino-api.json get /kamino-swap/users/{pubkey}/transactions Get the Swap transaction history for a provided user wallet address, with optional limit and offset. # Find Lookup Tables for addresses Source: https://docs.kamino.com/build/lookup-tables/find-lookup-tables-for-addresses /kamino-api.json post /luts/find-minimal Finds the smallest set of Lookup Table (LUT) addresses that together cover all the provided Solana addresses. Optionally verifies active LUTs on-chain. # Get managed LUTs by product type Source: https://docs.kamino.com/build/lookup-tables/get-managed-luts-by-product-type /kamino-api.json get /luts/managed/product-type/{productType} Returns all active lookup table addresses grouped by product for a given product type. # Get managed LUTs for a product Source: https://docs.kamino.com/build/lookup-tables/get-managed-luts-for-a-product /kamino-api.json get /luts/managed Returns active lookup table addresses associated with a given product identifier address. # Get managed LUTs for multiple products Source: https://docs.kamino.com/build/lookup-tables/get-managed-luts-for-multiple-products /kamino-api.json get /luts/managed/batch Returns active lookup table addresses for multiple product identifier addresses in a single request. # Register a new vault with its on-chain LUT Source: https://docs.kamino.com/build/lookup-tables/register-a-new-vault-with-its-on-chain-lut /kamino-api.json post /luts/managed/new-vault Verifies the vault and LUT exist on-chain, then registers the vault product and LUT entry. Private (authorized) API access only, please add a basic auth header to your request. # Get cumulative wallet Multiply earnings history Source: https://docs.kamino.com/build/multiply/get-cumulative-wallet-multiply-earnings-history /kamino-api.json get /owners/{pubkey}/multiply/pnl/history UTC cumulative daily or ISO-week points. The generation parameter is internal-only. Controlled by an off, internal, or on gate. # Get lifetime wallet Multiply earnings Source: https://docs.kamino.com/build/multiply/get-lifetime-wallet-multiply-earnings /kamino-api.json get /owners/{pubkey}/multiply/pnl Cumulative native earnings over Multiply and MultiplyFixedRate lifecycles. Controlled by an off, internal, or on gate. The generation parameter is internal-only. # Get filtered owner net value history Source: https://docs.kamino.com/build/other/get-filtered-owner-net-value-history /kamino-api.json get /owners/{pubkey}/net-values/history/filtered USD interval net revenue of selected products; distinct from Multiply SOL-basis earnings at /owners/{wallet}/multiply/pnl. # Get Kamino oracle prices Source: https://docs.kamino.com/build/other/get-kamino-oracle-prices /kamino-api.json get /oracles/prices Fetches all oracle prices for all public Klend Market assets # Get median Solana slot duration Source: https://docs.kamino.com/build/other/get-median-solana-slot-duration /kamino-api.json get /slots/duration Fetches the median duration of a recent Solana slot (in milliseconds) from the last three epochs # Get owner net value history Source: https://docs.kamino.com/build/other/get-owner-net-value-history /kamino-api.json get /owners/{pubkey}/net-values/history Fetches the historical USD values for an owner across all Kamino products — Lending, Strategies, Vaults, and Staking. # Get SOFR rate history Source: https://docs.kamino.com/build/other/get-sofr-rate-history /kamino-api.json get /benchmark-rates/sofr/history Returns daily SOFR rates published by the New York Fed from 2023 onwards, including the compounded SOFR index and 30/90/180-day compounded averages. The rate can be null for the latest date because the index is published one business day ahead of the rate. Supports filtering by date range (whole days, inclusive). # Get Solana epochs metadata Source: https://docs.kamino.com/build/other/get-solana-epochs-metadata /kamino-api.json get /epochs Fetches all epoch start and end times, first/last slot numbers, and epoch identifiers # Get USD benchmark lending rates Source: https://docs.kamino.com/build/other/get-usd-benchmark-lending-rates /kamino-api.json get /benchmark-rates/usd Returns USD benchmark lending rates aggregated across multiple protocols. Data is sourced from Allez and cached. Supports filtering by date range and downsampling by frequency. # Get pending farm rewards for a wallet Source: https://docs.kamino.com/build/portfolio/get-pending-farm-rewards-for-a-wallet /kamino-api.json get /portfolio/{pubkey}/rewards Returns pending farm reward source rows across Kamino products. USD reward totals are composed on the client from price data. # Get portfolio source data for a wallet Source: https://docs.kamino.com/build/portfolio/get-portfolio-source-data-for-a-wallet /kamino-api.json get /portfolio/{pubkey} Returns source position rows across Kamino products (lending, multiply, leverage, liquidity, earn, private credit, staking). Portfolio totals, counts, fees, historical PnL, and display-only rollups are intentionally left to client composition or their dedicated endpoints. After a transaction, pass minSlot to read a portfolio that includes it. # Get token USD price history Source: https://docs.kamino.com/build/prices/get-token-usd-price-history /kamino-api.json get /v2/prices/{mint}/history Returns one unrounded spot price in USD per bucket, preferring the most recently observed spot token ID throughout the request and filling its missing buckets from other spot IDs. Timestamps are bucket starts; gaps are possible. Start is inclusive and defaults to full history; end is exclusive and defaults to now. # Get private credit metrics Source: https://docs.kamino.com/build/private-credit/get-private-credit-metrics /kamino-api.json get /kvaults/private-credit/metrics Returns current aggregate metrics and active loans for private credit vaults # Get private credit metrics history Source: https://docs.kamino.com/build/private-credit/get-private-credit-metrics-history /kamino-api.json get /kvaults/private-credit/metrics/history Returns timeseries of private credit metrics. Frequency is automatically selected based on date range. # Borrow with the API Source: https://docs.kamino.com/build/recipes/borrow/borrow-via-api The API generates the unsigned transaction, and the client signs it securely Borrow assets from a Kamino reserve using the API. The API builds the transaction, and you sign it locally keeping your keys secure. ## Borrow via the API **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={"theme":"css-variables"} 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 2** ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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 SOL_RESERVE = 'd4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q'; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); ``` **Step 3** ### Call the Kamino API Make a POST request to the Kamino API to build the borrow transaction. ```typescript theme={"theme":"css-variables"} const res = await fetch(`${API_BASE_URL}/ktx/klend/borrow`, { 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; ``` > [!NOTE] > > The API returns a pre-built transaction encoded in base64 format ready for signing. **Step 4** ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` **Step 5** ### Resolve Address Lookup Tables and Sign Fetch the latest blockhash, decompile the transaction to resolve Address Lookup Tables, and sign. ```typescript theme={"theme":"css-variables"} 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); ``` > [!NOTE] > > `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. **Step 6** ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={"theme":"css-variables"} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions, }); await sendAndConfirm(signedTransaction, { commitment: 'confirmed', skipPreflight: false, }); console.log('Borrow successful! Signature:', signature); ``` > [!TIP] > > Your borrow is complete! The API built the transaction, you signed it locally (keeping your keys secure), and it was successfully submitted to the network. # Deposit with the API Source: https://docs.kamino.com/build/recipes/borrow/deposit-via-api The API generates the unsigned transaction, and the client signs it securely Deposit collateral into a Kamino reserve using the API. The API builds the transaction, and you sign it locally keeping your keys secure. ## Deposit via the API **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={"theme":"css-variables"} 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 2** ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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 3** ### Call the Kamino API Make a POST request to the Kamino API to build the deposit transaction. ```typescript theme={"theme":"css-variables"} const res = await fetch(`${API_BASE_URL}/ktx/klend/deposit`, { 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; ``` > [!NOTE] > > The API returns a pre-built transaction encoded in base64 format ready for signing. **Step 4** ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` **Step 5** ### Resolve Address Lookup Tables and Sign Fetch the latest blockhash, decompile the transaction to resolve Address Lookup Tables, and sign. ```typescript theme={"theme":"css-variables"} 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); ``` > [!NOTE] > > `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. **Step 6** ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={"theme":"css-variables"} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions, }); await sendAndConfirm(signedTransaction, { commitment: 'confirmed', skipPreflight: false, }); console.log('Success! Signature:', signature); ``` > [!TIP] > > 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. # Get Market Reserve APYs Source: https://docs.kamino.com/build/recipes/borrow/get-market-reserve-apys Fetch Kamino market reserve borrow and supply APY data using the API or SDK ## Borrow & Supply APY Calculation A reserve is a single asset lending pool within a market. All deposits of an asset enter the same reserve, and all borrowing draws from that pool. Variable rates are driven by utilization, the fraction of deposits currently borrowed: ``` Utilization = Borrowed / Total Deposited ``` As utilization increases, borrow rates rise. As utilization decreases, borrow rates fall. Supply APY is derived from borrower interest and depends on both the borrow rate and utilization: ``` Supply APY ≈ Borrow Rate × Utilization × (1 − Protocol Spread) ``` Not all deposited capital is borrowed at any given time, so supply APY is always lower than the borrow rate. Higher utilization means more of the pool is earning interest, which increases lender yield. Reserves are isolated pools. The same asset in different markets has different borrowers, collateral, and risk profiles, and therefore different rates. > [tab] API > > **Step 1** > > ### Fetch All Markets > > Retrieve the list of all lending markets on Kamino. > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const response = await fetch(`${API_BASE_URL}/v2/kamino-market`); > const markets = await response.json(); > ``` > > > [!NOTE] > > > > The `/v2/kamino-market` endpoint returns all lending markets including SOL/BTC Market, JLP Market, Altcoins Market, and Prime Market. > > **Step 2** > > ### Get Reserve APYs for Each Market > > For each market, fetch the APY metrics for all reserves (USDC, SOL, wETH, etc.). > > ```typescript theme={"theme":"css-variables"} > const allMarketReserves = await Promise.all( > markets.map(async (market) => { > const response = await fetch( > `${API_BASE_URL}/kamino-market/${market.lendingMarket}/reserves/metrics` > ); > const reserves = await response.json(); > return { market, reserves }; > }) > ); > > allMarketReserves.forEach(({ market, reserves }) => { > console.log(`\n${market.name}:`); > > reserves.forEach((reserve) => { > console.log(`\n${reserve.liquidityToken}:`); > console.log(` Supply APY: ${(reserve.supplyApy * 100).toFixed(2)}%`); > console.log(` Borrow APY: ${(reserve.borrowApy * 100).toFixed(2)}%`); > console.log(` Total Deposits: $${Number(reserve.totalSupplyUsd).toFixed(2)}`); > console.log(` Total Borrowed: $${Number(reserve.totalBorrowUsd).toFixed(2)}`); > }); > }); > ``` > > > [!NOTE] > > > > The `/kamino-market/{pubkey}/reserves/metrics` endpoint returns comprehensive metrics for each reserve including APYs, total deposits, and borrows. > [tab] SDK > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication and Kamino SDK. > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > ``` > > **Step 2** > > ### Load a Market > > Load a lending market with the measured slot duration. > > ```typescript theme={"theme":"css-variables"} > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketAddress = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > > const market = await KaminoMarket.load(rpc, marketAddress, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > > [!NOTE] > > > > Fixed-rate APYs depend on the slot duration passed to `KaminoMarket.load`. A hard-coded value such as 400 ms shows them at about half their real rate, because mainnet slots are closer to 210 ms. > > **Step 3** > > ### Get the Ledger Instant > > APYs are calculated at a ledger instant: the current slot and block time. > > ```typescript theme={"theme":"css-variables"} > const ledgerInstant = await getCurrentLedgerInstant(rpc); > ``` > > **Step 4** > > ### Calculate APYs for Each Reserve > > Calculate the supply and borrow APY of every reserve in the market. > > ```typescript theme={"theme":"css-variables"} > const reserves = market!.getReserves().map((reserve) => ({ > symbol: reserve.getTokenSymbol(), > kind: reserve.getKind().toString(), > supplyAPY: `${(reserve.totalSupplyAPY(ledgerInstant) * 100).toFixed(2)}%`, > borrowAPY: `${(reserve.totalBorrowAPY(ledgerInstant) * 100).toFixed(2)}%`, > utilization: `${(reserve.calculateUtilizationRatio() * 100).toFixed(2)}%`, > depositTvlUsd: reserve.getDepositTvl().toFixed(2), > borrowTvlUsd: reserve.getBorrowTvl().toFixed(2), > })); > > console.table(reserves); > ``` > > > [!NOTE] > > > > A token can have several reserves: one variable-rate reserve plus fixed-rate ones, so each row shows its kind. > > > [!TIP] > > > > You've successfully calculated borrow and supply APYs across all reserves using the Kamino SDK. # Repay with the API Source: https://docs.kamino.com/build/recipes/borrow/repay-via-api The API generates the unsigned transaction, and the client signs it securely Repay borrowed assets into a Kamino reserve using the API. The API builds the transaction, and you sign it locally keeping your keys secure. ## Repay via the API **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, getTransactionDecoder, getCompiledTransactionMessageDecoder, decompileTransactionMessageFetchingLookupTables, pipe, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, addSignersToTransactionMessage, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { parseKeypairFile } from '@kamino-finance/klend-sdk'; ``` **Step 2** ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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 SOL_RESERVE = 'd4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q'; const signer = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc(RPC_ENDPOINT); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); ``` **Step 3** ### Call the Kamino API Make a POST request to the Kamino API to build the repay transaction. ```typescript theme={"theme":"css-variables"} 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; ``` > [!NOTE] > > The API returns a pre-built transaction encoded in base64 format ready for signing. **Step 4** ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` **Step 5** ### Resolve Address Lookup Tables and Sign Fetch the latest blockhash, decompile the transaction to resolve Address Lookup Tables, and sign. ```typescript theme={"theme":"css-variables"} 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); ``` > [!NOTE] > > `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. **Step 6** ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={"theme":"css-variables"} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions, }); await sendAndConfirm(signedTransaction, { commitment: 'confirmed', skipPreflight: false, }); console.log('Repay successful! Signature:', signature); ``` > [!TIP] > > 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. # Withdraw via the API Source: https://docs.kamino.com/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 **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={"theme":"css-variables"} 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 2** ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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 3** ### Call the Kamino API Make a POST request to the Kamino API to build the withdraw transaction. ```typescript theme={"theme":"css-variables"} 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; ``` > [!NOTE] > > The API returns a pre-built transaction encoded in base64 format ready for signing. **Step 4** ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` **Step 5** ### Resolve Address Lookup Tables and Sign Fetch the latest blockhash, decompile the transaction to resolve Address Lookup Tables, and sign. ```typescript theme={"theme":"css-variables"} 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); ``` > [!NOTE] > > `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. **Step 6** ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={"theme":"css-variables"} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions, }); await sendAndConfirm(signedTransaction, { commitment: 'confirmed', skipPreflight: false, }); console.log('Withdraw successful! Signature:', signature); ``` > [!TIP] > > 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. # Earn Deposit with the API Source: https://docs.kamino.com/build/recipes/earn/earn-via-api The API generates the unsigned transaction, and the client signs it securely ## Earn Deposit with API **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={"theme":"css-variables"} 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 2** ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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 3** ### Call Kamino API Make a POST request to the Kamino API to build the deposit transaction. ```typescript theme={"theme":"css-variables"} 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(); console.log('API error:', error.message); } const { transaction: encodedTransaction } = await response.json(); ``` > [!NOTE] > > The API returns a pre-built transaction encoded in base64 format. This transaction includes Address Lookup Tables (ALTs) for efficiency. **Step 4** ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` **Step 5** ### Resolve Address Lookup Tables Fetch and resolve the Address Lookup Tables from the blockchain. ```typescript theme={"theme":"css-variables"} 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) ); ``` > [!NOTE] > > `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. > [!NOTE] > > A fresh blockhash is fetched and set to ensure the transaction remains valid. **Step 6** ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={"theme":"css-variables"} 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); ``` > [!TIP] > > 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. # Earn Deposit with the SDK Source: https://docs.kamino.com/build/recipes/earn/earn-via-sdk Deposit to vaults using TypeScript SDK ## Deposit to Earn Vault Deposit assets to start earning yield. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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'); ``` > [!NOTE] > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. **Step 3** ### Load the Vault Initialize the vault and load its state, reserves, and farm state once. The deposit instructions need all three. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const farmState = await manager.loadVaultFarmState(vaultState); ``` **Step 4** ### Set Slippage Protection Estimate the shares the deposit will mint, minus a slippage tolerance. The deposit reverts if fewer shares would be minted. ```typescript theme={"theme":"css-variables"} const depositAmount = new Decimal(1.0); // 1 USDC const minSharesOut = manager.estimateSharesFromTokens( vaultState, depositAmount, await getCurrentLedgerInstant(rpc), vaultReservesMap, 10 // 0.1% slippage ); ``` > [!NOTE] > > The deposit amount is in tokens (`1.0` is 1 USDC), not lamports. **Step 5** ### Build Deposit Instructions Generate the deposit instructions, plus the instructions that stake the new shares in the vault's farm. ```typescript theme={"theme":"css-variables"} const bundle = await vault.depositIxs( signer, depositAmount, vaultReservesMap, farmState, null, // first-loss capital farm undefined, // payer undefined, // memo minSharesOut ); const instructions = [...bundle.depositIxs, ...bundle.stakeInFarmIfNeededIxs]; ``` > [!NOTE] > > If the vault has a rewards farm, `stakeInFarmIfNeededIxs` stakes the minted shares in it so the position earns farm rewards. Shares staked here are unstaked automatically when you withdraw. **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` > [!NOTE] > > Every vault has its own lookup table. Compressing with it cuts the deposit from about 1,021 to 528 bytes, well under Solana's 1,232-byte transaction limit. **Step 7** ### Build and Sign Transaction Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} 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); ``` **Step 8** ### Send and Confirm Transaction Send the deposit transaction and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deposit successful! Signature:', signature); ``` > [!TIP] > > 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. # Earn Deposit from Privy Wallet Source: https://docs.kamino.com/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 **Step 1** ### Import Dependencies Import the required packages for Privy client, Solana RPC communication, and Kamino SDK operations. ```typescript theme={"theme":"css-variables"} import { PrivyClient } from '@privy-io/node'; import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, createNoopSigner, getBase64EncodedWireTransaction, compileTransaction, assertIsTransactionWithinSizeLimit, getBase64Encoder, getTransactionDecoder, assertTransactionIsFullySigned, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Configure Privy and Initialize Client Set up your Privy credentials and initialize the Privy client and RPC connection. ```typescript theme={"theme":"css-variables"} 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 WS_ENDPOINT = 'wss://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); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); ``` > [!NOTE] > > Update the configuration values with your Privy app credentials and user details. This example uses the Steakhouse USDC Vault. **Step 3** ### Create Privy User and Wallet Create a Privy user account and generate an embedded Solana wallet. ```typescript theme={"theme":"css-variables"} 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. **Step 4** ### Load the Vault Initialize the vault and load its state, reserves, and farm state once. The deposit instructions need all three. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault(rpc, address(VAULT_ADDRESS), slotDuration); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const farmState = await manager.loadVaultFarmState(vaultState); ``` **Step 5** ### Build Deposit Instructions Generate the deposit instructions using a noop signer, with slippage protection on the minted shares. ```typescript theme={"theme":"css-variables"} const noopSigner = createNoopSigner(address(walletAddress)); const depositAmount = new Decimal(1.0); // 1 USDC const minSharesOut = manager.estimateSharesFromTokens( vaultState, depositAmount, await getCurrentLedgerInstant(rpc), vaultReservesMap, 10 // 0.1% slippage ); const bundle = await vault.depositIxs( noopSigner, depositAmount, vaultReservesMap, farmState, null, // first-loss capital farm undefined, // payer undefined, // memo minSharesOut ); const instructions = [...bundle.depositIxs, ...bundle.stakeInFarmIfNeededIxs]; ``` > [!NOTE] > > A noop signer is used to build instructions without requiring the actual private key. Privy will handle signing later. Use the same `noopSigner` as the fee payer in the next steps, since two signer objects for one address cause a "Multiple distinct signers" error. **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` **Step 7** ### Build Transaction Message Fetch the latest blockhash and construct the compressed transaction message. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const depositTransactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(noopSigner, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(instructions, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lutsByAddress) ); ``` **Step 8** ### Sign Transaction with Privy Compile the transaction, serialize it, and sign using Privy's wallet API. ```typescript theme={"theme":"css-variables"} const compiledTransaction = compileTransaction(depositTransactionMessage); assertIsTransactionWithinSizeLimit(compiledTransaction); const signResponse = await privy.wallets().solana().signTransaction(walletId, { transaction: getBase64EncodedWireTransaction(compiledTransaction), 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. **Step 9** ### Send and Confirm Transaction Decode the transaction Privy signed, then send it and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signedTransaction = { ...getTransactionDecoder().decode(getBase64Encoder().encode(signResponse.signed_transaction)), lifetimeConstraint: compiledTransaction.lifetimeConstraint, }; assertTransactionIsFullySigned(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!NOTE] > > Privy returns the signed transaction as a base64 string. Decoding it and adding the blockhash lifetime from the compiled transaction lets `sendAndConfirmTransactionFactory` send it and wait until it is confirmed or its blockhash expires. > [!TIP] > > Your deposit is complete! The user's funds are now deposited in the Kamino Earn vault using their Privy embedded wallet. # Earn Withdraw with the API Source: https://docs.kamino.com/build/recipes/earn/earn-withdraw-via-api The API generates the unsigned transaction, and the client signs it securely ## Earn Withdraw with API **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, transaction handling, and Kamino SDK utilities. ```typescript theme={"theme":"css-variables"} 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 2** ### Configure and Initialize Set up the configuration and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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 3** ### Call Kamino API Make a POST request to the Kamino API to build the withdrawal transaction. ```typescript theme={"theme":"css-variables"} 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(); console.log('API error:', error.message); } const { transaction: encodedTransaction } = await response.json(); ``` > [!NOTE] > > The API returns a pre-built transaction encoded in base64 format. This transaction includes Address Lookup Tables (ALTs) for efficiency. **Step 4** ### Decode Transaction Decode the base64-encoded transaction and extract the message bytes. ```typescript theme={"theme":"css-variables"} const txBuffer = Buffer.from(encodedTransaction, 'base64'); const txMessageBytes = getTransactionDecoder().decode(txBuffer).messageBytes; const compiledMessage = getCompiledTransactionMessageDecoder().decode(txMessageBytes); ``` **Step 5** ### Resolve Address Lookup Tables Fetch and resolve the Address Lookup Tables from the blockchain. ```typescript theme={"theme":"css-variables"} 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) ); ``` > [!NOTE] > > `decompileTransactionMessageFetchingLookupTables` fetches the lookup table data from the blockchain and resolves all address references. This is required for transactions that use ALTs. > [!NOTE] > > A fresh blockhash is fetched and set to ensure the transaction remains valid. **Step 6** ### Send and Confirm Transaction Submit the signed transaction to the Solana network. ```typescript theme={"theme":"css-variables"} 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); ``` > [!TIP] > > 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. # Earn Withdraw with the SDK Source: https://docs.kamino.com/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. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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'); ``` > [!NOTE] > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. **Step 3** ### Load the Vault Initialize the vault and load its state, reserves, and farm state once. The withdraw instructions need all three. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const farmState = await manager.loadVaultFarmState(vaultState); const ledgerInstant = await getCurrentLedgerInstant(rpc); ``` **Step 4** ### Convert Tokens to Shares Convert the token amount you want back into vault shares, capped at the shares you hold. ```typescript theme={"theme":"css-variables"} const withdrawAmount = new Decimal(1.0); // 1 USDC const userShares = await vault.getUserShares(signer.address); const tokensPerShare = await manager.getTokensPerShareSingleVault(vault, ledgerInstant, vaultReservesMap, ledgerInstant); const sharesToWithdraw = Decimal.min(withdrawAmount.div(tokensPerShare), userShares.totalShares); ``` > [!NOTE] > > `withdrawIxs` takes an amount of **vault shares**, not tokens. Shares grow in value as interest accrues, so one share is worth more than one token. To withdraw everything, pass `userShares.totalShares`. **Step 5** ### Build Withdraw Instructions Generate the unstake and withdraw instructions. ```typescript theme={"theme":"css-variables"} const bundle = await vault.withdrawIxs( signer, sharesToWithdraw, ledgerInstant, vaultReservesMap, farmState, null // first-loss capital farm ); const instructions = [...bundle.unstakeFromFarmIfNeededIxs, ...bundle.withdrawIxs, ...bundle.postWithdrawIxs]; ``` > [!NOTE] > > Deposits stake shares in the vault's farm, so `unstakeFromFarmIfNeededIxs` must come before `withdrawIxs`. Without it, withdrawing staked shares fails with `CannotWithdrawZeroShares`. **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` > [!NOTE] > > Some vaults need the lookup table for a withdraw to fit in one transaction. Without it, a withdraw from one vault we tested was 1,274 bytes, over Solana's 1,232-byte limit. **Step 7** ### Build and Sign Transaction Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} 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); ``` **Step 8** ### Send and Confirm Transaction Send the withdraw transaction and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Withdraw successful! Signature:', signature); ``` > [!TIP] > > Once the withdraw transaction is confirmed, your vault shares are burned and you receive the underlying tokens plus any accrued interest. # Get Vault APYs Source: https://docs.kamino.com/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. > [tab] API > > **Step 1** > > ### Fetch All Vaults > > Retrieve the list of all available vaults on Kamino. > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const response = await fetch(`${API_BASE_URL}/kvaults/vaults`); > const vaults = await response.json(); > ``` > > > [!NOTE] > > > > The `/kvaults/vaults` endpoint returns all vaults with basic information including vault addresses, token mints, and strategies. > > **Step 2** > > ### Get APY for Each Vault > > Fetch APY metrics for all vaults in parallel using the vault public keys. > > ```typescript theme={"theme":"css-variables"} > // 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)}%`); > }); > ``` > > > [!NOTE] > > > > 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). > > > [!TIP] > > > > You now have APY data for all vaults across multiple timeframes. > [tab] SDK > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication and Kamino SDK. > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc } from '@solana/kit'; > import { > KaminoManager, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > ``` > > **Step 2** > > ### Initialize SDK > > Set up the RPC connection and create a Kamino Manager instance. > > ```typescript theme={"theme":"css-variables"} > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoManager = new KaminoManager(rpc, slotDuration); > ``` > > **Step 3** > > ### Load All Vaults and Their Reserves > > Retrieve all vaults, then load the reserves of every vault in one batched call. > > ```typescript theme={"theme":"css-variables"} > const vaults = await kaminoManager.getAllVaults(); > const vaultStates = await Promise.all(vaults.map((vault) => vault.getState())); > const allReservesMap = await kaminoManager.loadVaultsReserves(vaultStates); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > ``` > > > [!NOTE] > > > > `loadVaultsReserves` fetches the reserves for all vaults at once. Loading reserves vault by vault means hundreds of RPC calls, which hits the rate limits of public RPC endpoints. > > **Step 4** > > ### Get APYs for Each Vault > > Calculate the actual and theoretical APY of each vault from the shared reserves map. > > ```typescript theme={"theme":"css-variables"} > const vaultAPYs = []; > for (const vault of vaults) { > const vaultState = await vault.getState(); > const hasReserves = vaultState.vaultAllocationStrategy.some((a) => allReservesMap.has(a.reserve)); > if (!hasReserves) continue; > > const actualAPY = await kaminoManager.getVaultActualAPY(vaultState, ledgerInstant, allReservesMap); > const theoreticalAPY = await kaminoManager.getVaultTheoreticalAPY(vaultState, ledgerInstant, allReservesMap); > > vaultAPYs.push({ > address: vault.address.toString(), > name: kaminoManager.getDecodedVaultName(vaultState), > actualAPY: `${actualAPY.netAPY.mul(100).toFixed(2)}%`, > theoreticalAPY: `${theoreticalAPY.netAPY.mul(100).toFixed(2)}%`, > }); > } > > console.table(vaultAPYs); > ``` > > > [!NOTE] > > > > Each APY result contains `grossAPY` and `netAPY` (after fees), calculated from on-chain state. The actual APY is based on the amounts currently invested in each reserve. The theoretical APY assumes all of the vault's funds are invested according to its allocation weights. Vaults with no allocations yet are skipped. > > > [!TIP] > > > > You've successfully fetched vault APYs using the Kamino SDK. ## Related Resources > [card] [Lending Vaults Concepts](/products/lending-vaults/concepts) > > Learn how vaults work under the hood > [card] [Vault Data](/build/earn/vault-data-positions) > > Query vault metrics and positions > [card] [Benchmark Rate](/products/lending-vaults/benchmark-rate) > > Compare vault yields to market baseline > [card] [Earn Deposit](/build/recipes/earn/earn-via-api) > > Deposit into vaults via API # Withdraw to Privy Wallet and Check Balance Source: https://docs.kamino.com/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 **Step 1** ### Import Dependencies Import the required packages for Privy client, Solana RPC communication, and Kamino SDK operations. ```typescript theme={"theme":"css-variables"} import { PrivyClient } from '@privy-io/node'; import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, createNoopSigner, getBase64EncodedWireTransaction, compileTransaction, assertIsTransactionWithinSizeLimit, getBase64Encoder, getTransactionDecoder, assertTransactionIsFullySigned, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; ``` **Step 2** ### Configure Privy and Initialize Client Set up your Privy credentials and initialize the Privy client and RPC connection. ```typescript theme={"theme":"css-variables"} 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 WS_ENDPOINT = 'wss://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); const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT); ``` **Step 3** ### Get Wallet and Load the Vault Retrieve the Privy wallet, then load the vault's state, reserves, and farm state once. The withdraw instructions need all three. ```typescript theme={"theme":"css-variables"} const wallet = await privy.wallets().get(WALLET_ID); const noopSigner = createNoopSigner(address(wallet.address)); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault(rpc, address(VAULT_ADDRESS), slotDuration); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const farmState = await manager.loadVaultFarmState(vaultState); ``` > [!NOTE] > > A noop signer is used to build instructions without requiring the actual private key. Privy will handle signing later. **Step 4** ### Check User Shares Query the wallet's vault shares to determine how much can be withdrawn. ```typescript theme={"theme":"css-variables"} const userShares = await vault.getUserShares(noopSigner.address); console.log( `Vault shares: ${userShares.unstakedShares.toString()} unstaked, ${userShares.stakedShares.toString()} staked` ); if (userShares.totalShares.isZero()) console.log('No shares to withdraw'); ``` > [!NOTE] > > The total shares represent the user's position in the vault. Both staked and unstaked shares are included in the withdrawal. **Step 5** ### Build Withdrawal Instructions Generate the unstake and withdraw instructions for all of the wallet's shares. ```typescript theme={"theme":"css-variables"} const bundle = await vault.withdrawIxs( noopSigner, userShares.totalShares, await getCurrentLedgerInstant(rpc), vaultReservesMap, farmState, null, // first-loss capital farm undefined, // payer undefined, // withdrawal penalties true // close the farm account once the position is empty ); const instructions = [...bundle.unstakeFromFarmIfNeededIxs, ...bundle.withdrawIxs, ...bundle.postWithdrawIxs]; ``` > [!NOTE] > > Staked shares are unstaked from the vault's farm in the same transaction, before they are withdrawn. Without `unstakeFromFarmIfNeededIxs`, withdrawing staked shares fails with `CannotWithdrawZeroShares`. The last argument closes the wallet's farm account after a full withdrawal and returns its rent. **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` **Step 7** ### Build Transaction Message Fetch the latest blockhash and construct the compressed withdrawal transaction message. ```typescript theme={"theme":"css-variables"} 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(instructions, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lutsByAddress) ); ``` **Step 8** ### Sign Transaction with Privy Compile the transaction, serialize it, and sign using Privy's wallet API. ```typescript theme={"theme":"css-variables"} const compiledWithdrawTx = compileTransaction(withdrawTxMessage); assertIsTransactionWithinSizeLimit(compiledWithdrawTx); const withdrawSignResponse = await privy.wallets().solana().signTransaction(WALLET_ID, { transaction: getBase64EncodedWireTransaction(compiledWithdrawTx), 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. **Step 9** ### Send and Confirm Transaction Decode the transaction Privy signed, then send it and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signedWithdrawTx = { ...getTransactionDecoder().decode(getBase64Encoder().encode(withdrawSignResponse.signed_transaction)), lifetimeConstraint: compiledWithdrawTx.lifetimeConstraint, }; assertTransactionIsFullySigned(signedWithdrawTx); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedWithdrawTx, { commitment: 'confirmed', skipPreflight: true, }); console.log('Withdrawal successful! Signature:', getSignatureFromTransaction(signedWithdrawTx)); ``` > [!NOTE] > > Privy returns the signed transaction as a base64 string. Decoding it and adding the blockhash lifetime from the compiled transaction lets `sendAndConfirmTransactionFactory` send it and wait until it is confirmed or its blockhash expires. **Step 10** ### Check USDC Balance Query the wallet's USDC balance using Privy's balance API. ```typescript theme={"theme":"css-variables"} 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}`); ``` > [!TIP] > > Your withdrawal is complete! The user's vault shares have been redeemed for USDC, and the balance is now available in their Privy wallet. # Building with LLMs Source: https://docs.kamino.com/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. ## Kamino AI Resources > [card] [skill.md](https://docs.kamino.com/skill.md) > > Structured capability reference with API endpoints, SDK methods, and integration workflows. Start here for agent tool use. > [card] [llms.txt](https://docs.kamino.com/llms.txt) > > Curated index of all documentation pages with one-line descriptions and direct URLs. > [card] [llms-pages.json](https://docs.kamino.com/llms-pages.json) > > Machine-readable JSON mapping of every page with title, section, URL, and keywords. ### 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={"theme":"css-variables"} { "/products/lending-vaults": { "title": "Lending Vaults", "url": "https://docs.kamino.com/products/lending-vaults", "section": "Docs", "description": "Single-token managed yield aggregation across Kamino's lending markets", "keywords": ["kamino", "lending vaults", "yield", "vault shares", "auto-compounding"] } } ``` # Kamino Program Addresses Source: https://docs.kamino.com/build/resources/program-addresses The official program addresses for Kamino's protocols across different environments ## Klend | Environment | Address | | - | - | | Mainnet | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | | Staging (Mainnet) | `SLendK7ySfcEzyaFqy93gDnD3RtrpXJcnRwb6zFHJSh` | | Devnet | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` | ## Kvault | Environment | Address | | - | - | | Mainnet | `KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd` | | Staging (Mainnet) | `stKvQfwRsQiKnLtMNVLHKS3exFJmZFsgfzBPWHECUYK` | | Devnet | `devkRngFnfp4gBc5a3LsadgbQKdPo8MSZ4prFiNSVmY` | ## Kfarms | Environment | Address | | - | - | | Mainnet | `FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr` | | Devnet | `FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr` | ## Limo | Environment | Address | | - | - | | Mainnet | `LiMoM9rMhrdYrfzUCxQppvxCSG1FcrUK9G8uLq4A1GF` | | Staging (Mainnet) | `sLim6uuAFC8kAWstWpu1r6oJD4T8VR6raukSpU2Zim7` | ## Scope | Environment | Address | | - | - | | Mainnet | `HFn8GnPADiny6XqUoWE8uRPPxb29ikn4yTuPa9MF2fWJ` | | Staging (Mainnet) | `scpStzYvKzE7DHwsGMP5XLhcMTuLr3feoiC9mJ3yHr5` | ## Kliquidity | Environment | Address | | - | - | | Mainnet | `6LtLpnUFNByNXLyCoK9wA2MykKAmQNZKBdY8s47dehDc` | # Get all KVault season rewards Source: https://docs.kamino.com/build/season-rewards/get-all-kvault-season-rewards /kamino-api.json get /kvaults/rewards Get all active season points rewards for each Kamino Earn Vault # Get final vesting pool allocation Source: https://docs.kamino.com/build/season-rewards/get-final-vesting-pool-allocation /kamino-api.json get /season-rewards/final-vesting-pool Total rewards forfeited to the final vesting pool by users who claimed before full vesting # Get summary of the KVault program earnings Source: https://docs.kamino.com/build/season-rewards/get-summary-of-the-kvault-program-earnings /kamino-api.json get /kvaults/summary Get an aggregated all-time summary of all Kamino Earn Vault rewards and interest earned, in SOL and USD # Get user season claim status Source: https://docs.kamino.com/build/season-rewards/get-user-season-claim-status /kamino-api.json get /season-rewards/users/{pubkey}/claim-status Fetches season reward claim and forfeiture data for a specific user # Get user season rewards Source: https://docs.kamino.com/build/season-rewards/get-user-season-rewards /kamino-api.json get /season-rewards/users/{pubkey} Fetches combined season reward data from both KLend and KVault for a specific user # Get user staking boosts Source: https://docs.kamino.com/build/season-rewards/get-user-staking-boosts /kamino-api.json get /users/{pubkey}/staking-boosts Fetches staking boost multipliers for a specific user # Get mean staking yields Source: https://docs.kamino.com/build/staking-yields/get-mean-staking-yields /kamino-api.json get /v2/staking-yields/mean Fetches staking yields and calculates mean (average) APY over the last 10 epochs # Get median staking yields Source: https://docs.kamino.com/build/staking-yields/get-median-staking-yields /kamino-api.json get /v2/staking-yields/median Fetches staking yields and calculates median APY over the last 10 epochs # Get staking yields Source: https://docs.kamino.com/build/staking-yields/get-staking-yields /kamino-api.json get /v2/staking-yields Fetches the latest staking yields for all LSTs # Calculate Claimable User Rewards Source: https://docs.kamino.com/build/tutorials/borrow/calculate-claimable-user-rewards Calculate pending rewards for a user across all farm positions and check claimability Follow this tutorial to retrieve all pending rewards for a user across Liquidity, Lend, Borrow Markets, and Multiply farm positions, and check if they're claimable based on cooldown periods. > [!NOTE] > > **Farm Position Types** > > User rewards can come from different types of farm positions: > > * **Liquidity Farms**: Rewards from providing liquidity to Kamino vaults > * **Lend Farms**: Rewards from depositing collateral or holding vault shares > * **Borrow Markets Farms**: Rewards from borrowing assets (debt farms) or holding collateral/debt combinations (extra farms) > * **Multiply Farms**: Rewards from leveraged positions > > This tutorial shows how to identify all farm positions for a user and calculate their claimable rewards across all position types. ## Calculate Claimable User Rewards Calculate pending rewards for a user across all farm positions and check if they are claimable based on cooldown periods. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address, type Address } from '@solana/kit'; import { Farms, fetchAllMaybeFarmState, type FarmState, type UserFarm, type PendingReward } from '@kamino-finance/farms-sdk'; import { VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import Decimal from 'decimal.js'; type FarmPositionType = 'Liquidity' | 'Lend' | 'Borrow Markets' | 'Multiply'; type RewardWithAmount = { reward: PendingReward; rewardInfo: FarmState['rewardInfos'][0]; lastClaimTs: string; amount: Decimal; }; const DEFAULT_PUBKEY = '11111111111111111111111111111111'; ``` **Step 2** ### Initialize RPC and User Address Set up the Solana RPC connection and define the user wallet and lending market addresses. ```typescript theme={"theme":"css-variables"} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const user = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); const lendingMarket = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); ``` **Step 3** ### Define Helper Functions Create helper functions to validate addresses and determine farm position types. First, define the address validation helper: ```typescript theme={"theme":"css-variables"} // Helper function: Check if address is not default pubkey const isNotDefaultPubkey = (addr: Address): boolean => { return addr.toString() !== DEFAULT_PUBKEY; }; ``` Next, create the farm type determination function that checks for Liquidity and Lend farms: ```typescript theme={"theme":"css-variables"} // Helper function: Determine farm position type based on farm and user state const determineFarmType = ( farmState: FarmState, userFarm: UserFarm, walletPubKey: Address, lendingMarketAddress: Address, obligationPDA: Address ): FarmPositionType => { // Check for Liquidity farm (has strategyId) if (isNotDefaultPubkey(farmState.strategyId)) { return 'Liquidity'; } // Check for Lend vault farm (has vaultId) const isVaultFarm = isNotDefaultPubkey(farmState.vaultId); if (isVaultFarm) { return 'Lend'; } ``` Finally, add the delegation logic to identify Borrow Markets and Multiply positions: ```typescript theme={"theme":"css-variables"} // Calculate delegation variables const delegateeIsOwner = userFarm.userState.delegatee.toString() === userFarm.userState.owner.toString(); const farmHasSecondDelegatedAuthority = isNotDefaultPubkey(farmState.secondDelegatedAuthority); const farmUserStateIsForObligation = userFarm.userState.delegatee.toString() === obligationPDA.toString(); // Check for Lend collateral farm (delegated but not for obligation) if (!delegateeIsOwner && farmHasSecondDelegatedAuthority && !farmUserStateIsForObligation) { return 'Lend'; } // Check for Borrow Markets (delegated to obligation) if ( lendingMarketAddress && (farmUserStateIsForObligation || walletPubKey.toString() === userFarm.userState.delegatee.toString()) ) { return 'Borrow Markets'; } // Default to Multiply return 'Multiply'; }; ``` > [!NOTE] > > The `determineFarmType` function uses various state checks to identify the farm position type. Liquidity farms have a `strategyId`, Lend farms have a `vaultId` or specific delegation patterns, and Borrow Markets farms are identified by obligation delegation. **Step 4** ### Fetch User Farms Get all farms the user is participating in and fetch their states in parallel. ```typescript theme={"theme":"css-variables"} const farms = new Farms(rpc); const currentTime = new Decimal(Math.floor(Date.now() / 1000)); // Get all farms user is participating in const userFarms = await farms.getAllFarmsForUser(user, currentTime); // Fetch farm states in batch const farmAddresses = Array.from(userFarms.keys()); const farmStates = await fetchAllMaybeFarmState(rpc, farmAddresses); // Build farm data objects const farmsData = farmAddresses.flatMap((farmAddress, index) => { const farmState = farmStates[index]; const userFarm = userFarms.get(farmAddress); return farmState.exists && userFarm ? [{ farmAddress, userFarm, farmState: farmState.data }] : []; }); ``` > [!NOTE] > > The `getAllFarmsForUser` method returns a map of all farms where the user has an active position. Using `fetchAllMaybeFarmState` fetches all farm states in a single batch request. **Step 5** ### Calculate Obligation PDA and Display Rewards Calculate the obligation PDA, then loop through all user farms to calculate pending rewards and check if they're claimable based on cooldown periods. First, calculate the obligation PDA: ```typescript theme={"theme":"css-variables"} // Calculate obligation PDA const obligationType = new VanillaObligation(PROGRAM_ID); const obligationPDA = await obligationType.toPda(lendingMarket, user); ``` Then iterate through farms and filter rewards with positive amounts: ```typescript theme={"theme":"css-variables"} for (const { farmAddress, userFarm, farmState } of farmsData) { // Determine farm type const farmType = determineFarmType(farmState, userFarm, user, lendingMarket, obligationPDA); // Filter and calculate token amounts const rewardsWithAmount = userFarm.pendingRewards .map((reward: PendingReward, index: number) => { const rewardInfo = farmState.rewardInfos[index]; const lastClaimTs = userFarm.userState.lastClaimTs[index]; if (reward.rewardTokenMint === DEFAULT_PUBKEY || !rewardInfo || !lastClaimTs) { return null; } const amount = new Decimal(reward.cumulatedPendingRewards.toString()).div( new Decimal(10).pow(Number(rewardInfo.token.decimals)) ); if (amount.gt(0)) { return { reward, rewardInfo, lastClaimTs: lastClaimTs.toString(), amount }; } return null; }) .filter((r): r is RewardWithAmount => r !== null); ``` Finally, check claimability based on cooldown periods and display the results: ```typescript theme={"theme":"css-variables"} // Only display farm if it has valid rewards if (rewardsWithAmount.length > 0) { console.log(`${farmType} Farm: ${farmAddress.toString()}`); console.log(` Owner: ${userFarm.userState.owner.toString()}`); console.log(` Delegatee: ${userFarm.userState.delegatee.toString()}`); for (const { reward, rewardInfo, lastClaimTs, amount } of rewardsWithAmount) { // Check if reward is claimable based on cooldown period const minClaimDuration = new Decimal(rewardInfo.minClaimDurationSeconds.toString()).toNumber(); const lastClaimTsNum = new Decimal(lastClaimTs).toNumber(); const currentTimeNum = currentTime.toNumber(); const timeSinceClaim = currentTimeNum - lastClaimTsNum; // Validate data (1 year = 31536000 seconds - anything larger is invalid) const isValidDuration = minClaimDuration < 31536000; const isValidTimestamp = timeSinceClaim >= 0 && timeSinceClaim < 31536000000; console.log(` Reward: ${reward.rewardTokenMint}`); console.log(` Amount: ${amount.toFixed(Number(rewardInfo.token.decimals))}`); if (!isValidDuration || !isValidTimestamp) { console.log(` Claimable: No\n`); } else { const claimable = timeSinceClaim >= minClaimDuration; if (claimable) { console.log(` Claimable: Yes\n`); } else { const timeRemaining = minClaimDuration - timeSinceClaim; console.log(` Claimable: ${Math.ceil(timeRemaining / 60)}m\n`); } } } } } ``` > [!TIP] > > The script outputs all pending rewards grouped by farm type and position. Each reward shows the token mint, amount, and claimability status. If a reward has a cooldown period, the remaining time is displayed in minutes. # Interest Rate Curve Source: https://docs.kamino.com/build/tutorials/borrow/calculate-interest-rate-curve Calculate how borrow and supply APY change based on pool utilization > [!NOTE] > > The interest rate curve shows how borrow and supply APY change as pool utilization increases from 0% to 100%, where utilization represents the share of supplied liquidity that is borrowed. ## Calculate Interest Rate Curve Generate curve points showing APY at different utilization levels. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, ONE_HUNDRED_PCT_IN_BPS, getBorrowRate, calculateAPYFromAPR, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; ``` **Step 2** ### Configure Market and Reserve ```typescript theme={"theme":"css-variables"} const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); // SOL/BTC Market const reserveAddress = address('ESCkPWKHmgNE7Msf77n9yzqJd5kQVWWGy3o5Mgxhvavp'); // USDG const CHART_POINTS = 21; ``` > [!NOTE] > > `CHART_POINTS` sets the chart resolution: 21 points is 0% to 100% utilization in 5% steps. The curve's own points are always included, so its kinks aren't skipped. **Step 3** ### Load Market and Reserve ```typescript theme={"theme":"css-variables"} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const reserve = market!.getReserveByAddress(reserveAddress); if (!reserve) { console.log('Reserve not found:', reserveAddress); } ``` **Step 4** ### Extract Borrow Curve Points The curve is a list of (utilization, borrow rate) points in basis points, joined by straight lines. Its rates are APRs. The on-chain list has a fixed length, so repeated points at 100% are padding and are dropped. ```typescript theme={"theme":"css-variables"} const curve: [number, number][] = reserve!.state.config.borrowRateCurve.points .filter((point, index, points) => index === 0 || point.utilizationRateBps !== points[index - 1].utilizationRateBps) .map((point) => [point.utilizationRateBps / ONE_HUNDRED_PCT_IN_BPS, point.borrowRateBps / ONE_HUNDRED_PCT_IN_BPS]); console.log('Curve points (utilization, borrow APR):', curve); ``` > [!NOTE] > > The [reserve metrics history](/build/api-reference/borrow/market-data/market-reserve-metrics-history) endpoint returns the same configured curve as `borrowCurve`, without an RPC. **Step 5** ### Read the Rate Parameters ```typescript theme={"theme":"css-variables"} const rateFactor = reserve!.rateAdjustmentFactor(); const hostRate = reserve!.getFixedHostInterestRate().toNumber() * rateFactor; const supplyShare = 1 - reserve!.state.config.protocolTakeRatePct / 100; ``` > [!NOTE] > > Borrowers pay the curve rate plus the reserve's fixed host interest. Suppliers earn the curve rate on the borrowed share of the reserve, minus the protocol take rate. **Step 6** ### Generate Curve Points Calculate the borrow and supply APY at each utilization. ```typescript theme={"theme":"css-variables"} const utilizations = [ ...new Set([...Array.from({ length: CHART_POINTS }, (_, i) => i / (CHART_POINTS - 1)), ...curve.map(([u]) => u)]), ].sort((a, b) => a - b); const curvePoints = utilizations.map((utilization) => { const borrowRate = getBorrowRate(utilization, curve) * rateFactor; return { utilization: `${(utilization * 100).toFixed(0)}%`, borrowAPY: `${(calculateAPYFromAPR(borrowRate + hostRate) * 100).toFixed(2)}%`, supplyAPY: `${(calculateAPYFromAPR(utilization * borrowRate * supplyShare) * 100).toFixed(2)}%`, }; }); console.table(curvePoints); ``` > [!NOTE] > > `getBorrowRate` reads the borrow rate at any utilization from the curve. `calculateAPYFromAPR` compounds an APR into an APY. **Step 7** ### Compare with Current Rates ```typescript theme={"theme":"css-variables"} const ledgerInstant = await getCurrentLedgerInstant(rpc); console.log({ symbol: reserve!.getTokenSymbol(), utilization: `${(reserve!.calculateUtilizationRatio() * 100).toFixed(2)}%`, borrowAPY: `${(reserve!.totalBorrowAPY(ledgerInstant) * 100).toFixed(2)}%`, supplyAPY: `${(reserve!.totalSupplyAPY(ledgerInstant) * 100).toFixed(2)}%`, }); ``` > [!TIP] > > The table shows the borrow and supply APY across the curve, and the current rates show where the reserve sits on it. Plot the table with any charting library. ## Understanding the Results The curve shows how rates change with utilization: * **Below the kink**: rates rise slowly. For USDG the kink is at 95% utilization. * **Above the kink**: rates rise sharply to pull in deposits and push borrowers to repay. * **Supply APY**: always below borrow APY, because suppliers earn only on the borrowed share of the reserve, minus the protocol take rate. ### Example Output USDG on the SOL/BTC Market, October 2026 (rows trimmed): ```text theme={"theme":"css-variables"} Curve points (utilization, borrow APR): [ [ 0, 0 ], [ 0.95, 0.0551 ], [ 1, 0.3634 ] ] utilization borrowAPY supplyAPY 0% 0.50% 0.00% 25% 1.97% 0.33% 50% 3.46% 1.31% 75% 4.97% 2.98% 90% 5.89% 4.32% 95% 6.19% 4.82% 100% 44.54% 38.69% { symbol: 'USDG', utilization: '90.61%', borrowAPY: '5.92%', supplyAPY: '4.38%' } ``` # Calculate Reserve Reward APY Source: https://docs.kamino.com/build/tutorials/borrow/calculate-reserve-reward-apy Calculate collateral and debt farm reward APY for market reserves Follow this tutorial to calculate reward APY for both deposit and borrow positions on Kamino lending reserves. > [!NOTE] > > **Reserve Farms vs Extra Farms** > > Reserve farms are attached directly to a reserve and reward all users who deposit or borrow that reserve asset. Depositors earn rewards through collateral farms, while borrowers earn rewards through debt farms. > > Extra farms reward users only when specific collateral and debt combinations are used. Rewards are conditional on holding qualifying positions rather than simply depositing or borrowing a single reserve. > > This tutorial focuses on reserve farms. ## Calculate Reserve Reward APY Calculate APY for both collateral and debt farm rewards on a specific reserve. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address, type Address } from '@solana/kit'; import { KaminoMarket, PROGRAM_ID, lamportsToNumberDecimal } from '@kamino-finance/klend-sdk'; import { fetchAllMaybeFarmState, calculateCurrentRewardPerToken } from '@kamino-finance/farms-sdk'; import Decimal from 'decimal.js'; type PriceData = { mint: string; price: string }; const DEFAULT_PUBKEY = '11111111111111111111111111111111'; ``` **Step 2** ### Initialize RPC and Fetch Prices Set up the Solana RPC connection and fetch token prices from the Kamino API. ```typescript theme={"theme":"css-variables"} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const mainMarket = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const usdsMint = address('USDSwr9ApdHk5bvJKMjzff41FfuX8bSxdKcR81vTwcA'); // Fetch token prices from Kamino API const pricesRes = await fetch('https://api.kamino.finance/oracles/prices?markets=main'); const pricesData = (await pricesRes.json()) as PriceData[]; const priceMap = new Map(); for (const p of pricesData) { priceMap.set(p.mint, parseFloat(p.price)); } ``` > [!NOTE] > > Creating a price map allows quick lookups for multiple reward tokens. The example uses USDS reserve which has both collateral and debt farm rewards active. **Step 3** ### Load Market and Reserve Load the Kamino market and get the reserve by its mint address. ```typescript theme={"theme":"css-variables"} // Load market and reserve const market = await KaminoMarket.load(rpc, mainMarket, 400, PROGRAM_ID); const [reserve] = market!.getReservesByMint(usdsMint); if (!reserve) { console.log('Reserve not found'); } else { ``` > [!NOTE] > > The `getReservesByMint` method returns the reserves for a mint (here, the first one), and retrieves the reserve configuration including references to both the collateral farm and debt farm addresses. **Step 4** ### Collect and Fetch Farm Addresses Collect both collateral and debt farm addresses, checking they're not the default pubkey, then fetch all farms in parallel. ```typescript theme={"theme":"css-variables"} // Collect debt and collateral farm addresses const farmsToFetch: { name: string; address: Address }[] = []; if (reserve.state.farmCollateral.toString() !== DEFAULT_PUBKEY) { farmsToFetch.push({ name: 'Collateral Farm Rewards', address: reserve.state.farmCollateral }); } if (reserve.state.farmDebt.toString() !== DEFAULT_PUBKEY) { farmsToFetch.push({ name: 'Debt Farm Rewards', address: reserve.state.farmDebt }); } // Fetch all farms in batch const farmAddresses = farmsToFetch.map((f) => f.address); const farmStates = await fetchAllMaybeFarmState(rpc, farmAddresses); const farms = farmsToFetch.flatMap((farmInfo, index) => { const state = farmStates[index]; return state.exists ? [{ name: farmInfo.name, state: state.data }] : []; }); ``` > [!NOTE] > > Checking for the default pubkey ensures we only fetch farms that are actually configured on the reserve. Using `fetchAllMaybeFarmState` fetches all farm states in a single batch request, which is more efficient than individual fetches. **Step 5** ### Calculate Farm Reward APY Calculate APY for each active reward on both collateral and debt farms. ```typescript theme={"theme":"css-variables"} for (const farm of farms) { const totalStaked = lamportsToNumberDecimal( farm.state.totalStakedAmount.toString(), Number(farm.state.token.decimals) || 6 ); console.log(farm.name + ':'); for (const rewardInfo of farm.state.rewardInfos) { if (rewardInfo.rewardsAvailable > 0n && !totalStaked.isZero()) { const rewardMint = rewardInfo.token.mint.toString(); const rewardPrice = priceMap.get(rewardMint) || 1; const currentTime = new Decimal(Date.now() / 1000); // Calculate APY from farm rewards const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(rewardInfo, currentTime); // returns the raw value const divisor = new Decimal(10) .pow(rewardInfo.rewardsPerSecondDecimals.toString()) .mul(new Decimal(10).pow(rewardInfo.token.decimals.toString())); const adjustedRewardPerToken = new Decimal(rewardPerTokenPerSecond).div(divisor); const dailyRewards = adjustedRewardPerToken.mul(86400).mul(rewardPrice); const apy = Decimal.pow(dailyRewards.div(totalStaked).plus(1), 365).minus(1); console.log(` Reward Token: ${rewardMint}`); console.log(` APY: ${(apy.toNumber() * 100).toFixed(2)}%\n`); } } } } ``` > [!TIP] > > The script outputs APY for all active rewards on both the collateral and debt farms. The `calculateCurrentRewardPerToken` helper from farms-sdk handles the reward schedule logic. Each reward is priced in USD and the total staked amount represents the value of all positions earning that reward. # Claim User Rewards Source: https://docs.kamino.com/build/tutorials/borrow/claim-user-rewards Claim all pending rewards from lending farm positions Follow this tutorial to claim all accumulated rewards from your collateral or debt farm positions on Kamino lending reserves. > [!NOTE] > > **Delegated vs Non-Delegated Farms** > > Different farm types use different delegation patterns. For the correct delegatees for your specific farm, check the user farm state returned by `getAllFarmsForUser` in the "Calculate Claimable User Rewards" tutorial. ## Claim User Rewards Claim all pending rewards from a user's farm position. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, parseKeypairFile, VanillaObligation, PROGRAM_ID } from '@kamino-finance/klend-sdk'; import { Farms } from '@kamino-finance/farms-sdk'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} // Configuration - UPDATE THESE VALUES const KEYPAIR_FILE = '/path/to/your/keypair.json'; // Load keypair from file const signer = await parseKeypairFile(KEYPAIR_FILE); // Initialize RPC and RPC Subscriptions const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); ``` **Step 3** ### Load Market and Get Obligation Load the Kamino market and get the user's obligation address. ```typescript theme={"theme":"css-variables"} const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); const market = await KaminoMarket.load(rpc, marketPubkey, 400); // Get obligation address for delegatees array const kaminoObligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!kaminoObligation) { console.log('No obligation found'); } console.log('Obligation:', kaminoObligation?.obligationAddress.toString()); ``` **Step 4** ### Build Claim Instructions Use the Farms SDK to build claim instructions for all rewards on the farm. ```typescript theme={"theme":"css-variables"} // Build claim instructions using farms-sdk const farm = new Farms(rpc); const claimIxs = await farm.claimForUserForFarmAllRewardsIx( signer, // payer signer.address, // user (wallet address = owner) address('Gsoc83qRQ5X1LfGGbPqU2FdxZnveqbkP2vMXq6BcmtMk'), // farm true, // isDelegated = true for lending farms [signer.address, kaminoObligation!.obligationAddress] // delegatees array ); ``` > [!WARNING] > > The `delegatees` array values depend on your specific farm position. To find the correct delegatee addresses for your farm, use the "Calculate Claimable User Rewards" tutorial - it shows the actual delegatee in the user farm state. **Step 5** ### Build and Sign Transaction Use Kit's functional pipe pattern to build and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const claimTx = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(claimIxs, tx) ); const claimSigned = await signTransactionMessageWithSigners(claimTx); const claimSignature = getSignatureFromTransaction(claimSigned); ``` **Step 6** ### Send and Confirm Transaction Send the transaction to the network and wait for confirmation. ```typescript theme={"theme":"css-variables"} await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(claimSigned, { commitment: 'confirmed', skipPreflight: true, }); console.log(`Claim farm rewards successful! Signature: ${claimSignature}`); ``` > [!TIP] > > The rewards have been claimed and transferred to your wallet. You can verify the transaction using the signature on a Solana explorer. # Deposit and Borrow Source: https://docs.kamino.com/build/tutorials/borrow/deposit-and-borrow Deposit collateral and borrow assets against it ## Deposit Collateral Deposit assets as collateral to enable borrowing. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Build Deposit Instructions Deposit USDC as collateral into the wallet's borrow position. ```typescript theme={"theme":"css-variables"} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); const depositAction = await KaminoAction.buildDepositTxns({ kaminoMarket: market!, amount: new BN(3_000_000), reserveAddress: usdcReserve.address, owner: signer, obligation: new VanillaObligation(PROGRAM_ID), useV2Ixs: true, scopeRefreshConfig: undefined, initUserMetadata: { skipInitialization: false, skipLutCreation: true }, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!NOTE] > > A market can hold several reserves for the same token: one variable-rate reserve plus [fixed-rate](/build/borrow/tutorials/fixed-rate-borrowing) reserves. Actions take a reserve address, and `getExistingFloatRateReserveByMint()` returns the variable-rate one. `skipLutCreation: true` keeps a first deposit, including user account setup, in one transaction; without it the deposit fails with `0x17a3`. **Step 4** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(depositAction), tx) ); ``` **Step 5** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The collateral is deposited and the borrow position is ready. ## Borrow Assets Borrow assets against your deposited collateral. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Load the Obligation Load the wallet's borrow position so the SDK refreshes every reserve it uses. ```typescript theme={"theme":"css-variables"} const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!obligation) { console.log('No borrow position found for', signer.address); } ``` **Step 4** ### Build Borrow Instructions Borrow USDT from its variable-rate reserve against the collateral. ```typescript theme={"theme":"css-variables"} const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); const usdtReserve = market!.getExistingFloatRateReserveByMint(usdtMint); const borrowAction = await KaminoAction.buildBorrowTxns({ kaminoMarket: market!, amount: new BN(1_000_000), reserveAddress: usdtReserve.address, owner: signer, obligation: obligation!, useV2Ixs: true, scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!NOTE] > > The borrow must keep the position under its borrow limit, or the program rejects it. **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(borrowAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Borrow successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The USDT is in the wallet and the debt is recorded in the borrow position. # Deposit with Referral Source: https://docs.kamino.com/build/tutorials/borrow/deposit-with-referral Deposit funds with a referrer who earns commission from a user's borrowing activity Follow this tutorial to make a deposit with a referrer who will earn commission from your future borrowing activity. ## Deposit with Referral A UserMetadata account stores the referrer information. The referrer must be included when the account is created. After it is set, the referrer cannot be changed. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > some, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > VanillaObligation, > PROGRAM_ID, > DEFAULT_PUBLIC_KEY, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import BN from 'bn.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Check the Referrer on Record > > The referrer is stored in the wallet's user metadata, created by its first Kamino deposit. If the account already exists, pass the referrer on record. > > ```typescript theme={"theme":"css-variables"} > const REFERRER = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const [, userMetadata] = await market!.getUserMetadata(signer.address); > const referrer = userMetadata ? userMetadata.referrer : REFERRER; > > if (userMetadata) { > console.log('Referrer already fixed for this wallet:', referrer === DEFAULT_PUBLIC_KEY ? 'none' : referrer); > } > ``` > > > [!WARNING] > > > > The referrer can only be set when the user metadata account is created and can't be changed after. A wallet that already used Kamino without a referral has `DEFAULT_PUBLIC_KEY` (`11111111111111111111111111111111`) on record, meaning no referrer, and can't get one. Passing a different referrer than the one on record makes the transaction fail. > > **Step 4** > > ### Build Deposit Instructions with Referrer > > Deposit USDC as collateral with the referrer attached. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const depositAction = await KaminoAction.buildDepositTxns({ > kaminoMarket: market!, > amount: new BN(1_000_000), > reserveAddress: usdcReserve.address, > owner: signer, > obligation: new VanillaObligation(PROGRAM_ID), > useV2Ixs: true, > scopeRefreshConfig: undefined, > initUserMetadata: { skipInitialization: false, skipLutCreation: true }, > referrer: some(referrer), > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(depositAction), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > The deposit with referral is complete. The referrer is linked to the account and earns a share of the interest it pays on borrows. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Initialize User with Referrer > > Create the user metadata account linked to a referrer before depositing. > > ```rust theme={"theme":"css-variables"} > use klend_interface::helpers; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let referrer = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY").unwrap(); > > // Derive the referrer's user_metadata PDA > let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer); > > // Your user's address lookup table (created during onboarding) > let user_lookup_table = Pubkey::from_str("YOUR_USER_LOOKUP_TABLE_PUBKEY").unwrap(); > > let init_ixs = helpers::lifecycle::init_user( > owner, > owner, // fee payer > user_lookup_table, > Some(referrer_user_metadata), // links to this referrer > ); > ``` > > > [!WARNING] > > > > Once a UserMetadata account has a referrer, it cannot be changed. The original referrer permanently earns commission from the user's borrowing activity. > > **Step 4** > > ### Build Obligation Context > > Derive the obligation PDA and build the context for depositing. > > ```rust theme={"theme":"css-variables"} > use klend_interface::ObligationContext; > > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > // Derive the obligation PDA > let (obligation_pubkey, _) = pda::obligation( > &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, > &Pubkey::default(), &Pubkey::default(), > ); > > // Fetch the obligation account > let obligation_data = rpc_client.get_account(&obligation_pubkey)?; > > // Discover which reserves the obligation references > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; > > // Fetch all reserve accounts in one RPC call > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > > // Build the context > let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() > .zip(reserve_accounts.iter()) > .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) > .collect(); > let ctx = ObligationContext::from_account_data( > obligation_pubkey, &obligation_data.data, &reserves > )?; > ``` > > > [!NOTE] > > > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. > > **Step 5** > > ### Build Deposit Instructions > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); > let user_source_liquidity = get_associated_token_address(&owner, &liquidity_mint); > > let deposit_ixs = ctx.deposit( > owner, > &reserve_pubkey, > user_source_liquidity, > 1_000_000, // 1 USDC > )?; > ``` > > **Step 6** > > ### Send Transactions > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > // Transaction 1: Initialize user metadata with referrer > let message = Message::new(&init_ixs, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > rpc_client.send_and_confirm_transaction(&tx)?; > > // Transaction 2: Deposit with referral > let message = Message::new(&deposit_ixs, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Deposit with referral successful! Signature: {signature}"); > ``` # Calculate Extra Farm Reward APY Source: https://docs.kamino.com/build/tutorials/borrow/extra-farm-reward-apy Calculate APY for extra farm stablecoin rewards This tutorial shows you how to calculate APY for extra farm rewards that are earned when using specific collateral and debt combinations. > [!NOTE] > > Extra farms provide additional rewards to users who deposit specific collateral and borrow specific assets. ## Calculate Extra Farm Reward APY Calculate APY for extra farm rewards paid in stablecoins like CASH that are pegged to USD. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and decimal calculations. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { fetchAllMaybeFarmState, calculateCurrentRewardPerToken } from '@kamino-finance/farms-sdk'; import { KaminoMarket, PROGRAM_ID, lamportsToNumberDecimal } from '@kamino-finance/klend-sdk'; import Decimal from 'decimal.js'; type ExtraFarm = { market: string; farm: string; collMint: string; debtMint: string }; type Resources = { 'mainnet-beta': { extraFarms: ExtraFarm[] } }; ``` **Step 2** ### Initialize RPC and Load Market Set up the Solana RPC connection and load the Kamino market. ```typescript theme={"theme":"css-variables"} const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const mainMarketAddress = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); // Load market and get CASH and SOL mints from reserves const market = await KaminoMarket.load(rpc, mainMarketAddress, 400, PROGRAM_ID); let cashReserve, solReserve; for (const reserve of market!.reserves.values()) { if (reserve.stats.symbol === 'CASH') cashReserve = reserve; if (reserve.stats.symbol === 'SOL') solReserve = reserve; } if (!cashReserve || !solReserve) { console.log('CASH or SOL reserve not found'); } const cashMint = cashReserve!.getLiquidityMint().toString(); const solMint = solReserve!.getLiquidityMint().toString(); ``` > [!NOTE] > > This example targets the SOL/CASH extra farm pair where users deposit SOL collateral and borrow CASH to earn rewards. **Step 3** ### Get and Filter Extra Farms Fetch the list of extra farms from the CDN and filter by SOL collateral and CASH debt. ```typescript theme={"theme":"css-variables"} // Get extraFarms from CDN API and filter by SOL/CASH pair const cdnRes = await fetch('https://cdn.kamino.finance/resources.json'); const allResources = (await cdnRes.json()) as Resources; const kaminoResources = allResources['mainnet-beta']; const extraFarmsForMarket = kaminoResources.extraFarms.filter((f) => f.market === mainMarketAddress.toString()); // Filter by collateral (SOL) and debt (CASH) mints const solCashFarms = extraFarmsForMarket.filter((f) => f.collMint === solMint && f.debtMint === cashMint); ``` > [!NOTE] > > The CDN resources endpoint provides a list of all extra farms. We filter for farms that specifically reward SOL collateral deposits paired with CASH borrows. **Step 4** ### Fetch All Farm States in Batch Fetch all farm states in a single batch request for better performance. ```typescript theme={"theme":"css-variables"} // Fetch all farm states in batch const farmAddresses = solCashFarms.map((f) => address(f.farm)); const farmStates = await fetchAllMaybeFarmState(rpc, farmAddresses); const farms = solCashFarms.flatMap((extraFarm, index) => { const farmState = farmStates[index]; return farmState.exists ? [{ farm: extraFarm.farm, farmState: farmState.data }] : []; }); ``` > [!NOTE] > > Using `fetchAllMaybeFarmState` fetches all farm states in a single batch request. **Step 5** ### Calculate APY for SOL/CASH Farms Loop through the fetched farms and calculate APY for CASH rewards. ```typescript theme={"theme":"css-variables"} for (const { farm, farmState } of farms) { const totalStaked = lamportsToNumberDecimal( farmState.totalStakedAmount.toString(), Number(farmState.token.decimals) || 6 ); const cashReward = farmState.rewardInfos.find( (r) => r.token.mint.toString() === cashMint && r.rewardsAvailable > 0n ); if (cashReward && !totalStaked.isZero()) { const currentTime = new Decimal(Date.now() / 1000); // Calculate APY from farm rewards const rewardPerTokenPerSecond = calculateCurrentRewardPerToken(cashReward, currentTime); // returns the raw value const divisor = new Decimal(10) .pow(cashReward.rewardsPerSecondDecimals.toString()) .mul(new Decimal(10).pow(cashReward.token.decimals.toString())); const adjustedRewardPerToken = new Decimal(rewardPerTokenPerSecond).div(divisor); const dailyRewards = adjustedRewardPerToken.mul(86400); const apy = Decimal.pow(dailyRewards.div(totalStaked).plus(1), 365).minus(1); console.log(`ExtraFarm: ${farm}`); console.log(` CASH APY: ${(apy.toNumber() * 100).toFixed(2)}%\n`); } } ``` > [!TIP] > > The script outputs the APY for SOL/CASH extra farms paying CASH rewards. The `calculateCurrentRewardPerToken` helper from farms-sdk handles the reward schedule logic. Since CASH is pegged to USD, no price lookup is required. # Flash Loans Source: https://docs.kamino.com/build/tutorials/borrow/flash-loans Execute a flash loan to borrow assets and repay within a single atomic transaction ## Flash Loans > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > none, > assertIsTransactionWithinSizeLimit, > } from '@solana/kit'; > import { > KaminoMarket, > PROGRAM_ID, > getFlashLoanInstructions, > getAssociatedTokenAddress, > getMedianSlotDurationInMsFromLastEpochs, > } 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 2** > > ### Setup Market and Signer > > Load your keypair, initialize RPC connections, and load the Kamino market. > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Configure Flash Loan Parameters > > Set the token, the flash loan amount in lamports (1 USDC), and the wallet's token account that receives it. > > ```typescript theme={"theme":"css-variables"} > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > > const flashLoanAmount = new Decimal(1_000_000); > const usdcAta = await getAssociatedTokenAddress(usdcMint, signer.address, usdcReserve.getLiquidityTokenProgram()); > ``` > > **Step 4** > > ### Build Flash Loan Instructions > > Generate the flash borrow and flash repay instructions using the Kamino SDK. > > ```typescript theme={"theme":"css-variables"} > 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, > }); > ``` > > > [!NOTE] > > > > `borrowIxIndex: 0` says 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. > > > [!NOTE] > > > > The flash repay takes the amount plus the reserve's flash loan fee (`reserve.state.config.fees.flashLoanFeeSf`, 0.001% for USDC on the SOL/BTC Market). The wallet must already hold enough USDC in that token account to pay the fee, or the repay fails with insufficient funds. > > **Step 5** > > ### 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={"theme":"css-variables"} > const memoIx = getAddMemoInstruction({ memo: 'Hello Kamino' }); > > const allInstructions = [flashBorrowIx, memoIx, flashRepayIx]; > ``` > > **Step 6** > > ### Build and Send Transaction > > Build the transaction with a fresh blockhash and send it to the network. > > ```typescript theme={"theme":"css-variables"} > 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(allInstructions, tx) > ); > > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: false, > }); > > console.log('Flash loan successful! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > Your flash loan transaction is complete! The borrowed funds were used for your operations and automatically repaid within the same atomic transaction. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Fetch Reserve Data > > ```rust theme={"theme":"css-variables"} > use klend_interface::helpers; > use klend_interface::ReserveInfo; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > > let reserve_data = rpc_client.get_account(&reserve_pubkey)?; > let reserve = ReserveInfo::from_account_data(reserve_pubkey, &reserve_data.data)?; > ``` > > > [!NOTE] > > > > Use `ReserveInfo::from_account_data(pubkey, &data)` to construct reserve info from raw RPC account bytes. > > **Step 4** > > ### Derive Token Accounts > > ```rust theme={"theme":"css-variables"} > use spl_associated_token_account::get_associated_token_address; > > let user_token_account = get_associated_token_address(&owner, &reserve.liquidity_mint); > ``` > > **Step 5** > > ### Build Flash Loan Instructions > > ```rust theme={"theme":"css-variables"} > let (borrow_ix, repay_ix) = helpers::flash::flash_loan( > owner, > &reserve, > user_token_account, // source for repayment > user_token_account, // destination for borrowed funds > 1_000_000, // 1 USDC (6 decimals) > 0, // borrow instruction index in the transaction > None, // no referrer > ); > ``` > > > [!NOTE] > > > > The `borrow_instruction_index` parameter specifies the position of the flash borrow instruction in the final transaction. Set to `0` if it is the first instruction. > > **Step 6** > > ### Compose and Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > // Insert your custom instructions between borrow and repay > let your_custom_instructions = vec![/* your logic here */]; > > let mut all_instructions = vec![borrow_ix]; > all_instructions.extend(your_custom_instructions); > all_instructions.push(repay_ix); > > let message = Message::new(&all_instructions, Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Flash loan successful! Signature: {signature}"); > ``` > > > [!NOTE] > > > > The flash borrow and repay must be in the same transaction. You can insert any number of instructions between them. # Markets Source: https://docs.kamino.com/build/tutorials/borrow/index Learn how to access market data including supply APY, borrow APY, TVL, and utilization rates for lending reserves > [card] [Borrow & Lend](/build/borrow/index) > > Borrow and lend assets ## Get Market Information Retrieve market-wide TVL metrics for deposits and borrows. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > > console.log({ > totalDepositsUsd: market!.getTotalDepositTVL().toFixed(2), > totalBorrowsUsd: market!.getTotalBorrowTVL().toFixed(2), > }); > ``` > > View Code ## Get Reserve Supply and Borrow APY Fetch historical supply APY and borrow APY data for a specific reserve over time. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const marketPubkey = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; > const reservePubkey = '37Jk2zkz23vkAYBT66HM2gaqJuNg2nYLsCreQAVt5MWK'; > > const params = new URLSearchParams({ > start: '2026-10-15T00:00:00.000Z', > end: '2026-10-22T00:00:00.000Z', > frequency: 'day', > }); > > const res = await fetch( > `${API_BASE_URL}/kamino-market/${marketPubkey}/reserves/${reservePubkey}/metrics/history?${params}` > ); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > > const { history } = await res.json(); > > console.table( > history.map((item) => ({ > date: item.timestamp.slice(0, 10), > symbol: item.metrics.symbol, > supplyAPY: `${(item.metrics.supplyInterestAPY * 100).toFixed(2)}%`, > borrowAPY: `${(item.metrics.borrowInterestAPY * 100).toFixed(2)}%`, > depositTvlUsd: Number(item.metrics.depositTvl).toFixed(2), > borrowTvlUsd: Number(item.metrics.borrowTvl).toFixed(2), > })) > ); > ``` > > View Code ## Get Reserve Information Check detailed metrics for all reserves including supply APY, borrow APY, deposit TVL, borrow TVL, and utilization rates. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const reserves = market!.getReserves().map((reserve) => ({ > symbol: reserve.getTokenSymbol(), > kind: reserve.getKind().toString(), > supplyAPY: `${(reserve.totalSupplyAPY(ledgerInstant) * 100).toFixed(2)}%`, > borrowAPY: `${(reserve.totalBorrowAPY(ledgerInstant) * 100).toFixed(2)}%`, > utilization: `${(reserve.calculateUtilizationRatio() * 100).toFixed(2)}%`, > depositTvlUsd: reserve.getDepositTvl().toFixed(2), > borrowTvlUsd: reserve.getBorrowTvl().toFixed(2), > })); > > console.table(reserves); > ``` > > > [!NOTE] > > > > A token can have several reserves: one variable-rate reserve plus fixed-rate ones, so each row shows its kind. Fixed-rate APYs depend on the slot duration passed to `KaminoMarket.load`. A hard-coded value such as 400 ms shows them at about half their real rate, because mainnet slots are closer to 210 ms. > > View Code ## Get Reserve Reward History Fetches historical KLend reward metrics for a specific deposit and borrow reserve pair. > [!NOTE] > > This endpoint returns KMNO reward incentives for specific deposit and borrow reserve combinations. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const depositReservePubkey = 'd4A2prbA2whesmvHaL88BH6Ewn5N4bTSU2Ze8P6Bc4Q'; > const borrowReservePubkey = 'D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59'; > > const params = new URLSearchParams({ > start: '2025-11-07T00:00:00.000Z', > end: '2025-11-14T23:59:59.999Z', > frequency: 'day', > }); > > const res = await fetch( > `${API_BASE_URL}/klend/${depositReservePubkey}/${borrowReservePubkey}/rewards/history?${params}` > ); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > > const rewards = await res.json(); > > console.table( > rewards.map((item) => ({ > date: item.timestamp.slice(0, 10), > rewardToken: item.rewardTokenMint, > rewardAPY: `${(item.rewardApy * 100).toFixed(2)}%`, > })) > ); > ``` > > > [!NOTE] > > > > The endpoint only returns rows for windows when the pair had KMNO incentives. Other windows return an empty array. > > View Code ## Get User Obligation Info Retrieve detailed obligation information including deposits, borrows, and health metrics. > [tab] TypeScript > > ```typescript expandable theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > VanillaObligation, > PROGRAM_ID, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const userAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligation = await market!.getObligationByWallet(userAddress, new VanillaObligation(PROGRAM_ID)); > > if (!obligation) { > console.log('No obligation found for user:', userAddress); > } > > const positions = [ > ...obligation!.getDeposits().map((position) => ({ side: 'deposit', ...position })), > ...obligation!.getBorrows().map((position) => ({ side: 'borrow', ...position })), > ]; > > console.table( > positions.map((position) => ({ > side: position.side, > symbol: market!.getReserveByAddress(position.reserveAddress)?.getTokenSymbol(), > amount: position.amount.div(position.mintFactor).toFixed(6), > valueUsd: position.marketValueRefreshed.toFixed(2), > })) > ); > > console.log({ > ltv: `${obligation!.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > liquidationLtv: `${obligation!.refreshedStats.liquidationLtv.mul(100).toFixed(2)}%`, > borrowUtilization: `${obligation!.refreshedStats.borrowUtilization.mul(100).toFixed(2)}%`, > }); > ``` > > View Code ## Get All User Obligations Retrieve all obligations for a user wallet, including different obligation types across the market. > [tab] TypeScript > > ```typescript expandable theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > ObligationTypeTag, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const userAddress = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligations = await market!.getAllUserObligations(userAddress, await getCurrentLedgerInstant(rpc)); > > if (obligations.length === 0) { > console.log('No obligations found for wallet:', userAddress); > } > > for (const obligation of obligations) { > console.log(`\nObligation ${obligation.obligationAddress} (${ObligationTypeTag[obligation.obligationTag]})`); > console.table( > [ > ...obligation.getDeposits().map((position) => ({ side: 'deposit', ...position })), > ...obligation.getBorrows().map((position) => ({ side: 'borrow', ...position })), > ].map((position) => ({ > side: position.side, > symbol: market!.getReserveByAddress(position.reserveAddress)?.getTokenSymbol(), > amount: position.amount.div(position.mintFactor).toFixed(6), > valueUsd: position.marketValueRefreshed.toFixed(2), > })) > ); > console.log({ > ltv: `${obligation.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > liquidationLtv: `${obligation.refreshedStats.liquidationLtv.mul(100).toFixed(2)}%`, > }); > } > ``` > > View Code ## Get All Obligations by Reserve Retrieve all obligations that have deposits in a specific reserve. Useful for analyzing reserve utilization and user exposure. > [tab] TypeScript > > ```typescript expandable theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoMarket, > ObligationTypeTag, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); > const reserveAddress = address('37Jk2zkz23vkAYBT66HM2gaqJuNg2nYLsCreQAVt5MWK'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > const obligations = await market!.getAllObligationsByDepositedReserve( > reserveAddress, > await getCurrentLedgerInstant(rpc) > ); > > console.log(`Found ${obligations.length} obligations with deposits in this reserve`); > > console.table( > obligations.map((obligation) => ({ > obligation: obligation.obligationAddress, > type: ObligationTypeTag[obligation.obligationTag], > depositUsd: obligation.getDepositByReserve(reserveAddress)?.marketValueRefreshed.toFixed(2), > totalBorrowsUsd: obligation.refreshedStats.userTotalBorrow.toFixed(2), > ltv: `${obligation.refreshedStats.loanToValue.mul(100).toFixed(2)}%`, > })) > ); > ``` > > > [!WARNING] > > > > This reads every obligation in the market. Public RPC endpoints reject it, so use a private RPC. > > View Code ## Get User Transaction History Access all transaction history for a user's wallet across deposits, borrows, repayments, and liquidations. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const API_BASE_URL = 'https://api.kamino.finance'; > const marketPubkey = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'; > const userPubkey = 'EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'; > > const res = await fetch(`${API_BASE_URL}/v2/kamino-market/${marketPubkey}/users/${userPubkey}/transactions`); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > > const transactionsByObligation = await res.json(); > > for (const [obligation, transactions] of Object.entries(transactionsByObligation)) { > console.log(`\nObligation ${obligation}`); > console.table( > transactions.map((tx) => ({ > date: tx.createdOn.slice(0, 10), > type: tx.transactionName, > token: tx.liquidityToken, > amount: tx.liquidityTokenAmount, > usdValue: Number(tx.liquidityUsdValue).toFixed(2), > })) > ); > } > ``` > > > [!NOTE] > > > > Results are grouped by obligation address. A market where the wallet has no obligation returns an empty object. > > View Code # Build a Liquidation Bot with KSwap Source: https://docs.kamino.com/build/tutorials/borrow/liquidation-bot Build a bot that monitors obligations, identifies profitable pairs, swaps into debt tokens via KSwap, and executes liquidations Liquidations on Kamino are permissionless. Any wallet can liquidate an unhealthy obligation and earn a bonus. Bots continuously monitor all obligations and execute when one crosses its health limit. ## Scanning for Unhealthy Positions The first step is loading every obligation in a market and checking which ones have breached their health limit. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, createSolanaRpcSubscriptions, address } from '@solana/kit'; > import { > KaminoMarket, > KaminoObligation, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **Step 2** > > ### Set Up RPC and Load Market > > ```typescript theme={"theme":"css-variables"} > const KEYPAIR_FILE = '/path/to/your/keypair.json'; > const liquidator = await parseKeypairFile(KEYPAIR_FILE); > > const rpc = createSolanaRpc('https://your-private-rpc.example.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://your-private-rpc.example.com'); > const marketPubkey = address('7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF'); // SOL/BTC Market > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > > [!WARNING] > > > > Scanning reads every obligation in the market. Public RPC endpoints reject it, so use a private RPC. On the SOL/BTC Market it reads over 100,000 obligations and takes about five minutes. > > > [!NOTE] > > > > Kamino operates multiple markets (SOL/BTC, JLP, Altcoins, Prime). A production bot should scan all of them. See [Markets](/products/borrow/markets) for the full list. > > **Step 3** > > ### Scan Obligations in Batches > > An obligation is liquidatable when its LTV reaches its liquidation LTV. The scan also tracks the obligation closest to liquidation. > > ```typescript theme={"theme":"css-variables"} > const healthRatio = (obligation: KaminoObligation) => obligation.loanToValue().div(obligation.liquidationLtv()); > > const liquidatable: KaminoObligation[] = []; > let closest: KaminoObligation | undefined; > let scanned = 0; > > for await (const batch of market!.batchGetAllObligationsForMarket(await getCurrentLedgerInstant(rpc))) { > scanned += batch.length; > const withDebt = batch.filter( > (obligation) => obligation.refreshedStats.userTotalBorrow.gt(0) && obligation.liquidationLtv().gt(0) > ); > liquidatable.push(...withDebt.filter((obligation) => healthRatio(obligation).gte(1))); > closest = withDebt.reduce((a, b) => (healthRatio(b).gt(healthRatio(a!)) ? b : a), closest ?? withDebt[0]); > } > > console.log(`Scanned ${scanned} obligations, ${liquidatable.length} liquidatable`); > ``` > > > [!NOTE] > > > > `loanToValue()` and `liquidationLtv()` compute both at current prices over all deposits, the way the program checks. Don't use the obligation's stored values such as `getUnhealthyBorrowValue()`: they're from its last on-chain refresh and can mark a healthy obligation as liquidatable. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = { version = "0.6.0", features = ["solana-account"] } > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > solana-account = "2.1" > solana-account-decoder-client-types = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > reqwest = { version = "~0.12", features = ["blocking", "json"] } > serde = { version = "1", features = ["derive"] } > serde_json = "1" > bincode = "1" > base64 = "0.22" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let rpc_client = RpcClient::new("YOUR_RPC_URL"); > let market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF")?; > ``` > > > [!WARNING] > > > > Scanning obligations requires `getProgramAccounts`, which returns thousands of accounts per market. The public Solana RPC will reject these calls. Use a private RPC provider (Helius, Triton, QuickNode, etc.). > > **Step 3** > > ### Fetch All Obligations > > Fetch every obligation in the market using `get_program_accounts` with filters for the discriminator, lending market, and account size. > > ```rust theme={"theme":"css-variables"} > use klend_interface::{ > state::{Obligation, SplDiscriminate}, > KLEND_PROGRAM_ID, > }; > use solana_account::ReadableAccount; > use solana_account_decoder_client_types::UiAccountEncoding; > use solana_client::{ > rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig}, > rpc_filter::{Memcmp, RpcFilterType}, > }; > > const OBLIGATION_ACCOUNT_SIZE: u64 = 8 + std::mem::size_of::() as u64; > > let filters = vec![ > RpcFilterType::Memcmp(Memcmp::new_raw_bytes( > 0, > Obligation::SPL_DISCRIMINATOR_SLICE.to_vec(), > )), > RpcFilterType::Memcmp(Memcmp::new_raw_bytes(32, market.to_bytes().to_vec())), > RpcFilterType::DataSize(OBLIGATION_ACCOUNT_SIZE), > ]; > > let config = RpcProgramAccountsConfig { > filters: Some(filters), > account_config: RpcAccountInfoConfig { > encoding: Some(UiAccountEncoding::Base64Zstd), > ..Default::default() > }, > ..Default::default() > }; > > let accounts = rpc_client.get_program_accounts_with_config(&KLEND_PROGRAM_ID, config)?; > ``` > > > [!WARNING] > > > > Obligation accounts exceed the 128-byte limit for base58 responses. Use `Base64Zstd` encoding or the RPC will silently return zero results. > > **Step 4** > > ### Filter to Liquidatable Positions > > Parse each obligation and check `is_liquidatable()`, which returns true when borrow-factor-adjusted debt exceeds the unhealthy borrow value. > > ```rust theme={"theme":"css-variables"} > use klend_interface::Fraction; > > let mut liquidatable = Vec::new(); > > for (pubkey, account) in &accounts { > let obligation = klend_interface::from_account_data::(account.data())?; > > if obligation.has_debt == 0 { > continue; > } > > if obligation.is_liquidatable() { > let debt: f64 = Fraction::from_bits( > obligation.borrowed_assets_market_value() > ).to_num(); > > println!("Liquidatable: {pubkey} — debt: ${debt:.2}"); > liquidatable.push((*pubkey, obligation)); > } > } > > println!("Initial candidates (stale prices): {}", liquidatable.len()); > ``` > > **Step 5** > > ### Verify with Fresh Prices > > On-chain obligation values are only updated when `RefreshObligation` is called. Fetch fresh oracle prices from the Scope REST API and re-verify each candidate to avoid wasting transaction fees on false positives. > > ```rust theme={"theme":"css-variables"} > use klend_interface::state::{Reserve, from_account_data}; > use serde::Deserialize; > use std::collections::{HashMap, HashSet}; > > #[derive(Deserialize)] > struct OraclePrice { > mint: String, > price: String, > } > > // Collect all reserve pubkeys from candidates > let reserve_pubkeys: Vec = liquidatable > .iter() > .flat_map(|(_, obl)| { > obl.deposits.iter().map(|d| d.deposit_reserve) > .chain(obl.borrows.iter().map(|b| b.borrow_reserve)) > .filter(|pk| *pk != Pubkey::default()) > }) > .collect::>() > .into_iter() > .collect(); > > // Fetch reserves to map mints to prices and get borrow factors > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_pubkeys)?; > let reserve_map: HashMap = reserve_pubkeys > .iter() > .zip(reserve_accounts.iter()) > .filter_map(|(pk, acc)| { > acc.as_ref().and_then(|a| { > from_account_data::(&a.data).ok().map(|r| (*pk, *r)) > }) > }) > .collect(); > > // Fetch fresh prices from the Scope REST API > let fresh_prices: HashMap = reqwest::blocking::get( > "https://api.kamino.finance/oracles/prices", > ) > .ok() > .and_then(|r| r.json::>().ok()) > .map(|prices| prices.into_iter() > .filter_map(|p| p.price.parse::().ok().map(|v| (p.mint, v))) > .collect()) > .unwrap_or_default(); > > let mut verified = Vec::new(); > > for (pubkey, obligation) in &liquidatable { > // Re-price deposits > let mut fresh_deposited = 0.0f64; > let mut fresh_unhealthy = 0.0f64; > for deposit in &obligation.deposits { > if deposit.deposit_reserve == Pubkey::default() { continue; } > let reserve = match reserve_map.get(&deposit.deposit_reserve) { > Some(r) => r, > None => continue, > }; > let mint = reserve.liquidity.mint_pubkey; > let stale_price: f64 = Fraction::from_bits( > u128::from(reserve.liquidity.market_price_sf) > ).to_num(); > let price = fresh_prices.get(&mint.to_string()).copied().unwrap_or(stale_price); > let amount: f64 = Fraction::from_bits(deposit.deposited_amount.into()).to_num(); > let value = amount / 10f64.powi(reserve.liquidity.mint_decimals as i32) * price; > fresh_deposited += value; > fresh_unhealthy += value * reserve.liquidation_threshold_pct() as f64 / 100.0; > } > > // Re-price borrows > let mut fresh_adjusted_debt = 0.0f64; > for borrow in &obligation.borrows { > if borrow.borrow_reserve == Pubkey::default() { continue; } > let reserve = match reserve_map.get(&borrow.borrow_reserve) { > Some(r) => r, > None => continue, > }; > let mint = reserve.liquidity.mint_pubkey; > let stale_price: f64 = Fraction::from_bits( > u128::from(reserve.liquidity.market_price_sf) > ).to_num(); > let price = fresh_prices.get(&mint.to_string()).copied().unwrap_or(stale_price); > let amount: f64 = Fraction::from_bits(borrow.borrowed_amount()).to_num(); > let value = amount / 10f64.powi(reserve.liquidity.mint_decimals as i32) * price; > fresh_adjusted_debt += value * reserve.borrow_factor_pct() as f64 / 100.0; > } > > // Still liquidatable at fresh prices? > if fresh_adjusted_debt > fresh_unhealthy { > verified.push((*pubkey, *obligation)); > } > } > > println!("Verified {} out of {} candidates with fresh prices", verified.len(), liquidatable.len()); > ``` ## Picking the Most Profitable Pair An obligation can have multiple collateral deposits and multiple borrows. The liquidator must choose one debt token to repay and one collateral token to seize. The program enforces priority rules: target the lowest-threshold collateral and the highest-borrow-factor debt first. > [tab] TypeScript > > **Step 1** > > ### Choose the Obligation > > Liquidations are rare. When the scan finds none, print the closest obligation and stop before swapping anything. > > ```typescript theme={"theme":"css-variables"} > if (liquidatable.length === 0) { > console.log('Closest to liquidation:', closest?.obligationAddress, `health ratio ${closest && healthRatio(closest).toFixed(4)}`); > process.exit(0); > } > > const obligation = liquidatable[0]; > ``` > > **Step 2** > > ### Select the Target Pair > > Seize the riskiest collateral (lowest liquidation threshold) and repay the most heavily weighted debt (highest borrow factor). > > ```typescript theme={"theme":"css-variables"} > const [collateral] = obligation > .getDeposits() > .map((position) => market!.getReserveByAddress(position.reserveAddress)!) > .filter((reserve) => reserve.state.config.loanToValuePct > 0) > .sort((a, b) => a.state.config.liquidationThresholdPct - b.state.config.liquidationThresholdPct); > > const [debtPosition] = obligation > .getBorrows() > .sort( > (a, b) => > Number(market!.getReserveByAddress(b.reserveAddress)!.state.config.borrowFactorPct) - > Number(market!.getReserveByAddress(a.reserveAddress)!.state.config.borrowFactorPct) > ); > const debtReserve = market!.getReserveByAddress(debtPosition.reserveAddress)!; > ``` > [tab] Rust > > **Step 1** > > ### Fetch Reserve Data > > Collect all unique reserve pubkeys from the obligation's deposits and borrows, then fetch and parse them in one RPC call. > > ```rust theme={"theme":"css-variables"} > use klend_interface::state::{Reserve, from_account_data}; > use std::collections::HashSet; > > let active_deposits: Vec<_> = obligation > .deposits > .iter() > .filter(|d| d.deposit_reserve != Pubkey::default()) > .collect(); > > let active_borrows: Vec<_> = obligation > .borrows > .iter() > .filter(|b| b.borrow_reserve != Pubkey::default()) > .collect(); > > let reserve_pubkeys: Vec = active_deposits > .iter() > .map(|d| d.deposit_reserve) > .chain(active_borrows.iter().map(|b| b.borrow_reserve)) > .collect::>() > .into_iter() > .collect(); > > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_pubkeys)?; > > let parsed_reserves: Vec<(Pubkey, Reserve)> = reserve_pubkeys > .iter() > .zip(reserve_accounts.iter()) > .filter_map(|(pk, acc_opt)| { > let acc = acc_opt.as_ref()?; > let reserve = from_account_data::(&acc.data).ok()?; > Some((*pk, *reserve)) > }) > .collect(); > ``` > > **Step 2** > > ### Sort by Priority > > Sort deposits by `liquidation_threshold_pct` ascending (weakest collateral first) and borrows by `borrow_factor_pct` descending (riskiest debt first). > > ```rust theme={"theme":"css-variables"} > let mut deposit_pairs: Vec<(Pubkey, &Reserve)> = active_deposits > .iter() > .filter_map(|d| { > parsed_reserves > .iter() > .find(|(pk, _)| *pk == d.deposit_reserve) > .map(|(pk, r)| (*pk, r)) > }) > .collect(); > > deposit_pairs.sort_by_key(|(_, r)| r.liquidation_threshold_pct()); > > let mut borrow_pairs: Vec<(Pubkey, &Reserve)> = active_borrows > .iter() > .filter_map(|b| { > parsed_reserves > .iter() > .find(|(pk, _)| *pk == b.borrow_reserve) > .map(|(pk, r)| (*pk, r)) > }) > .collect(); > > borrow_pairs.sort_by(|(_, a), (_, b)| b.borrow_factor_pct().cmp(&a.borrow_factor_pct())); > ``` > > **Step 3** > > ### Select the Target Pair > > The first entry in each sorted list is the priority target. Collateral reserves with `loan_to_value_pct == 0` are deposit-only and cannot be seized. > > ```rust theme={"theme":"css-variables"} > let withdraw_pair = deposit_pairs > .iter() > .find(|(_, r)| r.loan_to_value_pct() > 0); > > let repay_pair = borrow_pairs.first(); > > match (withdraw_pair, repay_pair) { > (Some((coll_pk, coll_reserve)), Some((debt_pk, debt_reserve))) => { > println!("Seize collateral: {coll_pk} (mint: {})", coll_reserve.liquidity.mint_pubkey); > println!("Repay debt: {debt_pk} (mint: {})", debt_reserve.liquidity.mint_pubkey); > } > _ => println!("No valid liquidation pair found"), > } > ``` ## Executing the Liquidation Once an unhealthy obligation and target pair have been identified, build and send the liquidation transaction. > [tab] TypeScript > > **Step 1** > > ### Import Transaction Utilities > > ```typescript theme={"theme":"css-variables"} > import { > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > compressTransactionMessageUsingAddressLookupTables, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > type Address, > type Instruction, > } from '@solana/kit'; > import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; > import { KaminoAction } from '@kamino-finance/klend-sdk'; > import { KswapSdk, loadRouterContext } from '@kamino-finance/kswap-sdk'; > import BN from 'bn.js'; > import Decimal from 'decimal.js'; > ``` > > **Step 2** > > ### Calculate Repay Amount > > One liquidation can repay up to the market's close factor share of the debt. > > ```typescript theme={"theme":"css-variables"} > const SLIPPAGE_BPS = 50; > const MAX_COMPUTE_UNITS = 1_400_000; > const slippage = new Decimal(SLIPPAGE_BPS).div(10_000); > > const repayLamports = debtPosition.amount.mul(market!.state.liquidationMaxDebtCloseFactorPct).div(100).floor(); > const repayUsd = repayLamports.div(debtReserve.getMintFactor()).mul(debtReserve.getOracleMarketPrice()); > > console.log(`Liquidating ${obligation.obligationAddress}: repay ${repayUsd.toFixed(2)} USD of ${debtReserve.getTokenSymbol()}`); > ``` > > **Step 3** > > ### Size the SOL Swap > > Price the repay in SOL with the market's own oracle prices, plus slippage, and check the wallet holds it. > > ```typescript theme={"theme":"css-variables"} > const solMint = address('So11111111111111111111111111111111111111112'); > const solReserve = market!.getExistingFloatRateReserveByMint(solMint); > > const solLamports = repayUsd > .div(solReserve.getOracleMarketPrice()) > .mul(solReserve.getMintFactor()) > .mul(slippage.plus(1)) > .ceil(); > > const { value: balance } = await rpc.getBalance(liquidator.address).send(); > if (solLamports.gt(balance.toString())) { > console.log(`Not enough SOL: need ${solLamports.div(solReserve.getMintFactor())} SOL for the swap`); > process.exit(0); > } > ``` > > **Step 4** > > ### Define a Send Helper > > ```typescript theme={"theme":"css-variables"} > const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); > > async function send(instructions: Instruction[], lookupTableAddresses: Record) { > const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signedTransaction = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayerSigner(liquidator, tx), > (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), > (tx) => appendTransactionMessageInstructions(instructions, tx), > (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) > ) > ); > assertIsTransactionWithinSizeLimit(signedTransaction); > await sendAndConfirm(signedTransaction, { commitment: 'confirmed', skipPreflight: true }); > return getSignatureFromTransaction(signedTransaction); > } > ``` > > **Step 5** > > ### Swap SOL into the Debt Token via KSwap > > ```typescript theme={"theme":"css-variables"} > const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); > > const { routes } = await kswap.getAllRoutes( > { > executor: liquidator.address, > tokenIn: solMint, > tokenOut: debtPosition.mintAddress, > amount: new BN(solLamports.toFixed(0)), > maxSlippageBps: SLIPPAGE_BPS, > swapType: 'exactIn', > wrapAndUnwrapSol: true, > }, > await loadRouterContext(rpc, solMint, debtPosition.mintAddress) > ); > if (routes.length === 0) { > console.log('No KSwap route found for SOL ->', debtPosition.mintAddress); > } > > const [swapRoute] = routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); > const swapIxs = swapRoute.instructions!; > > const swapSignature = await send( > [...swapIxs.createInAtaIxs, ...swapIxs.wrapSolIxs, ...swapIxs.swapIxs, ...swapIxs.unwrapSolIxs, ...swapIxs.createOutAtaIxs], > Object.fromEntries((swapRoute.lookupTableAccounts ?? []).map((lut) => [lut.address, lut.data.addresses])) > ); > console.log('Swapped SOL into the debt token:', swapSignature); > ``` > > > [!NOTE] > > > > Use `@kamino-finance/kswap-sdk` 2.9.0, the last version on `@solana/kit` 2. The swap is exact-in so every KSwap router is available: exact-out routes currently come only from Jupiter-based routers. > > **Step 6** > > ### Calculate Minimum Collateral > > The minimum collateral to accept assumes the smallest liquidation bonus, takes off the protocol's liquidation fee, and allows for slippage. > > ```typescript theme={"theme":"css-variables"} > const collateralConfig = collateral.state.config; > > const minCollateralLamports = repayUsd > .mul(new Decimal(collateralConfig.minLiquidationBonusBps).div(10_000).plus(1)) > .mul(new Decimal(1).minus(new Decimal(collateralConfig.protocolLiquidationFeePct).div(100))) > .mul(new Decimal(1).minus(slippage)) > .div(collateral.getOracleMarketPrice()) > .mul(collateral.getMintFactor()) > .floor(); > ``` > > **Step 7** > > ### Build the Liquidation Instructions > > ```typescript theme={"theme":"css-variables"} > const liquidateAction = await KaminoAction.buildLiquidateTxns({ > kaminoMarket: market!, > amount: new BN(repayLamports.toFixed(0)), > minCollateralReceiveAmount: new BN(minCollateralLamports.toFixed(0)), > repayReserveAddress: debtReserve.address, > withdrawReserveAddress: collateral.address, > liquidator, > obligationOwner: obligation.state.owner, > obligation, > useV2Ixs: true, > extraComputeBudget: MAX_COMPUTE_UNITS, > initUserMetadata: { skipInitialization: true, skipLutCreation: true }, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > > const liquidateIxs = KaminoAction.actionToIxs(liquidateAction); > ``` > > **Step 8** > > ### Fetch Lookup Tables and Send > > ```typescript theme={"theme":"css-variables"} > const addresses = [ > ...new Set(liquidateIxs.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), > ]; > > const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { > method: 'POST', > headers: { 'Content-Type': 'application/json' }, > body: JSON.stringify({ addresses }), > }); > if (!lutResponse.ok) { > console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); > } > > const { lutAddresses } = await lutResponse.json(); > const lookupTables = await fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); > > const liquidationSignature = await send( > liquidateIxs, > Object.fromEntries(lookupTables.map((lut) => [lut.address, lut.data.addresses])) > ); > console.log('Liquidation executed:', liquidationSignature); > ``` > > > [!TIP] > > > > The debt is repaid and the collateral, including the liquidation bonus, is in the liquidator's wallet. > [tab] Rust > > **Step 1** > > ### Fetch Obligation and Reserves > > Use `ObligationContext` to discover all reserves referenced by the obligation, then fetch them in one RPC call. > > ```rust theme={"theme":"css-variables"} > use klend_interface::{ > helpers::refresh, > instructions::liquidate::{ > liquidate_obligation_and_redeem_reserve_collateral_v2, > LiquidateObligationAndRedeemReserveCollateralV2Accounts, > }, > pda, > state::{LendingMarket, Obligation, Reserve, from_account_data}, > Fraction, ObligationContext, ObligationInfo, ReserveInfo, KLEND_PROGRAM_ID, > }; > use solana_instruction::AccountMeta; > use solana_sdk::signer::{keypair::read_keypair_file, Signer}; > > let signer = read_keypair_file("/path/to/liquidator-keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > > let obligation_account = rpc_client.get_account(&obligation_pubkey)?; > let obligation = from_account_data::(&obligation_account.data)?; > > let reserve_addrs = ObligationContext::reserve_addresses_for_obligation( > &obligation_account.data, > )?; > let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; > > let parsed_reserves: Vec<(Pubkey, Reserve)> = reserve_addrs > .iter() > .zip(reserve_accounts.iter()) > .filter_map(|(pk, acc)| { > acc.as_ref().and_then(|a| { > from_account_data::(&a.data).ok().map(|r| (*pk, *r)) > }) > }) > .collect(); > > let repay_reserve = parsed_reserves.iter() > .find(|(pk, _)| *pk == repay_reserve_pubkey) > .map(|(_, r)| r) > .expect("Repay reserve not found"); > > let withdraw_reserve = parsed_reserves.iter() > .find(|(pk, _)| *pk == withdraw_reserve_pubkey) > .map(|(_, r)| r) > .expect("Withdraw reserve not found"); > ``` > > **Step 2** > > ### Calculate Repay Amount > > Fetch the `LendingMarket` account to read the close factor, then calculate the maximum repayable amount from the borrow position. > > ```rust theme={"theme":"css-variables"} > let borrow_position = obligation.borrows.iter() > .find(|b| b.borrow_reserve == repay_reserve_pubkey) > .expect("Borrow position not found"); > > let borrowed_amount: u64 = Fraction::from_bits( > borrow_position.borrowed_amount() > ).to_num(); > > let market_account = rpc_client.get_account(&obligation.lending_market)?; > let lending_market = from_account_data::(&market_account.data)?; > > let close_factor = lending_market.liquidation_max_debt_close_factor_pct; > let repay_amount = (borrowed_amount as f64 * close_factor as f64 / 100.0) as u64; > ``` > > **Step 3** > > ### Swap into Debt Token via KSwap > > If the liquidator does not hold the debt token, swap into it using the KSwap REST API before liquidating. > > ```rust theme={"theme":"css-variables"} > use serde::Deserialize; > use solana_sdk::transaction::VersionedTransaction; > > #[derive(Deserialize)] > struct KswapResponse { data: KswapData } > > #[derive(Deserialize)] > #[serde(rename_all = "camelCase")] > struct KswapData { > transaction: String, > expected_amount_out: String, > min_amount_out: String, > } > > let liquidator_debt_ata = > spl_associated_token_account::get_associated_token_address_with_program_id( > &owner, > &repay_reserve.liquidity.mint_pubkey, > &repay_reserve.liquidity.token_program, > ); > > use spl_token::state::Account as TokenAccount; > use solana_sdk::program_pack::Pack; > > let wallet_balance = rpc_client.get_account(&liquidator_debt_ata) > .ok() > .and_then(|a| TokenAccount::unpack(&a.data).ok()) > .map(|acct| acct.amount) > .unwrap_or(0); > > if wallet_balance < repay_amount { > let wsol = Pubkey::from_str("So11111111111111111111111111111111111111112")?; > > // Calculate how much SOL to swap based on debt USD value > let debt_price: f64 = Fraction::from_bits( > u128::from(repay_reserve.liquidity.market_price_sf) > ).to_num(); > let repay_usd = repay_amount as f64 > / 10f64.powi(repay_reserve.liquidity.mint_decimals as i32) * debt_price; > let sol_price = parsed_reserves.iter() > .find(|(_, r)| r.liquidity.mint_pubkey == wsol) > .map(|(_, r)| Fraction::from_bits( > u128::from(r.liquidity.market_price_sf) > ).to_num::()) > .unwrap_or(100.0); > let sol_balance = rpc_client.get_balance(&owner)?; > let swap_amount = (repay_usd / sol_price * 1e9) as u64; > let swap_amount = swap_amount.min(sol_balance.saturating_sub(5_000_000)); > > let client = reqwest::blocking::Client::new(); > let resp = client > .get("https://api.kamino.finance/kswap/swap/") > .query(&[ > ("tokenIn", wsol.to_string()), > ("tokenOut", repay_reserve.liquidity.mint_pubkey.to_string()), > ("amountIn", swap_amount.to_string()), > ("maxSlippageBps", "50".to_string()), > ("wallet", owner.to_string()), > ("wrapAndUnwrapSol", "true".to_string()), > ]) > .send()?; > > if !resp.status().is_success() { > let status = resp.status(); > let body = resp.text().unwrap_or_default(); > return Err(format!("KSwap API error {status}: {body}").into()); > } > > let kswap: KswapResponse = resp.json()?; > > // Decode, re-sign, and send the swap transaction > use base64::Engine; > let tx_bytes = base64::engine::general_purpose::STANDARD > .decode(&kswap.data.transaction)?; > let swap_tx: VersionedTransaction = bincode::deserialize(&tx_bytes)?; > let blockhash = rpc_client.get_latest_blockhash()?; > let mut msg = swap_tx.message; > msg.set_recent_blockhash(blockhash); > let signed = VersionedTransaction::try_new(msg, &[&signer])?; > rpc_client.send_and_confirm_transaction_with_spinner(&signed)?; > } > ``` > > **Step 4** > > ### Derive Token Accounts > > Derive ATAs using the actual token programs from the reserve data. The collateral cToken mint address is read directly from the `Reserve` struct. > > ```rust theme={"theme":"css-variables"} > let user_source_liquidity = > spl_associated_token_account::get_associated_token_address_with_program_id( > &owner, > &repay_reserve.liquidity.mint_pubkey, > &repay_reserve.liquidity.token_program, > ); > > let ctoken_mint = withdraw_reserve.collateral.mint_pubkey; > let ctoken_program = rpc_client.get_account(&ctoken_mint) > .map(|a| a.owner) > .unwrap_or(spl_token::ID); > > let user_destination_collateral = > spl_associated_token_account::get_associated_token_address_with_program_id( > &owner, &ctoken_mint, &ctoken_program, > ); > > let user_destination_liquidity = > spl_associated_token_account::get_associated_token_address_with_program_id( > &owner, > &withdraw_reserve.liquidity.mint_pubkey, > &withdraw_reserve.liquidity.token_program, > ); > ``` > > **Step 5** > > ### Create Token Accounts > > Create the associated token accounts if they do not already exist. Uses `create_associated_token_account_idempotent` which is a no-op if the account is already initialized. > > ```rust theme={"theme":"css-variables"} > let ata_ixs = vec![ > spl_associated_token_account::instruction::create_associated_token_account_idempotent( > &owner, &owner, &repay_reserve.liquidity.mint_pubkey, &repay_reserve.liquidity.token_program, > ), > spl_associated_token_account::instruction::create_associated_token_account_idempotent( > &owner, &owner, &ctoken_mint, &ctoken_program, > ), > spl_associated_token_account::instruction::create_associated_token_account_idempotent( > &owner, &owner, &withdraw_reserve.liquidity.mint_pubkey, &withdraw_reserve.liquidity.token_program, > ), > ]; > > let blockhash = rpc_client.get_latest_blockhash()?; > let ata_tx = Transaction::new(&[&signer], Message::new(&ata_ixs, Some(&owner)), blockhash); > rpc_client.send_and_confirm_transaction(&ata_tx)?; > ``` > > **Step 6** > > ### Build Liquidation Instructions > > Build refresh instructions for each reserve and the obligation, then the liquidation instruction using actual addresses from the `Reserve` struct. > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let (lma, _) = pda::lending_market_authority( > &KLEND_PROGRAM_ID, &repay_reserve.lending_market, > ); > > let obligation_info = ObligationInfo::from_obligation( > obligation_pubkey, obligation, > ); > > let all_reserve_infos: Vec = parsed_reserves.iter() > .map(|(pk, r)| ReserveInfo::from_reserve(*pk, r)) > .collect(); > > // Refresh reserves and obligation > let mut instructions = Vec::new(); > for info in &all_reserve_infos { > if obligation_info.deposit_reserves.contains(&info.address) > || obligation_info.borrow_reserves.contains(&info.address) > { > instructions.push(refresh::refresh_reserve(info)); > } > } > instructions.push(refresh::refresh_obligation( > &repay_reserve.lending_market, &obligation_info, > )); > > // Remaining accounts: deposit reserves + borrow reserves > let mut remaining: Vec = Vec::new(); > for r in &obligation_info.deposit_reserves { > remaining.push(AccountMeta::new(*r, false)); > } > for r in &obligation_info.borrow_reserves { > remaining.push(AccountMeta::new(*r, false)); > } > > // Calculate slippage protection to guard against sandwich attacks. > // Without this, a malicious validator could reorder transactions > // to extract the full liquidation bonus. > const MIN_RECEIVED_SLIPPAGE_BPS: u16 = 200; // 2% > > let collateral_price: f64 = Fraction::from_bits( > u128::from(withdraw_reserve.liquidity.market_price_sf) > ).to_num(); > let collateral_decimals = withdraw_reserve.liquidity.mint_decimals; > let bonus_bps = withdraw_reserve.config.min_liquidation_bonus_bps as f64; > let protocol_fee_pct = withdraw_reserve.config.protocol_liquidation_fee_pct as f64; > > let debt_price: f64 = Fraction::from_bits( > u128::from(repay_reserve.liquidity.market_price_sf) > ).to_num(); > let repay_usd = repay_amount as f64 > / 10f64.powi(repay_reserve.liquidity.mint_decimals as i32) * debt_price; > > let min_received = if collateral_price > 0.0 { > let collateral_value = repay_usd * (1.0 + bonus_bps / 10_000.0); > let after_fee = collateral_value * (1.0 - protocol_fee_pct / 100.0); > let expected_tokens = after_fee / collateral_price > * 10f64.powi(collateral_decimals as i32); > let with_slippage = expected_tokens > * (10_000.0 - MIN_RECEIVED_SLIPPAGE_BPS as f64) / 10_000.0; > (with_slippage as u64).max(1) > } else { > 1 > }; > > // Liquidation instruction with actual reserve struct addresses > instructions.push(liquidate_obligation_and_redeem_reserve_collateral_v2( > LiquidateObligationAndRedeemReserveCollateralV2Accounts { > liquidator: owner, > obligation: obligation_pubkey, > lending_market: repay_reserve.lending_market, > lending_market_authority: lma, > repay_reserve: repay_reserve_pubkey, > repay_reserve_liquidity_mint: repay_reserve.liquidity.mint_pubkey, > repay_reserve_liquidity_supply: repay_reserve.liquidity.supply_vault, > withdraw_reserve: withdraw_reserve_pubkey, > withdraw_reserve_liquidity_mint: withdraw_reserve.liquidity.mint_pubkey, > withdraw_reserve_collateral_mint: withdraw_reserve.collateral.mint_pubkey, > withdraw_reserve_collateral_supply: withdraw_reserve.collateral.supply_vault, > withdraw_reserve_liquidity_supply: withdraw_reserve.liquidity.supply_vault, > withdraw_reserve_liquidity_fee_receiver: withdraw_reserve.liquidity.fee_vault, > user_source_liquidity, > user_destination_collateral, > user_destination_liquidity, > repay_liquidity_token_program: repay_reserve.liquidity.token_program, > withdraw_liquidity_token_program: withdraw_reserve.liquidity.token_program, > collateral_obligation_farm_user_state: None, > collateral_reserve_farm_state: None, > debt_obligation_farm_user_state: None, > debt_reserve_farm_state: None, > }, > repay_amount, > min_received, > 0, // max_allowed_ltv_override_percent (must be 0 on mainnet) > remaining, > )); > ``` > > > [!WARNING] > > > > The `helpers::liquidate::liquidate()` helper uses `ReservePdas::derive()` which does not match reserves created by older program versions. Use the actual addresses from the `Reserve` struct as shown above. > > **Step 7** > > ### Simulate and Send > > ```rust theme={"theme":"css-variables"} > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let message = Message::new(&instructions, Some(&owner)); > let tx = Transaction::new(&[&signer], message, recent_blockhash); > > // Simulate first > let sim = rpc_client.simulate_transaction(&tx)?; > if let Some(err) = sim.value.err { > println!("Simulation failed: {err}"); > return Ok(()); > } > > // Send with fresh blockhash > let fresh_blockhash = rpc_client.get_latest_blockhash()?; > let fresh_msg = Message::new(&instructions, Some(&owner)); > let fresh_tx = Transaction::new(&[&signer], fresh_msg, fresh_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&fresh_tx)?; > println!("Liquidation executed: {signature}"); > ``` # Mint cTokens Source: https://docs.kamino.com/build/tutorials/borrow/mint-ctokens Mint cTokens by depositing liquidity into Kamino lending reserves > [!NOTE] > > Mint cTokens (collateral tokens) by depositing assets into Kamino lending reserves. cTokens represent your deposit and accrue interest over time, which can be redeemed later for the underlying asset plus earned interest. ## Minting cTokens Deposit reserve liquidity to receive cTokens in your wallet. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Build Deposit Reserve Liquidity Instructions Supply USDC to the reserve and receive its cTokens. ```typescript theme={"theme":"css-variables"} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); const mintAction = await KaminoAction.buildDepositReserveLiquidityTxns({ kaminoMarket: market!, amount: new BN(1_000_000), reserveAddress: usdcReserve.address, owner: signer, obligation: new VanillaObligation(PROGRAM_ID), scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); console.log('cToken mint:', usdcReserve.getCTokenMint()); ``` > [!NOTE] > > This doesn't open a borrow position, so the `obligation` prop is required by the type but unused. `reserve.getCollateralExchangeRate()` returns the current cTokens per token. **Step 4** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(mintAction), tx) ); ``` **Step 5** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('cTokens minted! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > Once the transaction is confirmed, the cTokens are in your wallet. They grow in value as borrowers pay interest, and can be redeemed for USDC plus the interest earned. # Multiply Deposit with KSwap Source: https://docs.kamino.com/build/tutorials/borrow/multiply-deposit-kswap Create leveraged positions using flash loans in a single atomic transaction A multiply deposit creates a leveraged collateral position in a single, atomic transaction by combining an initial deposit with temporary liquidity. When a multiply deposit is initiated, the protocol first temporarily borrows the debt token (for example, USDC) through a flash loan. The borrowed amount is swapped into the collateral token (for example, TSLAx) using KSwap (Kamino's token swap SDK). The resulting collateral is then deposited into Kamino Lend. With the collateral in place, the position borrows the debt token against it, and the borrowed amount is used to repay the flash loan before the transaction completes. The result is a leveraged position with increased exposure to the collateral token and an outstanding debt balance. ## Multiply Deposit with xStocks Create a leveraged position in a single atomic transaction using Klend's multiply feature and KSwap multi-route swap optimization. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, none, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, isTransactionMessageWithinSizeLimit, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, type Instruction, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoMarket, MultiplyObligation, ObligationTypeTag, PROGRAM_ID, getDepositWithLeverageIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, getUserLutAddressAndSetupIxs, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, type SwapInputs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { KswapSdk, loadRouterContext, type RouteOutput } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; import BN from 'bn.js'; import Decimal from 'decimal.js'; ``` > [!NOTE] > > Use `@kamino-finance/kswap-sdk` 2.9.0. It's the last version on `@solana/kit` 2, which `@kamino-finance/klend-sdk` 13 uses; 3.x moved to kit 8. **Step 2** ### Load Configuration and Initialize SDKs ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const DEPOSIT_AMOUNT = new Decimal(10); const TARGET_LEVERAGE = new Decimal(2); const SLIPPAGE_BPS = 50; const MAX_COMPUTE_UNITS = 1_400_000; const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const collReserve = market!.getExistingFloatRateReserveByMint(collMint); const debtReserve = market!.getExistingFloatRateReserveByMint(debtMint); const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); const scope = new Scope('mainnet-beta', rpc); ``` **Step 3** ### Set Up a New Wallet The leverage functions expect the wallet's Kamino user metadata to exist. A wallet that has never used Kamino sends one setup transaction first. ```typescript theme={"theme":"css-variables"} const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions }); const [, userMetadata] = await market!.getUserMetadata(signer.address); if (!userMetadata) { const [, setupInstructions] = await getUserLutAddressAndSetupIxs(market!, signer, none(), false); const { value: setupBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const setupTransaction = await signTransactionMessageWithSigners( pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(setupBlockhash, tx), (tx) => appendTransactionMessageInstructions(setupInstructions.flat(), tx) ) ); await sendAndConfirm(setupTransaction, { commitment: 'confirmed', skipPreflight: true }); } ``` **Step 4** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. It's `null` until the first deposit creates it. ```typescript theme={"theme":"css-variables"} const obligationAddress = await new MultiplyObligation(collMint, debtMint, PROGRAM_ID).toPda(marketPubkey, signer.address); const obligation = await market!.getObligationByAddress(obligationAddress); ``` **Step 5** ### Get Scope Price Refresh Instructions ```typescript theme={"theme":"css-variables"} const scopeRefreshIx = await getScopeRefreshIxForObligationAndReserves( market!, collReserve, debtReserve, obligation ?? undefined, { scope, scopeConfigurations: await scope.getAllConfigurations() } ); ``` **Step 6** ### Define the Swap Helpers The SDK asks for swaps through two callbacks: a quoter that prices the swap and a swapper that returns its instructions. Both use every KSwap route, sorted by output. ```typescript theme={"theme":"css-variables"} async function getRoutes(inputs: SwapInputs) { const { routes } = await kswap.getAllRoutes( { executor: signer.address, tokenIn: inputs.inputMint, tokenOut: inputs.outputMint, amount: new BN(inputs.inputAmountLamports.floor().toString()), maxSlippageBps: SLIPPAGE_BPS, swapType: 'exactIn', wrapAndUnwrapSol: false, }, await loadRouterContext(rpc, inputs.inputMint, inputs.outputMint) ); if (routes.length === 0) { console.log('No KSwap route found for', inputs.inputMint, '->', inputs.outputMint); } return routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); } function midPrice(route: RouteOutput) { const amounts = route.amountsExactIn!; const amountIn = new Decimal(amounts.amountIn.toString()).div(new Decimal(10).pow(route.inputTokenDecimals!)); const amountOut = new Decimal(amounts.amountOut.toString()).div(new Decimal(10).pow(route.outputTokenDecimals!)); return amountOut.div(amountIn); } const quoter = async (inputs: SwapInputs) => { const [bestRoute] = await getRoutes(inputs); return { priceAInB: midPrice(bestRoute), quoteResponse: bestRoute }; }; const swapper = async (inputs: SwapInputs) => (await getRoutes(inputs)).map((route) => { const routeIxs = route.instructions!; return { preActionIxs: [], swapIxs: [ ...routeIxs.createInAtaIxs, ...routeIxs.wrapSolIxs, ...routeIxs.swapIxs, ...routeIxs.unwrapSolIxs, ...routeIxs.createOutAtaIxs, ], lookupTables: route.lookupTableAccounts ?? [], quote: { priceAInB: midPrice(route), quoteResponse: route }, }; }); ``` > [!WARNING] > > `priceAInB` must be the mid price (`amountOut / amountIn`, each in token units), before slippage. The SDK applies `slippagePct` itself, so a guaranteed or minimum-out price counts slippage twice and sizes the position wrong. `getBestRoute` currently returns no routes, so use `getAllRoutes`, which in kswap-sdk 2.9.0 takes the router context as a second argument. **Step 7** ### Build the Leverage Routes The SDK builds one candidate transaction per swap route: flash borrow USDC, swap it to TSLAx, deposit, borrow USDC, repay the flash loan. ```typescript theme={"theme":"css-variables"} const routes = await getDepositWithLeverageIxs({ owner: signer, kaminoMarket: market!, debtReserveAddress: debtReserve.address, collReserveAddress: collReserve.address, depositAmount: DEPOSIT_AMOUNT, priceDebtToColl: debtReserve.getOracleMarketPrice().div(collReserve.getOracleMarketPrice()), slippagePct: new Decimal(SLIPPAGE_BPS / 100), obligation, referrer: none(), currentLedgerInstant: await getCurrentLedgerInstant(rpc), targetLeverage: TARGET_LEVERAGE, selectedTokenMint: debtMint, obligationTypeTagOverride: ObligationTypeTag.Multiply, scopeRefreshIx, budgetAndPriorityFeeIxs: getComputeBudgetAndPriorityFeeIxs(MAX_COMPUTE_UNITS), quoteBufferBps: new Decimal(0), quoter, swapper, useV2Ixs: true, }); ``` > [!NOTE] > > `selectedTokenMint` is the token you deposit: the debt token (USDC) here, or the collateral token. `quoteBufferBps` inflates only the amount used for the quote; 0 quotes the exact swap amount and leaves price moves to the slippage setting. **Step 8** ### Fetch Lookup Tables Fetch Kamino's lookup tables for each candidate transaction, one request per candidate. ```typescript theme={"theme":"css-variables"} async function getKaminoLookupTables(instructions: Instruction[]) { const addresses = [ ...new Set(instructions.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), ]; const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addresses }), }); if (!lutResponse.ok) { console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); } const { lutAddresses } = await lutResponse.json(); return fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); } ``` > [!NOTE] > > `/luts/find-minimal` takes one transaction's worth of addresses (between 64 and 128), so a single request for all candidates is rejected. **Step 9** ### Pick the Route That Fits Compress each candidate with its route's lookup tables and Kamino's, then take the best-output one that fits in a transaction. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const candidates = await Promise.all( routes.map(async (route) => { const lookupTables = [...route.lookupTables, ...(await getKaminoLookupTables(route.ixs))]; const lookupTableAddresses: Record = Object.fromEntries( lookupTables.map((lut) => [lut.address, lut.data.addresses]) ); return pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(route.ixs, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) ); }) ); const transactionMessage = candidates.find((candidate) => isTransactionMessageWithinSizeLimit(candidate)); if (!transactionMessage) { console.log(`None of the ${candidates.length} swap routes fit in one transaction`); } ``` > [!NOTE] > > The best-output route often has too many accounts to fit, even compressed: in testing only one or two of five to ten routes did. The slippage setting covers the gap between the best route's quote and the one sent. **Step 10** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage!); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Multiply deposit successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The 2x TSLAx position is open: TSLAx collateral with a USDC debt, created in one transaction. ## Transaction Flow > [accordion] View Transaction Flow Diagram > > ```mermaid theme={"theme":"css-variables"} > graph TD > A[Load Market & SDKs] --> B[Set Up New Wallet] > B --> C[Load Multiply Obligation] > C --> D[Refresh Scope Prices] > D --> E[Build One Candidate per Swap Route] > E --> F[Compress with Lookup Tables] > F --> G[Pick Best Route That Fits] > G --> J[Sign & Send Transaction] > > J --> K{Transaction Success?} > K -->|Yes| L[Leveraged Position Created] > K -->|No| M[Transaction Reverts] > ``` ## Asset Flow > [accordion] 2x Leveraged TSLAx Position: Step-by-Step > > **1. Initial State** > > * Wallet: 10 USDC > * Position: None > > **2. Flash Borrow** > > * Flash loan: 10 USDC (temporary) > * Available: 20 USDC total > > **3. Swap & Deposit** > > * Swap 20 USDC to TSLAx via KSwap > * Deposit TSLAx as collateral > > **4. Borrow & Repay** > > * Borrow 10 USDC against collateral > * Repay 10 USDC flash loan > > **5. Final Position** > > * Collateral: TSLAx (\$20 value) > * Debt: 10 USDC > * Net Equity: 10 USDC > * Leverage: 2x ## Key Concepts > [accordion] Flash Loans > > Flash loans are uncollateralized loans that must be borrowed and repaid within the same transaction. They enable: > > * **Zero upfront capital**: Borrow large amounts without collateral > * **Atomic execution**: All operations succeed or fail together > * **Leverage creation**: Bootstrap leveraged positions in one transaction > * **Risk-free**: Transaction reverts if flash loan cannot be repaid > [accordion] Multiply Obligation Type > > The `MultiplyObligation` is a specialized obligation type that: > > * **Defines position type**: Multiply vs Leverage vs Vanilla > * **Derives unique address**: Via PDA using collateral/debt mints > * **Supports multiple positions**: Create different obligations with same tokens using ID parameter > * **Creates new obligation**: When none exists (indicated by `obligation: null`) > [accordion] KSwap Multi-Route Optimization > > KSwap provides optimal swap execution through: > > * **Multi-DEX routing**: Tests routes across Jupiter, OKX, dFlow, and other DEX aggregators > * **Route choice**: Sorted by output; the best-output route that fits in one transaction is sent > * **Slippage protection**: Each route enforces a minimum output within the slippage setting > * **Automatic ATA creation**: Handles token account creation and SOL wrapping/unwrapping ### Borrow and Multiply SDK Methods | Method | Operation | When to Use | | - | - | - | | `getDepositWithLeverageIxs` | Open position or add collateral | Creating or adding to a leveraged position | | `buildRepayTxns` | Repay with wallet funds | Reducing debt using USDC, SOL, etc. from wallet | | `buildWithdrawTxns` | Withdraw collateral | Withdrawing collateral after debt is repaid | | `getWithdrawWithLeverageIxs` | Shrink the position and withdraw | Take value out while keeping the position's LTV; leverage stays the same | | `getRepayWithCollIxs` | Repay debt with collateral | Sell collateral to repay debt without withdrawing (value stays in position) | > [!NOTE] > > **Multiply operations** use `MultiplyObligation`. **Vanilla operations** use `VanillaObligation`. The obligation type determines which PDA is derived for your position. ## Related Resources > [card] [Deposit and Borrow](/build/tutorials/borrow/deposit-and-borrow) > > Learn basic deposit and borrow operations > [card] [Market Data](/build/developers/borrow/data/market-data) > > Read market metrics and reserve data > [card] [KSwap SDK](https://www.npmjs.com/package/@kamino-finance/kswap-sdk) > > Multi-DEX swap routing SDK > [card] [Scope SDK](https://github.com/Kamino-Finance/scope-sdk) > > Oracle price aggregation SDK # Redeem cTokens Source: https://docs.kamino.com/build/tutorials/borrow/redeem-ctokens Redeem cTokens to receive the underlying asset plus earned interest > [!NOTE] > > Redeem cTokens (collateral tokens) to receive the underlying asset plus any accrued interest. This process burns your cTokens and returns the deposited assets along with earned yield. ## Redeeming cTokens Burn cTokens to withdraw your deposit and interest from Kamino lending reserves. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getAssociatedTokenAddress, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Get the Wallet's cToken Balance The redeem amount is in cTokens, not USDC. Read the wallet's cToken balance to redeem all of it. ```typescript theme={"theme":"css-variables"} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); const cTokenAccount = await getAssociatedTokenAddress(usdcReserve.getCTokenMint(), signer.address); const { value: cTokenBalance } = await rpc.getTokenAccountBalance(cTokenAccount).send(); console.log('cTokens to redeem:', cTokenBalance.uiAmountString); ``` **Step 4** ### Build Redeem Reserve Collateral Instructions Redeem the cTokens for USDC. ```typescript theme={"theme":"css-variables"} const redeemAction = await KaminoAction.buildRedeemReserveCollateralTxns({ kaminoMarket: market!, amount: new BN(cTokenBalance.amount), reserveAddress: usdcReserve.address, owner: signer, obligation: new VanillaObligation(PROGRAM_ID), scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(redeemAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('cTokens redeemed! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > Once the transaction is confirmed, the cTokens are burned and the USDC, including the interest earned, is in your wallet. # Refer User Without Deposit Source: https://docs.kamino.com/build/tutorials/borrow/refer-user-without-deposit Create UserMetadata with a referrer without requiring an initial deposit This tutorial shows you how to link a referrer to a user by creating UserMetadata without requiring an initial deposit. ## Refer User Without Deposit Create a UserMetadata account with a referrer without requiring an initial deposit. This allows you to link a referrer to a user before they perform any lending operations. > [!NOTE] > > The referrer must be set when the UserMetadata account is created and cannot be changed afterward. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > some, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > getUserLutAddressAndSetupIxs, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **Step 2** > > ### Initialize RPC and Load Market > > ```typescript theme={"theme":"css-variables"} > 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 REFERRER = address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY'); > > const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Check Existing User Metadata > > ```typescript theme={"theme":"css-variables"} > const [, userMetadata] = await market!.getUserMetadata(signer.address); > > if (userMetadata) { > console.log('User metadata already exists, so the referrer can no longer be set:', signer.address); > } > ``` > > **Step 4** > > ### Build User Metadata Setup Instructions > > ```typescript theme={"theme":"css-variables"} > const [, setupInstructions] = await getUserLutAddressAndSetupIxs(market!, signer, some(REFERRER), false); > ``` > > > [!NOTE] > > > > The referrer's wallet must have Kamino user metadata itself. The instructions also create the wallet's lookup table; `false` skips filling it. For a wallet that already has user metadata, the SDK returns no instructions. > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(setupInstructions.flat(), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Referrer linked! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > User metadata created. The referrer is now linked to the wallet and earns a share of the interest it pays on borrows. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Derive PDAs and Build Instruction > > Create the `init_user_metadata` instruction linking the user to a referrer without requiring a deposit. > > ```rust theme={"theme":"css-variables"} > use klend_interface::instructions::referrer::{ > init_user_metadata, > InitUserMetadataAccounts, > }; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > > let referrer = Pubkey::from_str("EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY").unwrap(); > > // Derive PDAs > let (user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &owner); > let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer); > > // Your user's address lookup table (created during onboarding) > let user_lookup_table = Pubkey::from_str("YOUR_USER_LOOKUP_TABLE_PUBKEY").unwrap(); > > let ix = init_user_metadata( > InitUserMetadataAccounts { > owner, > fee_payer: owner, > user_metadata, > referrer_user_metadata: Some(referrer_user_metadata), > }, > user_lookup_table, > ); > ``` > > > [!WARNING] > > > > Once UserMetadata is created with a referrer, the referrer cannot be changed. Always check if UserMetadata exists before attempting to create it. > > **Step 4** > > ### Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&[ix], Some(&owner)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("UserMetadata created with referrer! Signature: {signature}"); > ``` > [accordion] When to Use This vs Deposit with Referral > > **Use this method when:** > > * You want to link a referrer to a user before they make their first deposit > * You're creating UserMetadata as a separate step from deposit operations > * You have a simpler flow that doesn't require immediate deposit > > **Use Deposit with Referral when:** > > * You want to combine UserMetadata creation and deposit in a single transaction > * The user is ready to deposit immediately > * You want to minimize the number of transactions # Referral Code Setup Source: https://docs.kamino.com/build/tutorials/borrow/referrer-setup Set up referrer state with a unique referral code This tutorial shows you how to set up your own referral code that you can share with users to earn commission from their borrowing activity. ## How Referral Codes Work Kamino's referral system allows referrers to earn commission from the borrowing activity of referred users. Each referrer creates a unique referral code that can be shared publicly without revealing a wallet address, providing a user-friendly way to distribute referral codes. \[!NOTE] In the SDK, the `shortUrl` field represents the referral code. > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > PROGRAM_ID, > getInitReferrerStateAndShortUrlIxs, > getReferrerForShortUrl, > isShortUrlAvailable, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **Step 2** > > ### Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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'); > ``` > > **Step 3** > > ### Create Referrer State with Short URL > > Check the referral code is free, then create the referrer state and short URL. > > ```typescript theme={"theme":"css-variables"} > const shortUrl = 'your-referral-code'; > > if (!(await isShortUrlAvailable(rpc, shortUrl, PROGRAM_ID))) { > console.log('Referral code is invalid or already taken:', shortUrl); > } > > const initReferrerIx = await getInitReferrerStateAndShortUrlIxs({ > referrer: signer, > shortUrl, > programId: PROGRAM_ID, > }); > ``` > > > [!NOTE] > > > > The short URL must be unique, at most 32 characters, and use only ASCII letters, digits, underscore and hyphen. `isShortUrlAvailable` checks both. Each wallet gets one code. > > **Step 4** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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([initReferrerIx], tx) > ); > ``` > > **Step 5** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Referrer registered! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > **Step 6** > > ### Verify Short URL Resolution > > ```typescript theme={"theme":"css-variables"} > const referrer = await getReferrerForShortUrl(rpc, shortUrl, PROGRAM_ID); > console.log(`Code ${shortUrl} resolves to:`, referrer); > ``` > > > [!TIP] > > > > Referrer setup complete. The short URL is active and can be shared with users to establish referral relationships. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Derive PDAs and Build Instruction > > ```rust theme={"theme":"css-variables"} > use klend_interface::instructions::referrer::{ > init_referrer_state_and_short_url, > InitReferrerStateAndShortUrlAccounts, > }; > use klend_interface::pda; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > > let referrer = signer.pubkey(); > let short_url = format!("ref-{}", std::time::SystemTime::now() > .duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()); > > // Derive required PDAs > let (referrer_state, _) = pda::referrer_state(&KLEND_PROGRAM_ID, &referrer); > let (referrer_short_url, _) = pda::short_url(&KLEND_PROGRAM_ID, &short_url); > let (referrer_user_metadata, _) = pda::user_metadata(&KLEND_PROGRAM_ID, &referrer); > > let ix = init_referrer_state_and_short_url( > InitReferrerStateAndShortUrlAccounts { > referrer, > referrer_state, > referrer_short_url, > referrer_user_metadata, > }, > short_url.clone(), > ); > ``` > > > [!NOTE] > > > > The short URL must be unique, contain a maximum of 32 characters, and use only ASCII alphanumeric characters plus underscore and hyphen. > > **Step 4** > > ### Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&[ix], Some(&referrer)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Referrer setup successful! Short URL: {short_url}"); > println!("Signature: {signature}"); > ``` # Repay and Withdraw Source: https://docs.kamino.com/build/tutorials/borrow/repay-and-withdraw Repay borrowed assets and withdraw your collateral ## Repay Debt Repay borrowed assets to improve your position health. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Load the Obligation Load the wallet's borrow position so the SDK refreshes every reserve it uses. ```typescript theme={"theme":"css-variables"} const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!obligation) { console.log('No borrow position found for', signer.address); } ``` **Step 4** ### Build Repay Instructions Repay part of the USDT loan from the USDT in the wallet. ```typescript theme={"theme":"css-variables"} const usdtMint = address('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'); const usdtReserve = market!.getExistingFloatRateReserveByMint(usdtMint); const repayAction = await KaminoAction.buildRepayTxns({ kaminoMarket: market!, amount: new BN(1_000_000), reserveAddress: usdtReserve.address, owner: signer, obligation: obligation!, useV2Ixs: true, scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!TIP] > > To repay the whole loan including accrued interest, pass `new BN(U64_MAX)` as the amount (`U64_MAX` is exported by the SDK). The program repays the exact debt, so no dust is left. **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(repayAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Repay successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The debt in the borrow position is reduced. ## Withdraw Collateral Withdraw collateral from your obligation. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, } from '@solana/kit'; import { KaminoMarket, KaminoAction, VanillaObligation, PROGRAM_ID, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import BN from 'bn.js'; ``` **Step 2** ### Load Market and Initialize RPC ```typescript theme={"theme":"css-variables"} 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, await getMedianSlotDurationInMsFromLastEpochs()); ``` **Step 3** ### Load the Obligation Load the wallet's borrow position so the SDK refreshes every reserve it uses. ```typescript theme={"theme":"css-variables"} const obligation = await market!.getObligationByWallet(signer.address, new VanillaObligation(PROGRAM_ID)); if (!obligation) { console.log('No borrow position found for', signer.address); } ``` **Step 4** ### Build Withdraw Instructions Withdraw USDC collateral from the borrow position. ```typescript theme={"theme":"css-variables"} const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); const withdrawAction = await KaminoAction.buildWithdrawTxns({ kaminoMarket: market!, amount: new BN(1_000_000), reserveAddress: usdcReserve.address, owner: signer, obligation: obligation!, useV2Ixs: true, scopeRefreshConfig: undefined, currentLedgerInstant: await getCurrentLedgerInstant(rpc), }); ``` > [!TIP] > > With open borrows, the withdrawal must keep the position under its borrow limit. To withdraw all of a deposit, pass `new BN(U64_MAX)` as the amount. **Step 5** ### Build the Transaction ```typescript theme={"theme":"css-variables"} 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(KaminoAction.actionToIxs(withdrawAction), tx) ); ``` **Step 6** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Withdraw successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The collateral is back in the wallet. # Repay with Collateral using KSwap Source: https://docs.kamino.com/build/tutorials/borrow/repay-with-collateral-kswap Reduce debt by converting collateral using flash loans in a single atomic transaction Repay with collateral reduces debt in a single atomic transaction by converting collateral into the debt token without requiring additional funds. The protocol flash borrows the debt token, repays the debt, withdraws the freed collateral, swaps it to the debt token via KSwap, and repays the flash loan, all in one transaction. ## Repay with Collateral using KSwap Reduce debt in a single transaction by converting collateral using a flash loan and KSwap. **Step 1** ### Import Dependencies ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, none, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, isTransactionMessageWithinSizeLimit, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, type Instruction, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoMarket, MultiplyObligation, PROGRAM_ID, getRepayWithCollIxs, getScopeRefreshIxForObligationAndReserves, getComputeBudgetAndPriorityFeeIxs, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, type SwapInputs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { KswapSdk, loadRouterContext, type RouteOutput } from '@kamino-finance/kswap-sdk'; import { Scope } from '@kamino-finance/scope-sdk'; import BN from 'bn.js'; import Decimal from 'decimal.js'; ``` > [!NOTE] > > Use `@kamino-finance/kswap-sdk` 2.9.0. It's the last version on `@solana/kit` 2, which `@kamino-finance/klend-sdk` 13 uses; 3.x moved to kit 8. **Step 2** ### Load Configuration and Initialize SDKs ```typescript theme={"theme":"css-variables"} 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('5wJeMrUYECGq41fxRESKALVcHnNX26TAWy4W98yULsua'); // xStocks Market const collMint = address('XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB'); // TSLAx const debtMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC const REPAY_AMOUNT = new Decimal(5); const SLIPPAGE_BPS = 50; const MAX_COMPUTE_UNITS = 1_400_000; const market = await KaminoMarket.load(rpc, marketPubkey, await getMedianSlotDurationInMsFromLastEpochs()); const collReserve = market!.getExistingFloatRateReserveByMint(collMint); const debtReserve = market!.getExistingFloatRateReserveByMint(debtMint); const kswap = new KswapSdk('https://api.kamino.finance/kswap', rpc, rpcSubscriptions); const scope = new Scope('mainnet-beta', rpc); ``` **Step 3** ### Load the Multiply Obligation A Multiply position is its own obligation, addressed by the collateral and debt mints. ```typescript theme={"theme":"css-variables"} const obligationAddress = await new MultiplyObligation(collMint, debtMint, PROGRAM_ID).toPda(marketPubkey, signer.address); const obligation = await market!.getObligationByAddress(obligationAddress); if (!obligation) { console.log('No Multiply position found for', signer.address); } ``` **Step 4** ### Get Scope Price Refresh Instructions ```typescript theme={"theme":"css-variables"} const scopeRefreshIx = await getScopeRefreshIxForObligationAndReserves( market!, collReserve, debtReserve, obligation!, { scope, scopeConfigurations: await scope.getAllConfigurations() } ); ``` **Step 5** ### Define the Swap Helpers The SDK asks for swaps through two callbacks: a quoter that prices the swap and a swapper that returns its instructions. Both use every KSwap route, sorted by output. ```typescript theme={"theme":"css-variables"} async function getRoutes(inputs: SwapInputs) { const { routes } = await kswap.getAllRoutes( { executor: signer.address, tokenIn: inputs.inputMint, tokenOut: inputs.outputMint, amount: new BN(inputs.inputAmountLamports.floor().toString()), maxSlippageBps: SLIPPAGE_BPS, swapType: 'exactIn', wrapAndUnwrapSol: false, }, await loadRouterContext(rpc, inputs.inputMint, inputs.outputMint) ); if (routes.length === 0) { console.log('No KSwap route found for', inputs.inputMint, '->', inputs.outputMint); } return routes.sort((a, b) => b.amountsExactIn!.amountOut.cmp(a.amountsExactIn!.amountOut)); } function midPrice(route: RouteOutput) { const amounts = route.amountsExactIn!; const amountIn = new Decimal(amounts.amountIn.toString()).div(new Decimal(10).pow(route.inputTokenDecimals!)); const amountOut = new Decimal(amounts.amountOut.toString()).div(new Decimal(10).pow(route.outputTokenDecimals!)); return amountOut.div(amountIn); } const quoter = async (inputs: SwapInputs) => { const [bestRoute] = await getRoutes(inputs); return { priceAInB: midPrice(bestRoute), quoteResponse: bestRoute }; }; const swapper = async (inputs: SwapInputs) => (await getRoutes(inputs)).map((route) => { const routeIxs = route.instructions!; return { preActionIxs: [], swapIxs: [ ...routeIxs.createInAtaIxs, ...routeIxs.wrapSolIxs, ...routeIxs.swapIxs, ...routeIxs.unwrapSolIxs, ...routeIxs.createOutAtaIxs, ], lookupTables: route.lookupTableAccounts ?? [], quote: { priceAInB: midPrice(route), quoteResponse: route }, }; }); ``` > [!WARNING] > > `priceAInB` must be the mid price (`amountOut / amountIn`, each in token units), before slippage. The SDK applies `slippagePct` itself, so a guaranteed or minimum-out price counts slippage twice and sizes the position wrong. `getBestRoute` currently returns no routes, so use `getAllRoutes`, which in kswap-sdk 2.9.0 takes the router context as a second argument. **Step 6** ### Build the Repay Routes The SDK builds one candidate transaction per swap route: flash borrow, repay the debt, withdraw TSLAx, swap it to USDC, repay the flash loan. ```typescript theme={"theme":"css-variables"} const routes = await getRepayWithCollIxs({ owner: signer, kaminoMarket: market!, debtReserveAddress: debtReserve.address, collReserveAddress: collReserve.address, obligation: obligation!, referrer: none(), currentLedgerInstant: await getCurrentLedgerInstant(rpc), repayAmount: REPAY_AMOUNT, isClosingPosition: false, slippagePct: new Decimal(SLIPPAGE_BPS / 100), scopeRefreshIx, budgetAndPriorityFeeIxs: getComputeBudgetAndPriorityFeeIxs(MAX_COMPUTE_UNITS), quoter, swapper, useV2Ixs: true, }); ``` > [!NOTE] > > `slippagePct` also sizes the flash loan, so the worst-case swap fill still covers the repay. To repay all the debt and close the position, set `isClosingPosition` to `true`. **Step 7** ### Fetch Lookup Tables Fetch Kamino's lookup tables for each candidate transaction, one request per candidate. ```typescript theme={"theme":"css-variables"} async function getKaminoLookupTables(instructions: Instruction[]) { const addresses = [ ...new Set(instructions.flatMap((ix) => [ix.programAddress, ...(ix.accounts ?? []).map((account) => account.address)])), ]; const lutResponse = await fetch('https://api.kamino.finance/luts/find-minimal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ addresses }), }); if (!lutResponse.ok) { console.log(`Lookup table request failed: ${lutResponse.status} ${lutResponse.statusText}`); } const { lutAddresses } = await lutResponse.json(); return fetchAllAddressLookupTable(rpc, lutAddresses.map((lut: string) => address(lut))); } ``` > [!NOTE] > > `/luts/find-minimal` takes one transaction's worth of addresses (between 64 and 128), so a single request for all candidates is rejected. **Step 8** ### Pick the Route That Fits Compress each candidate with its route's lookup tables and Kamino's, then take the best-output one that fits in a transaction. ```typescript theme={"theme":"css-variables"} const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const candidates = await Promise.all( routes.map(async (route) => { const lookupTables = [...route.lookupTables, ...(await getKaminoLookupTables(route.ixs))]; const lookupTableAddresses: Record = Object.fromEntries( lookupTables.map((lut) => [lut.address, lut.data.addresses]) ); return pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(signer, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(route.ixs, tx), (tx) => compressTransactionMessageUsingAddressLookupTables(tx, lookupTableAddresses) ); }) ); const transactionMessage = candidates.find((candidate) => isTransactionMessageWithinSizeLimit(candidate)); if (!transactionMessage) { console.log(`None of the ${candidates.length} swap routes fit in one transaction`); } ``` > [!NOTE] > > The best-output route often has too many accounts to fit, even compressed: in testing only one or two of five to ten routes did. The slippage setting covers the gap between the best route's quote and the one sent. **Step 9** ### Sign and Send ```typescript theme={"theme":"css-variables"} const signedTransaction = await signTransactionMessageWithSigners(transactionMessage!); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Repay with collateral successful! Signature:', getSignatureFromTransaction(signedTransaction)); ``` > [!TIP] > > The debt is reduced by selling TSLAx collateral, with no USDC needed in the wallet. # Deposit and Borrow Source: https://docs.kamino.com/build/tutorials/borrow/rust/deposit-and-borrow Deposit collateral and borrow assets using the klend-interface Rust crate ## Deposit Collateral Deposit assets as collateral to enable borrowing. **Step 1** ### Add Dependencies ```toml theme={"theme":"css-variables"} [dependencies] klend-interface = "0.6.0" solana-pubkey = "2.1" solana-instruction = "2.1" solana-sdk = "~2.3" solana-client = "~2.3" spl-token = "7" spl-associated-token-account = "6" ``` > [!NOTE] > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. **Step 2** ### Set Up RPC Client ```rust theme={"theme":"css-variables"} use solana_client::rpc_client::RpcClient; use solana_sdk::signer::keypair::read_keypair_file; use solana_sdk::signer::Signer; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let signer = read_keypair_file("/path/to/your/keypair.json") .expect("Failed to read keypair file"); let owner = signer.pubkey(); ``` **Step 3** ### Build Obligation Context Derive the obligation PDA, fetch its account data along with all associated reserves, and build an `ObligationContext`. ```rust theme={"theme":"css-variables"} use klend_interface::ObligationContext; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; use std::str::FromStr; let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); // Derive the obligation PDA let (obligation_pubkey, _) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, &Pubkey::default(), &Pubkey::default(), ); // Fetch the obligation account let obligation_data = rpc_client.get_account(&obligation_pubkey)?; // Discover which reserves the obligation references let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; // Fetch all reserve accounts in one RPC call let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; // Build the context let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() .zip(reserve_accounts.iter()) .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) .collect(); let ctx = ObligationContext::from_account_data( obligation_pubkey, &obligation_data.data, &reserves )?; ``` > [!NOTE] > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. **Step 4** ### Derive Token Accounts ```rust theme={"theme":"css-variables"} use spl_associated_token_account::get_associated_token_address; // User's ATA for the deposit token (e.g. USDC) let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); let user_source_liquidity = get_associated_token_address(&owner, &liquidity_mint); ``` **Step 5** ### Build Instructions ```rust theme={"theme":"css-variables"} let instructions = ctx.deposit( owner, &reserve_pubkey, user_source_liquidity, 3_000_000, // 3 USDC (6 decimals) )?; // Returns: [refresh_reserves..., refresh_obligation, deposit_and_collateral_v2] ``` **Step 6** ### Build and Send Transaction ```rust theme={"theme":"css-variables"} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&instructions, Some(&owner)); let recent_blockhash = rpc_client.get_latest_blockhash()?; let tx = Transaction::new(&[&signer], message, recent_blockhash); let signature = rpc_client.send_and_confirm_transaction(&tx)?; println!("Deposit successful! Signature: {signature}"); ``` > [!TIP] > > The deposit is complete. Your collateral has been supplied and your borrow position is open. # Repay and Withdraw Source: https://docs.kamino.com/build/tutorials/borrow/rust/repay-and-withdraw Repay borrowed assets and withdraw collateral using the klend-interface Rust crate ## Repay Debt Repay borrowed assets to improve your position health. **Step 1** ### Add Dependencies ```toml theme={"theme":"css-variables"} [dependencies] klend-interface = "0.6.0" solana-pubkey = "2.1" solana-instruction = "2.1" solana-sdk = "~2.3" solana-client = "~2.3" spl-token = "7" spl-associated-token-account = "6" ``` > [!NOTE] > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. **Step 2** ### Set Up RPC Client ```rust theme={"theme":"css-variables"} use solana_client::rpc_client::RpcClient; use solana_sdk::signer::keypair::read_keypair_file; use solana_sdk::signer::Signer; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let signer = read_keypair_file("/path/to/your/keypair.json") .expect("Failed to read keypair file"); let owner = signer.pubkey(); ``` **Step 3** ### Build Obligation Context ```rust theme={"theme":"css-variables"} use klend_interface::ObligationContext; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; use std::str::FromStr; let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let repay_reserve_pubkey = Pubkey::from_str("FBSyPnxtHKLBZ4UeeUyAnbtFuAmTHLtso9YtsqRDRWpM").unwrap(); // Derive the obligation PDA let (obligation_pubkey, _) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, &Pubkey::default(), &Pubkey::default(), ); // Fetch the obligation account let obligation_data = rpc_client.get_account(&obligation_pubkey)?; // Discover which reserves the obligation references let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; // Fetch all reserve accounts in one RPC call let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; // Build the context let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() .zip(reserve_accounts.iter()) .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) .collect(); let ctx = ObligationContext::from_account_data( obligation_pubkey, &obligation_data.data, &reserves )?; ``` > [!NOTE] > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. **Step 4** ### Derive Token Accounts ```rust theme={"theme":"css-variables"} use spl_associated_token_account::get_associated_token_address; // User's ATA for the repay token (e.g. USDT) let repay_liquidity_mint = Pubkey::from_str("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB").unwrap(); let user_source_liquidity = get_associated_token_address(&owner, &repay_liquidity_mint); ``` **Step 5** ### Build Instructions ```rust theme={"theme":"css-variables"} let instructions = ctx.repay( owner, &repay_reserve_pubkey, user_source_liquidity, 1_000_000, // 1 USDT (6 decimals) )?; // Returns: [refresh_reserves..., refresh_obligation, repay_obligation_liquidity_v2] ``` **Step 6** ### Build and Send Transaction ```rust theme={"theme":"css-variables"} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&instructions, Some(&owner)); let recent_blockhash = rpc_client.get_latest_blockhash()?; let tx = Transaction::new(&[&signer], message, recent_blockhash); let signature = rpc_client.send_and_confirm_transaction(&tx)?; println!("Repay successful! Signature: {signature}"); ``` > [!NOTE] > > Repaying reduces your debt and improves your loan-to-value (LTV) ratio, making your position healthier and reducing liquidation risk. > [!TIP] > > The repay is complete. Your debt has been reduced. ## Withdraw **Step 1** ### Add Dependencies ```toml theme={"theme":"css-variables"} [dependencies] klend-interface = "0.6.0" solana-pubkey = "2.1" solana-instruction = "2.1" solana-sdk = "~2.3" solana-client = "~2.3" spl-token = "7" spl-associated-token-account = "6" ``` > [!NOTE] > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. **Step 2** ### Set Up RPC Client ```rust theme={"theme":"css-variables"} use solana_client::rpc_client::RpcClient; use solana_sdk::signer::keypair::read_keypair_file; use solana_sdk::signer::Signer; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let signer = read_keypair_file("/path/to/your/keypair.json") .expect("Failed to read keypair file"); let owner = signer.pubkey(); ``` **Step 3** ### Build Obligation Context ```rust theme={"theme":"css-variables"} use klend_interface::ObligationContext; use klend_interface::pda; use klend_interface::KLEND_PROGRAM_ID; use solana_pubkey::Pubkey; use std::str::FromStr; let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); // Derive the obligation PDA let (obligation_pubkey, _) = pda::obligation( &KLEND_PROGRAM_ID, 0, 0, &owner, &lending_market, &Pubkey::default(), &Pubkey::default(), ); // Fetch the obligation account let obligation_data = rpc_client.get_account(&obligation_pubkey)?; // Discover which reserves the obligation references let reserve_addrs = ObligationContext::reserve_addresses_for_obligation(&obligation_data.data)?; // Fetch all reserve accounts in one RPC call let reserve_accounts = rpc_client.get_multiple_accounts(&reserve_addrs)?; // Build the context let reserves: Vec<(Pubkey, &[u8])> = reserve_addrs.iter() .zip(reserve_accounts.iter()) .filter_map(|(addr, acc)| acc.as_ref().map(|a| (*addr, a.data.as_slice()))) .collect(); let ctx = ObligationContext::from_account_data( obligation_pubkey, &obligation_data.data, &reserves )?; ``` > [!NOTE] > > `ObligationContext` is the recommended approach for obligation-based operations. It fetches the obligation and its associated reserves, then provides convenient `.deposit()`, `.borrow()`, `.repay()`, and `.withdraw()` methods. **Step 4** ### Derive Token Accounts ```rust theme={"theme":"css-variables"} use spl_associated_token_account::get_associated_token_address; // User's ATA for the withdrawal token (e.g. USDC) let liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); let user_dest_liquidity = get_associated_token_address(&owner, &liquidity_mint); ``` **Step 5** ### Build Instructions ```rust theme={"theme":"css-variables"} let instructions = ctx.withdraw( owner, &reserve_pubkey, user_dest_liquidity, 1_000_000, // 1 USDC (6 decimals) )?; // Returns: [refresh_reserves..., refresh_obligation, withdraw_and_redeem] ``` > [!NOTE] > > Use `helpers::withdraw::redeem()` if you hold cTokens without an obligation — see the [Withdraw for Lending](/build/developers/borrow/operations/withdraw#withdraw-for-lending) tab. **Step 6** ### Build and Send Transaction ```rust theme={"theme":"css-variables"} use solana_sdk::transaction::Transaction; use solana_sdk::message::Message; let message = Message::new(&instructions, Some(&owner)); let recent_blockhash = rpc_client.get_latest_blockhash()?; let tx = Transaction::new(&[&signer], message, recent_blockhash); let signature = rpc_client.send_and_confirm_transaction(&tx)?; println!("Withdrawal successful! Signature: {signature}"); ``` > [!TIP] > > The withdrawal is complete. Your collateral has been returned to your wallet. # Withdraw Referrer Fees Source: https://docs.kamino.com/build/tutorials/borrow/withdraw-referrer-fees Withdraw accumulated referral fees from borrowing activity Follow this guide to withdraw the referral fees you've earned from referred users' borrowing activity. ## Withdraw Referrer Fees > [tab] TypeScript > > **Step 1** > > ### Import Dependencies > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > assertIsTransactionWithinSizeLimit, > sendAndConfirmTransactionFactory, > getSignatureFromTransaction, > } from '@solana/kit'; > import { > KaminoMarket, > KaminoAction, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **Step 2** > > ### Load Market and Initialize RPC > > ```typescript theme={"theme":"css-variables"} > 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, await getMedianSlotDurationInMsFromLastEpochs()); > ``` > > **Step 3** > > ### Check Accumulated Fees > > Fees accrue per reserve, in that reserve's token. Amounts are in lamports, so divide by the reserve's mint factor. > > ```typescript theme={"theme":"css-variables"} > const allFees = await market!.getAllReferrerFeesCumulative(signer.address); > > console.table( > [...allFees.entries()].map(([reserveAddress, fees]) => { > const reserve = market!.getReserveByAddress(reserveAddress); > return { > symbol: reserve?.getTokenSymbol(), > lifetimeFees: reserve ? fees.div(reserve.getMintFactor()).toFixed(6) : fees.toFixed(0), > }; > }) > ); > > const usdcMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); > const usdcReserve = market!.getExistingFloatRateReserveByMint(usdcMint); > const unclaimedFees = await market!.getReferrerFeesUnclaimedForReserve(signer.address, usdcReserve); > > console.log('Unclaimed USDC fees:', unclaimedFees.div(usdcReserve.getMintFactor()).toFixed(6)); > if (unclaimedFees.isZero()) { > console.log('No USDC referrer fees to withdraw for', signer.address); > } > ``` > > **Step 4** > > ### Build Withdraw Instructions > > Withdraw the unclaimed USDC fees to the wallet. > > ```typescript theme={"theme":"css-variables"} > const withdrawFeesAction = await KaminoAction.buildWithdrawReferrerFeeTxns({ > owner: signer, > reserveAddress: usdcReserve.address, > kaminoMarket: market!, > currentLedgerInstant: await getCurrentLedgerInstant(rpc), > }); > ``` > > > [!NOTE] > > > > A wallet that has never earned fees in the reserve has no referrer token state for it, and the withdrawal fails with `AccountOwnedByWrongProgram` (3007). > > **Step 5** > > ### Build the Transaction > > ```typescript theme={"theme":"css-variables"} > 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(KaminoAction.actionToIxs(withdrawFeesAction), tx) > ); > ``` > > **Step 6** > > ### Sign and Send > > ```typescript theme={"theme":"css-variables"} > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > assertIsTransactionWithinSizeLimit(signedTransaction); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > skipPreflight: true, > }); > > console.log('Referrer fees withdrawn! Signature:', getSignatureFromTransaction(signedTransaction)); > ``` > > > [!TIP] > > > > Fee withdrawal complete. The accumulated referral fees have been transferred to the referrer wallet. > [tab] Rust > > **Step 1** > > ### Add Dependencies > > ```toml theme={"theme":"css-variables"} > [dependencies] > klend-interface = "0.6.0" > solana-pubkey = "2.1" > solana-instruction = "2.1" > solana-sdk = "~2.3" > solana-client = "~2.3" > spl-token = "7" > spl-associated-token-account = "6" > ``` > > > [!NOTE] > > > > `klend-interface` is a lightweight Rust instruction builder that creates `Vec` with required refresh instructions prepended automatically. > > **Step 2** > > ### Set Up RPC Client > > ```rust theme={"theme":"css-variables"} > use solana_client::rpc_client::RpcClient; > use solana_sdk::signer::keypair::read_keypair_file; > use solana_sdk::signer::Signer; > > let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); > let signer = read_keypair_file("/path/to/your/keypair.json") > .expect("Failed to read keypair file"); > let owner = signer.pubkey(); > ``` > > **Step 3** > > ### Derive PDAs and Build Instruction > > ```rust theme={"theme":"css-variables"} > use klend_interface::instructions::referrer::{ > withdraw_referrer_fees, > WithdrawReferrerFeesAccounts, > }; > use klend_interface::pda::{self, ReservePdas}; > use klend_interface::KLEND_PROGRAM_ID; > use solana_pubkey::Pubkey; > use std::str::FromStr; > use spl_associated_token_account::get_associated_token_address; > > let referrer = signer.pubkey(); > let lending_market = Pubkey::from_str("7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF").unwrap(); > let reserve_pubkey = Pubkey::from_str("D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59").unwrap(); > let reserve_liquidity_mint = Pubkey::from_str("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap(); > > // Derive PDAs > let (referrer_token_state, _) = pda::referrer_token_state( > &KLEND_PROGRAM_ID, &referrer, &reserve_pubkey > ); > let (lending_market_authority, _) = pda::lending_market_authority( > &KLEND_PROGRAM_ID, &lending_market > ); > let reserve_pdas = ReservePdas::derive(&KLEND_PROGRAM_ID, &reserve_pubkey); > > // Derive referrer's ATA for the reserve liquidity mint > let referrer_token_account = get_associated_token_address(&referrer, &reserve_liquidity_mint); > > let ix = withdraw_referrer_fees(WithdrawReferrerFeesAccounts { > referrer, > referrer_token_state, > reserve: reserve_pubkey, > reserve_liquidity_mint, > reserve_supply_liquidity: reserve_pdas.liquidity_supply_vault, > referrer_token_account, > lending_market, > lending_market_authority, > token_program: spl_token::ID, > }); > ``` > > **Step 4** > > ### Send Transaction > > ```rust theme={"theme":"css-variables"} > use solana_sdk::transaction::Transaction; > use solana_sdk::message::Message; > > let message = Message::new(&[ix], Some(&referrer)); > let recent_blockhash = rpc_client.get_latest_blockhash()?; > let tx = Transaction::new(&[&signer], message, recent_blockhash); > let signature = rpc_client.send_and_confirm_transaction(&tx)?; > println!("Withdraw fees successful! Signature: {signature}"); > ``` # Claim Rewards Source: https://docs.kamino.com/build/tutorials/earn/claim-rewards Claim all rewards earned from Kamino vaults ## Claiming Rewards Retrieve and claim all pending rewards from a vault position. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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'); ``` > [!NOTE] > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. **Step 3** ### Load the Vault Initialize the vault and load its state and reserves once. Both the rewards check and the claim instructions use them. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'), slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const ledgerInstant = await getCurrentLedgerInstant(rpc); ``` **Step 4** ### Check Pending Rewards List the rewards your position has earned, per reward token. ```typescript theme={"theme":"css-variables"} const pending = await manager.getAllPendingRewardsForUserInVault( signer.address, vault, vaultReservesMap, ledgerInstant ); for (const [rewardMint, amount] of pending.totalPendingRewards) { if (amount.isZero()) continue; console.log(`Pending ${amount.toString()} lamports of reward token ${rewardMint}`); } ``` > [!NOTE] > > A position earns rewards from the vault's farm, the vault's delegated farm, and the farms of the reserves the vault allocates to. Amounts are in lamports, so divide by `10^decimals` of the reward token. Unused reward slots return `0` and are skipped. **Step 5** ### Generate Claim Rewards Instructions Build the instructions that claim every pending reward in one transaction. ```typescript theme={"theme":"css-variables"} const instructions = await manager.getClaimAllRewardsForVaultIxs( signer, vault, vaultReservesMap, ledgerInstant ); if (!instructions.length) { console.log('No rewards to claim'); } ``` **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` **Step 7** ### Build and Sign Transaction Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} 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); ``` **Step 8** ### Send and Confirm Transaction Send the claim transaction and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Claim rewards successful! Signature:', signature); ``` > [!TIP] > > Once the claim transaction is confirmed, the reward tokens are sent to your wallet. # Create a Vault Source: https://docs.kamino.com/build/tutorials/earn/creating-a-vault Create and configure Kamino vaults with custom fee structures to earn revenue > [!NOTE] > > Learn how to create a Kamino vault with [custom fee structures](#configure-vault), deposit limits, and allocation strategies. The SDK manages vault initialization, metadata setup, and lookup table creation to optimize future transactions. ## Creating a Vault Initialize a new vault with custom configuration and prepare it for user deposits. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Instruction, } from '@solana/kit'; import { KaminoManager, KaminoVault, KaminoVaultConfig, getMedianSlotDurationInMsFromLastEpochs, sleep, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Admin Keypair and Initialize Manager Load the admin keypair from file and initialize the Kamino manager with proper slot timing. ```typescript theme={"theme":"css-variables"} const KEYPAIR_FILE = '/path/to/your/keypair.json'; const adminSigner = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const kaminoManager = new KaminoManager(rpc, slotDuration); ``` > [!NOTE] > > `parseKeypairFile` loads an existing keypair from a JSON file that will become the vault admin. The admin wallet needs SOL for rent and fees, plus a small amount of the vault token: creation takes an initial deposit of 1,000 lamports (0.001 USDC here) from it. **Step 3** ### Configure Vault Create a vault configuration with the core identity and fee structure. ```typescript theme={"theme":"css-variables"} const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(15.0), managementFeeRatePercentage: new Decimal(2.0), name: 'MyCustomVault', vaultTokenSymbol: 'USDC', vaultTokenName: 'MyCustomVaultToken', minDepositAmount: 1000, minWithdrawAmount: 10, minInvestAmount: 0, minInvestDelaySlots: 0, withdrawalPenaltyBps: 1, withdrawalPenaltyLamports: 1, crankFundFeePerReserve: 1, }); ``` > [!NOTE] > > The parameters from `minDepositAmount` down are optional. The values shown are the defaults, so omit them to keep the defaults. All parameters can be changed after creation. Unallocated weight and cap can only be set after creation, see the [Configure Vault Parameters](#configure-vault-parameters-post-creation) step below. **Vault Configuration Parameters** | Parameter | Type | Default | Description | | - | - | - | - | | `admin` | `TransactionSigner` | | Keypair that owns and manages the vault | | `tokenMint` | `Address` | | SPL token mint address (e.g., USDC) | | `tokenMintProgramId` | `Address` | | Token program of the mint (`TOKEN_PROGRAM_ADDRESS`, or the Token-2022 program for Token-2022 mints) | | `performanceFeeRatePercentage` | `Decimal` | | Percentage of earned yield collected as fees | | `managementFeeRatePercentage` | `Decimal` | | Annual percentage fee on total assets | | `name` | `string` | | Vault name stored on-chain (max 40 characters) | | `vaultTokenSymbol` | `string` | | Symbol for vault share token (max 5 characters) | | `vaultTokenName` | `string` | | Display name for vault share token (max 10 characters) | | `minDepositAmount` | `number` | 1000 | Optional. Minimum deposit per transaction (lamports) | | `minWithdrawAmount` | `number` | 10 | Optional. Minimum withdrawal per transaction (lamports) | | `minInvestAmount` | `number` | 0 | Optional. Minimum amount moved in a single investment (lamports) | | `minInvestDelaySlots` | `number` | 0 | Optional. Slots between investments in a reserve | | `withdrawalPenaltyBps` | `number` | 1 | Optional. Percentage-based withdrawal fee (basis points) | | `withdrawalPenaltyLamports` | `number` | 1 | Optional. Absolute withdrawal fee (lamports) | | `crankFundFeePerReserve` | `number` | 1 | Optional. Fee per reserve to fund crank operations (lamports) | | `allowAllocationsInWhitelistedReservesOnly` | `boolean` | false | Optional. Only allow allocations to whitelisted reserves | | `allowInvestInWhitelistedReservesOnly` | `boolean` | false | Optional. Only allow investing in whitelisted reserves | **Step 4** ### Generate Vault Creation Instructions Pass the vault configuration to the Kamino manager to generate all required initialization instructions. ```typescript theme={"theme":"css-variables"} const { vault: vaultSigner, initVaultIxs: instructions } = await kaminoManager.createVaultIxs(kaminoVaultConfig); console.log('New vault address:', vaultSigner.address); ``` > [!NOTE] > > `createVaultIxs` returns a new vault keypair plus instruction bundles for initializing the vault, creating and filling its lookup table, creating its two farms (the Vault Farm for rewards and the First Loss Capital Farm), registering the farms on the vault, and setting the share token metadata. They are sent across four transactions in the steps below. **Step 5** ### Create a Send Function Vault creation sends several transactions, so define one function that builds, signs, and sends each of them. ```typescript theme={"theme":"css-variables"} async function sendTransaction(ixs: Instruction[], label: string) { const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(ixs, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`${label}:`, getSignatureFromTransaction(signedTransaction)); } ``` > [!NOTE] > > `signTransactionMessageWithSigners` signs with every signer in the instructions, including the new vault keypair. The blockhash is fetched inside the function so each transaction gets a fresh one. **Step 6** ### Initialize the Vault Send the first transaction: it creates the vault, applies the configuration, and creates the vault's lookup table. ```typescript theme={"theme":"css-variables"} await sendTransaction( [ ...instructions.createAtaIfNeededIxs, ...instructions.initVaultIxs, instructions.createLUTIx, ...instructions.cleanupIxs, ], 'Vault initialized' ); ``` > [!NOTE] > > The share token metadata instruction is sent later, in the last transaction. Adding it here takes this transaction over Solana's 1,232-byte limit. **Step 7** ### Create and Attach Farms Create the Vault Farm and the First Loss Capital Farm, and register each one on the vault. Each farm is one transaction. ```typescript theme={"theme":"css-variables"} const vaultFarm = instructions.createVaultFarms.createVaultFarmIxs; await sendTransaction( [...vaultFarm.setupFarmIxs, ...vaultFarm.updateFarmIxs, instructions.setFarmToVaultIxs.setFarmToVaultIx], 'Vault Farm created' ); const flcFarm = instructions.createVaultFarms.createFLCVaultFarmIxs; const setFlcFarm = instructions.setFarmToVaultIxs.setFLCFarmToVaultIx; if (flcFarm && setFlcFarm) { await sendTransaction( [...flcFarm.setupFarmIxs, ...flcFarm.updateFarmIxs, setFlcFarm], 'First Loss Capital Farm created' ); } ``` > [!NOTE] > > If you skip this step, you can create farms later with `kaminoManager.createVaultFarmIxs` and register them with `kaminoManager.updateVaultFarmIxs` (Vault Farm) or `kaminoManager.updateVaultFirstLossCapitalFarmIxs` (First Loss Capital Farm). See [Configure farms](/curators/vaults/guides/configure-farms) for the full post-creation flow. **Step 8** ### Fill the Lookup Table and Set Share Metadata Add the vault's accounts to its lookup table and set the share token metadata. ```typescript theme={"theme":"css-variables"} await sleep(2000); await sendTransaction( [...instructions.populateLUTIxs, instructions.initSharesMetadataIx], 'Lookup table filled and share metadata set' ); ``` > [!NOTE] > > A new lookup table can only be extended from the slot after it was created, so this transaction goes last. The lookup table keeps deposit and withdraw transactions for this vault small. **Step 9** ### Verify the Setup Check that every part of the vault was set up. ```typescript theme={"theme":"css-variables"} const vault = new KaminoVault(rpc, vaultSigner.address, slotDuration); const status = await kaminoManager.getVaultSetupStatus(vault, kaminoVaultConfig); if (status.allSet) { console.log('Vault created and fully set up:', vaultSigner.address); } else { console.log('Setup incomplete:', status); } ``` > [!NOTE] > > If a transaction failed, `kaminoManager.finishVaultSetup(vault, kaminoVaultConfig)` returns only the missing instructions, so you can send them without starting over. **Step 10** ### Configure Vault Parameters (Post-Creation) Set the parameters that are only available after creation (unallocated weight and cap), or update any parameter set during creation. ```typescript theme={"theme":"css-variables"} const vaultState = await vault.getState(); const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); const { updateVaultConfigIx: unallocWeightIx } = await kaminoManager.updateVaultUnallocatedWeightIxs(vault, 500, vaultReservesMap, adminSigner); const { updateVaultConfigIx: unallocCapIx } = await kaminoManager.updateVaultUnallocatedTokensCapIxs(vault, 2000000, vaultReservesMap, adminSigner); await sendTransaction([unallocWeightIx, unallocCapIx], 'Unallocated weight and cap set'); ``` > [!NOTE] > > Every creation parameter has an update method with the same arguments, for example `kaminoManager.updateVaultMinDepositAmountIxs(vault, 1000, vaultReservesMap, adminSigner)`. Each returns `{ updateVaultConfigIx }`. The new vault holds no allocations yet: add reserves with `kaminoManager.updateVaultReserveAllocationIxs` before it can earn. **Post-Creation Parameters** | Method | Parameter | Default | Description | | - | - | - | - | | `updateVaultMinDepositAmountIxs` | `minDepositAmount` | 1000 | Minimum deposit per transaction (lamports) | | `updateVaultMinWithdrawAmountIxs` | `minWithdrawAmount` | 10 | Minimum withdrawal per transaction (lamports) | | `updateVaultMinInvestAmountIxs` | `minInvestAmount` | 0 | Minimum amount moved in a single investment (lamports) | | `updateVaultMinInvestDelaySlotsIxs` | `minInvestDelaySlots` | 0 | Slots between investments in a reserve | | `updateVaultWithdrawalPenaltyBpsIxs` | `withdrawalPenaltyBps` | 1 | Percentage-based withdrawal fee (basis points); returned to vault | | `updateVaultWithdrawalPenaltyLamportsIxs` | `withdrawalPenaltyLamports` | 1 | Absolute withdrawal fee (lamports); system takes MAX of BPS and lamports | | `updateVaultCrankFundFeePerReserveIxs` | `crankFundFeePerReserve` | 1 | Fee per reserve to fund crank operations (lamports) | | `updateVaultUnallocatedWeightIxs` | `unallocatedWeight` | 500 | Relative weight for idle funds in total weight calculation | | `updateVaultUnallocatedTokensCapIxs` | `unallocatedTokensCap` | 2000000 | Maximum absolute amount to keep unallocated (lamports) | #### Full Code Example ```typescript expandable theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Instruction, } from '@solana/kit'; import { KaminoManager, KaminoVault, KaminoVaultConfig, getMedianSlotDurationInMsFromLastEpochs, sleep, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; import { Decimal } from 'decimal.js'; const KEYPAIR_FILE = '/path/to/your/keypair.json'; const adminSigner = await parseKeypairFile(KEYPAIR_FILE); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const kaminoManager = new KaminoManager(rpc, slotDuration); const kaminoVaultConfig = new KaminoVaultConfig({ admin: adminSigner, tokenMint: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, performanceFeeRatePercentage: new Decimal(15.0), managementFeeRatePercentage: new Decimal(2.0), name: 'MyCustomVault', vaultTokenSymbol: 'USDC', vaultTokenName: 'MyCustomVaultToken', minDepositAmount: 1000, minWithdrawAmount: 10, minInvestAmount: 0, minInvestDelaySlots: 0, withdrawalPenaltyBps: 1, withdrawalPenaltyLamports: 1, crankFundFeePerReserve: 1, }); const { vault: vaultSigner, initVaultIxs: instructions } = await kaminoManager.createVaultIxs(kaminoVaultConfig); console.log('New vault address:', vaultSigner.address); async function sendTransaction(ixs: Instruction[], label: string) { const { value: latestBlockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), (tx) => appendTransactionMessageInstructions(ixs, tx) ); const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); assertIsTransactionWithinSizeLimit(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log(`${label}:`, getSignatureFromTransaction(signedTransaction)); } await sendTransaction( [ ...instructions.createAtaIfNeededIxs, ...instructions.initVaultIxs, instructions.createLUTIx, ...instructions.cleanupIxs, ], 'Vault initialized' ); const vaultFarm = instructions.createVaultFarms.createVaultFarmIxs; await sendTransaction( [...vaultFarm.setupFarmIxs, ...vaultFarm.updateFarmIxs, instructions.setFarmToVaultIxs.setFarmToVaultIx], 'Vault Farm created' ); const flcFarm = instructions.createVaultFarms.createFLCVaultFarmIxs; const setFlcFarm = instructions.setFarmToVaultIxs.setFLCFarmToVaultIx; if (flcFarm && setFlcFarm) { await sendTransaction( [...flcFarm.setupFarmIxs, ...flcFarm.updateFarmIxs, setFlcFarm], 'First Loss Capital Farm created' ); } await sleep(2000); await sendTransaction( [...instructions.populateLUTIxs, instructions.initSharesMetadataIx], 'Lookup table filled and share metadata set' ); const vault = new KaminoVault(rpc, vaultSigner.address, slotDuration); const status = await kaminoManager.getVaultSetupStatus(vault, kaminoVaultConfig); if (status.allSet) { console.log('Vault created and fully set up:', vaultSigner.address); } else { console.log('Setup incomplete:', status); } const vaultState = await vault.getState(); const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); const { updateVaultConfigIx: unallocWeightIx } = await kaminoManager.updateVaultUnallocatedWeightIxs(vault, 500, vaultReservesMap, adminSigner); const { updateVaultConfigIx: unallocCapIx } = await kaminoManager.updateVaultUnallocatedTokensCapIxs(vault, 2000000, vaultReservesMap, adminSigner); await sendTransaction([unallocWeightIx, unallocCapIx], 'Unallocated weight and cap set'); ``` # Earn and Withdraw Source: https://docs.kamino.com/build/tutorials/earn/earn-and-withdraw Deposit assets into Kamino Earn Vaults and withdraw your shares ## Deposit to Earn Vault Deposit assets to start earning yield. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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'); ``` > [!NOTE] > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. **Step 3** ### Load the Vault Initialize the vault and load its state, reserves, and farm state once. The deposit instructions need all three. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const farmState = await manager.loadVaultFarmState(vaultState); ``` **Step 4** ### Set Slippage Protection Estimate the shares the deposit will mint, minus a slippage tolerance. The deposit reverts if fewer shares would be minted. ```typescript theme={"theme":"css-variables"} const depositAmount = new Decimal(1.0); // 1 USDC const minSharesOut = manager.estimateSharesFromTokens( vaultState, depositAmount, await getCurrentLedgerInstant(rpc), vaultReservesMap, 10 // 0.1% slippage ); ``` > [!NOTE] > > The deposit amount is in tokens (`1.0` is 1 USDC), not lamports. **Step 5** ### Build Deposit Instructions Generate the deposit instructions, plus the instructions that stake the new shares in the vault's farm. ```typescript theme={"theme":"css-variables"} const bundle = await vault.depositIxs( signer, depositAmount, vaultReservesMap, farmState, null, // first-loss capital farm undefined, // payer undefined, // memo minSharesOut ); const instructions = [...bundle.depositIxs, ...bundle.stakeInFarmIfNeededIxs]; ``` > [!NOTE] > > If the vault has a rewards farm, `stakeInFarmIfNeededIxs` stakes the minted shares in it so the position earns farm rewards. Shares staked here are unstaked automatically when you withdraw. **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` > [!NOTE] > > Every vault has its own lookup table. Compressing with it cuts the deposit from about 1,021 to 528 bytes, well under Solana's 1,232-byte transaction limit. **Step 7** ### Build and Sign Transaction Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} 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); ``` **Step 8** ### Send and Confirm Transaction Send the deposit transaction and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Deposit successful! Signature:', signature); ``` > [!TIP] > > 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. ## Withdraw from Earn Vault Withdraw your vault shares to receive the underlying tokens plus accrued interest. **Step 1** ### Import Dependencies Import the required packages for Solana RPC communication, Kamino SDK operations, and Kit transaction building. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, createSolanaRpcSubscriptions, address, pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, appendTransactionMessageInstructions, compressTransactionMessageUsingAddressLookupTables, signTransactionMessageWithSigners, assertIsTransactionWithinSizeLimit, sendAndConfirmTransactionFactory, getSignatureFromTransaction, type Address, } from '@solana/kit'; import { fetchAllAddressLookupTable } from '@solana-program/address-lookup-table'; import { KaminoManager, KaminoVault, getCurrentLedgerInstant, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; import { Decimal } from 'decimal.js'; ``` **Step 2** ### Load Signer and Initialize RPC Load your keypair from a file and initialize RPC connections. ```typescript theme={"theme":"css-variables"} 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'); ``` > [!NOTE] > > Replace `/path/to/your/keypair.json` with the actual path to your keypair file. `parseKeypairFile` loads an existing keypair from a JSON file. The `rpcSubscriptions` enables real-time transaction confirmation. **Step 3** ### Load the Vault Initialize the vault and load its state, reserves, and farm state once. The withdraw instructions need all three. ```typescript theme={"theme":"css-variables"} const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const manager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault( rpc, address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault slotDuration ); const vaultState = await vault.getState(); const vaultReservesMap = await manager.loadVaultReserves(vaultState); const farmState = await manager.loadVaultFarmState(vaultState); const ledgerInstant = await getCurrentLedgerInstant(rpc); ``` **Step 4** ### Convert Tokens to Shares Convert the token amount you want back into vault shares, capped at the shares you hold. ```typescript theme={"theme":"css-variables"} const withdrawAmount = new Decimal(1.0); // 1 USDC const userShares = await vault.getUserShares(signer.address); const tokensPerShare = await manager.getTokensPerShareSingleVault(vault, ledgerInstant, vaultReservesMap, ledgerInstant); const sharesToWithdraw = Decimal.min(withdrawAmount.div(tokensPerShare), userShares.totalShares); ``` > [!NOTE] > > `withdrawIxs` takes an amount of **vault shares**, not tokens. Shares grow in value as interest accrues, so one share is worth more than one token. To withdraw everything, pass `userShares.totalShares`. **Step 5** ### Build Withdraw Instructions Generate the unstake and withdraw instructions. ```typescript theme={"theme":"css-variables"} const bundle = await vault.withdrawIxs( signer, sharesToWithdraw, ledgerInstant, vaultReservesMap, farmState, null // first-loss capital farm ); const instructions = [...bundle.unstakeFromFarmIfNeededIxs, ...bundle.withdrawIxs, ...bundle.postWithdrawIxs]; ``` > [!NOTE] > > Deposits stake shares in the vault's farm, so `unstakeFromFarmIfNeededIxs` must come before `withdrawIxs`. Without it, withdrawing staked shares fails with `CannotWithdrawZeroShares`. **Step 6** ### Load the Vault's Lookup Table Fetch the vault's address lookup table to keep the transaction small. ```typescript theme={"theme":"css-variables"} const lookupTables = await fetchAllAddressLookupTable(rpc, [vaultState.vaultLookupTable]); const lutsByAddress: Record = {}; for (const lut of lookupTables) lutsByAddress[lut.address] = lut.data.addresses; ``` > [!NOTE] > > Some vaults need the lookup table for a withdraw to fit in one transaction. Without it, a withdraw from one vault we tested was 1,274 bytes, over Solana's 1,232-byte limit. **Step 7** ### Build and Sign Transaction Use Kit's functional pipe pattern to build, compress, and sign the transaction with a fresh blockhash. ```typescript theme={"theme":"css-variables"} 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); ``` **Step 8** ### Send and Confirm Transaction Send the withdraw transaction and wait for confirmation. ```typescript theme={"theme":"css-variables"} const signature = getSignatureFromTransaction(signedTransaction); await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { commitment: 'confirmed', skipPreflight: true, }); console.log('Withdraw successful! Signature:', signature); ``` > [!TIP] > > Once the withdraw transaction is confirmed, your vault shares are burned and you receive the underlying tokens plus any accrued interest. > [accordion] What Happens When You Deposit? > > 1. You deposit USDC (or another token) into the vault > 2. You receive vault share tokens (like kVUSDC or similar). If the vault has a rewards farm, the shares are staked in it automatically so they also earn farm rewards > 3. These shares represent your proportional ownership of the vault > 4. The shares appreciate in value as the vault earns yield > [accordion] What Happens When You Withdraw? > > 1. Your shares are unstaked from the vault's farm (if staked) and burned > 2. You receive back the underlying tokens (USDC) based on the current exchange rate # Vaults Source: https://docs.kamino.com/build/tutorials/earn/index Learn how to retrieve vault TVL, APY, farm rewards, allocation weights, and user share balances using the Kamino SDK and API > [card] [Earn Vaults](/build/earn/index) > > Earn interest on assets ## Get Vault Information Retrieve vault holdings, APY and exchange rate information. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > await getMedianSlotDurationInMsFromLastEpochs() > ); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const apys = await vault.getAPYs(ledgerInstant); > > console.log({ > holdings: (await vault.getVaultHoldings(ledgerInstant)).asJSON(), > actualAPY: apys.actualAPY.netAPY.toString(), > theoreticalAPY: apys.theoreticalAPY.netAPY.toString(), > exchangeRate: (await vault.getExchangeRate(ledgerInstant)).toString(), > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-01-get-vault-info-example/index.ts) ## Get User Position Check a user's share balance and token value for a specific vault. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const vault = new KaminoVault( > rpc, > address('A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'), > await getMedianSlotDurationInMsFromLastEpochs() > ); > > const user = address('883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62'); > > const shares = await vault.getUserShares(user); > const rate = await vault.getExchangeRate(await getCurrentLedgerInstant(rpc)); > > console.log({ > unstakedShares: shares.unstakedShares.toString(), > stakedShares: shares.stakedShares.toString(), > totalShares: shares.totalShares.toString(), > tokens: shares.totalShares.mul(rate).toString(), // the user's position in tokens > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-02-get-user-vault-position-example/index.ts) ## Get All User Positions Fetch a user's share balances across all vaults they participate in. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoManager, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const manager = new KaminoManager( > createSolanaRpc('https://api.mainnet-beta.solana.com'), > await getMedianSlotDurationInMsFromLastEpochs() > ); > > const user = address('883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62'); > const userSharesAllVaults = await manager.getUserSharesBalanceAllVaults(user); > > userSharesAllVaults.forEach((shares, vault) => { > if (shares.totalShares.gt(0)) { > console.log(`User shares in ${vault}:`, shares.totalShares.toString()); > } > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-03-get-user-all-vaults-positions-example/index.ts) ## Deposit to Vault Generate deposit instructions to add tokens to a vault. To sign and send them, follow the [deposit guide](/build/developers/earn/operations/deposit). > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address, createNoopSigner } from '@solana/kit'; > import { KaminoManager, KaminoVault, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > > const { depositIxs, stakeInFarmIfNeededIxs } = await vault.depositIxs( > createNoopSigner(address('EZC9wzVCvihCsCHEMGADYdsRhcpdRYWzSCZAVegSCfqY')), // user > new Decimal(100.0), > vaultReservesMap, > farmState, > null > ); > > console.log('Deposit Instructions:', [...depositIxs, ...stakeInFarmIfNeededIxs]); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-04-user-deposit-example/index.ts) ## Withdraw from Vault Generate withdrawal instructions to remove shares from a vault. To sign and send them, follow the [withdraw guide](/build/developers/earn/operations/withdraw). > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address, createNoopSigner } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'), > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await manager.loadVaultReserves(vaultState); > const farmState = await manager.loadVaultFarmState(vaultState); > > const { unstakeFromFarmIfNeededIxs, withdrawIxs, postWithdrawIxs } = await vault.withdrawIxs( > createNoopSigner(address('883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62')), // user > new Decimal(1.5), // withdraw 1.5 shares > await getCurrentLedgerInstant(rpc), > vaultReservesMap, > farmState, > null > ); > > console.log('Withdraw Instructions:', [...unstakeFromFarmIfNeededIxs, ...withdrawIxs, ...postWithdrawIxs]); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-05-user-withdraw-example/index.ts) ## Get Vault Allocations View how vault assets are allocated across different reserves with target weights. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoVault, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > > const vault = new KaminoVault( > createSolanaRpc('https://api.mainnet-beta.solana.com'), > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > await getMedianSlotDurationInMsFromLastEpochs() > ); > > const allocations = await vault.getVaultAllocations(); > > for (const [address, overview] of allocations) { > console.log( > `Reserve: ${address}: weight ${overview.targetWeight.toString()}, allocation: ${overview.ctokenAllocationLamports.toString()}` > ); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-06-get-vault-advanced-info-allocations-example/index.ts) ## Get Vault Incentives Access comprehensive vault incentive data including farm and reserve rewards. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > getCurrentLedgerInstant, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { Farms } from '@kamino-finance/farms-sdk'; > import { Decimal } from 'decimal.js'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoManager = new KaminoManager(rpc, slotDuration); > const vault = new KaminoVault( > rpc, > address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'), // USDC vault > slotDuration > ); > > const vaultState = await vault.getState(); > const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); > const ledgerInstant = await getCurrentLedgerInstant(rpc); > > const vaultTokenPrice = new Decimal(1.0); // as it is an USDC vault the token price is 1 > const vaultOverview = await kaminoManager.getVaultOverview( > vault, > vaultTokenPrice, > ledgerInstant, > vaultReservesMap, > await kaminoManager.loadKaminoMarketsForVaultReserves(vaultReservesMap), > await kaminoManager.loadVaultFarmStates([vaultState], vaultReservesMap), > new Farms(rpc), > await kaminoManager.loadKVaultGlobalConfig(), > ledgerInstant > ); > > console.log('delegated farm incentives', vaultOverview.delegatedFarmIncentives); > console.log('reserves farm incentives', vaultOverview.reservesFarmsIncentives); > console.log('vault farm incentives', vaultOverview.vaultFarmIncentives); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-07-get-vault-advanced-info-incentives-example/index.ts) ## Get Vault Metrics History Retrieve historical vault-level performance metrics including TVL, APY, and farm rewards APY over time. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address > > const API_BASE_URL = 'https://api.kamino.finance'; > > const params = new URLSearchParams({ > start: '2024-06-01T00:00:00.000Z', > end: '2025-01-01T00:00:00.000Z', > }).toString(); > > const url = `${API_BASE_URL}/kvaults/vaults/${kvaultPubkey}/metrics/history?${params}`; > const res = await fetch(url); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > const data = await res.json(); > > for (const item of data) { > console.log({ > tvl: item.tvl, > apy: item.apy, > apyFarmRewards: item.apyFarmRewards, > }); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-10-get-vault-historical-info-example/index.ts) ## Get User Position History Retrieve historical performance metrics for a user's position in a specific vault. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const kvaultPubkey = 'A2wsxhA7pF4B2UKVfXocb6TAAP9ipfPJam6oMKgDE5BK'; > const ownerPubkey = '883AnESJiUVzCnwowgaWCpXp4EGsK4JMVzUUUcjSSs62'; // user > > const API_BASE_URL = 'https://api.kamino.finance'; > > const params = new URLSearchParams({ > start: '2024-01-01T00:00:00.000Z', > end: '2025-10-01T00:00:00.000Z', > }).toString(); > > const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/history?${params}`; > const res = await fetch(url); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > const data = await res.json(); > > for (const item of data) { > console.log({ > createdOn: item.createdOn, > sharesAmount: item.sharesAmount, > usdAmount: item.usdAmount, > apy: item.apy, > cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, > }); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-08-get-user-vault-position-historical-info-example/index.ts) ## Get All User Position History Fetch cumulative historical metrics for a user across all their vault positions. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address > > const API_BASE_URL = 'https://api.kamino.finance'; > > const params = new URLSearchParams({ > start: '2024-01-01T00:00:00.000Z', > end: '2025-11-20T00:00:00.000Z', > }).toString(); > > const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/metrics/history?${params}`; > const res = await fetch(url); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > const data = await res.json(); > > for (const item of data) { > console.log({ > createdOn: item.createdOn, > usdAmount: item.usdAmount, > solAmount: item.solAmount, > weightedApy: item.weightedApy, > cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, > }); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-09-get-user-all-vaults-positions-historical-info-example/index.ts) ## Get User Vault Position History Access historical metrics for a user's position in a specific vault over time. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address > const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address > > const API_BASE_URL = 'https://api.kamino.finance'; > > const params = new URLSearchParams({ > start: '2024-01-01T00:00:00.000Z', > end: '2025-01-01T00:00:00.000Z', > }).toString(); > > const url = `${API_BASE_URL}/kvaults/users/${ownerPubkey}/vaults/${kvaultPubkey}/metrics/history?${params}`; > const res = await fetch(url); > if (!res.ok) { > console.log(`Request failed: ${res.status} ${res.statusText}`); > } > const data = await res.json(); > > for (const item of data) { > console.log({ > createdOn: item.createdOn, > sharesAmount: item.sharesAmount, > usdAmount: item.usdAmount, > apy: item.apy, > cumulativeInterestEarnedUsd: item.cumulativeInterestEarnedUsd, > }); > } > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-10-get-vault-historical-info-example/index.ts) ## Get User P\&L Calculate a user's profit and loss for their position in a vault. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > const kvaultPubkey = 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E'; // vault address > const ownerPubkey = 'AxqtG9SHDkZTLSWg81Sp7VqAzQpRqXtR9ziJ3VQAS8As'; // user address > > const API_BASE_URL = 'https://api.kamino.finance'; > > const url = `${API_BASE_URL}/kvaults/${kvaultPubkey}/users/${ownerPubkey}/pnl`; > const res = await fetch(url); > if (!res.ok) { > console.log(`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, > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/kvault-tutorial/earn-vaults-11-get-vault-user-pnl-example/index.ts) ## Vault Revenue Share Earn revenue by deploying vaults with custom fee structures. Set performance fees on profits and management fees on assets under management. > [tab] TypeScript > > ```typescript theme={"theme":"css-variables"} > import { address, generateKeyPairSigner } from '@solana/kit'; > import { KaminoVaultConfig } from '@kamino-finance/klend-sdk'; > import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; > import { Decimal } from 'decimal.js'; > > const adminSigner = await generateKeyPairSigner(); > const tokenMint = address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // USDC > > const kaminoVaultConfig = new KaminoVaultConfig({ > admin: adminSigner, > tokenMint: tokenMint, > tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, > performanceFeeRatePercentage: new Decimal(10.0), // 10% performance fee on profits > managementFeeRatePercentage: new Decimal(1.0), // 1% annual management fee on AUM > name: 'Revenue Share Vault', > vaultTokenSymbol: 'kUSDC', > vaultTokenName: 'kUSDC receipt', > }); > ``` > > [View Code](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) # Get raw token holdings for a wallet Source: https://docs.kamino.com/build/user/get-raw-token-holdings-for-a-wallet /kamino-api.json get /user/{walletPubkey}/holdings Returns raw SPL Token, Token-2022, and native SOL holdings keyed by mint. Native SOL is reported under the wrapped SOL mint and summed with any wrapped SOL token-account balance. Holdings are priced from cached Scope spot prices with kswap fallback prices when Scope has no price; valueUsd is null when neither source has a price. When minValueUsd is set, holdings below the threshold and unpriced holdings are excluded. Returns 422 when the wallet has too many token accounts to list. # Get principal token yields Source: https://docs.kamino.com/build/yields/get-principal-token-yields /kamino-api.json get /yields/principal-tokens Get fresh stored APYs for principal tokens with active Kamino reserves. Each value matches reserve stats `underlyingApy.current` for the same stored snapshot. Sources without a value from the last 48 hours are omitted; matured principal tokens with a fresh zero row report 0. # Get underlying token yield history Source: https://docs.kamino.com/build/yields/get-underlying-token-yield-history /kamino-api.json get /v2/underlying-yields/{mint}/history Get the native yield history for a reserve liquidity mint, with server-side source classification and combined LST alignment. # Get yield history Source: https://docs.kamino.com/build/yields/get-yield-history /kamino-api.json get /yields/{yieldSource}/history Get historical yield data for a given source, between an optional range of dates (max 366 days). For extra farm yields specify the source as farmAddress-rewardMint. # Allocation Data Source: https://docs.kamino.com/curators/data/allocation-data Query current allocations, weights, and historical allocation changes Access vault allocation state, reserve distribution, and historical allocation changes via the REST API and TypeScript SDK. Use these endpoints to monitor how your vault distributes capital across reserves. ## Current Allocations Query the current allocation state including reserve weights, ctoken allocations, and target distributions. ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), address('') ); const allocations = await vault.getVaultAllocations(); for (const [reserveAddress, overview] of allocations) { console.log( `Reserve: ${reserveAddress}: ` + `weight ${overview.targetWeight.toString()}, ` + `allocation: ${overview.ctokenAllocation.toString()}` ); } ``` ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/vaults/' ); const vault = await response.json(); // Allocation data is part of the vault state console.log('Vault state with allocations:', vault.state); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/vaults/ ``` ## Vault Overview with Allocations Get a comprehensive overview including allocation data, incentives, and performance metrics. ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const vault = new KaminoVault(rpc, address('')); const kaminoManager = new KaminoManager(rpc); const vaultTokenPrice = new Decimal(1.0); // adjust for non-stablecoin vaults const vaultOverview = await kaminoManager.getVaultOverview(vault, vaultTokenPrice); console.log('Overview:', vaultOverview); console.log('Reserve farm incentives:', vaultOverview.reservesFarmsIncentives); console.log('Delegated farm incentives:', vaultOverview.delegatedFarmIncentives); ``` ## Allocation Volume History Query historical allocation volume changes over time. Track how capital distribution across reserves has evolved. > [!NOTE] > > Historical allocation data is only available via the API. ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/vaults//allocation-volume/history' ); const history = await response.json(); console.log('Allocation history:', history); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/vaults//allocation-volume/history ``` ## Additional Resources > [card] [Full API Reference](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) # Depositor & Position Data Source: https://docs.kamino.com/curators/data/depositor-data Query depositor positions, P&L, transaction history, and metrics Access depositor position data, profit & loss tracking, and transaction history via the REST API and TypeScript SDK. Use these endpoints to monitor your vault's depositors and their positions. ## User Positions (All Vaults) Get all vault positions for a specific wallet address. ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager } from '@kamino-finance/klend-sdk'; const manager = new KaminoManager( createSolanaRpc('https://api.mainnet-beta.solana.com') ); const user = address(''); const userSharesAllVaults = await manager.getUserSharesBalanceAllVaults(user); userSharesAllVaults.forEach((shares, vault) => { console.log(`User shares in ${vault}:`, shares); }); ``` ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/users//positions' ); const positions = await response.json(); console.log('All positions:', positions); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/users//positions ``` ## User Vault Position Get a specific user's position in a specific vault, including share balance and token value. ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), address('') ); const user = address(''); const shares = await vault.getUserShares(user); const rate = await vault.getExchangeRate(); console.log({ shares: shares.totalShares.toString(), tokens: shares.totalShares.mul(rate).toString(), }); ``` ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/users//positions/' ); const position = await response.json(); console.log('Vault position:', position); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/users//positions/ ``` ## User Vault P\&L Get current profit and loss data for a user's position in a specific vault. Returns P\&L in USD, SOL, and token denominations. ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults//users//pnl' ); const pnl = await response.json(); console.log('User P&L:', pnl); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults//users//pnl ``` ## User Vault P\&L History Query historical profit and loss data. Returns transaction-level P\&L history with cost basis, realized gains, and position values. > [!NOTE] > > P\&L history is only available via the API. ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/users//vaults//pnl/history' ); const pnlHistory = await response.json(); console.log('P&L history:', pnlHistory); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/users//vaults//pnl/history ``` ## User Vault Metrics History Retrieve historical performance metrics for a specific user and vault. Returns time-series data including shares, APY, and cumulative interest earned. > [!NOTE] > > Metrics history is only available via the API. ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/users//vaults//metrics/history' ); const metricsHistory = await response.json(); console.log('User vault metrics history:', metricsHistory); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/users//vaults//metrics/history ``` ## User Total Metrics History Query cumulative performance metrics for a user across all vaults over a time range. Returns aggregated time-series data. > [!NOTE] > > Total metrics history is only available via the API. ```typescript API theme={"theme":"css-variables"} const params = new URLSearchParams({ start: '2025-01-01T00:00:00.000Z', end: '2025-12-31T00:00:00.000Z', }).toString(); const response = await fetch( `https://api.kamino.finance/kvaults/users//metrics/history?${params}` ); const totalMetrics = await response.json(); console.log('Total metrics history:', totalMetrics); ``` ```bash curl theme={"theme":"css-variables"} curl "https://api.kamino.finance/kvaults/users//metrics/history?start=2025-01-01T00:00:00.000Z&end=2025-12-31T00:00:00.000Z" ``` ## User Transactions Query deposit and withdrawal transaction history for a user. > [!NOTE] > > Transaction history is only available via the API. ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/users//transactions' ); const transactions = await response.json(); console.log('User transactions:', transactions); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/users//transactions ``` ## Additional Resources > [card] [Full API Reference](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) # Rewards Data Source: https://docs.kamino.com/curators/data/rewards-data Query vault rewards, incentive programs, and reward APY data Access vault reward information, incentive programs, and farm data via the REST API and TypeScript SDK. Use these endpoints to monitor reward distribution and calculate incentive APYs for your vault. ## Vault Rewards Query all active reward programs across vaults. ```typescript API theme={"theme":"css-variables"} const response = await fetch('https://api.kamino.finance/kvaults/rewards'); const rewards = await response.json(); console.log('All vault rewards:', rewards); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/rewards ``` ## Vault Incentive Data Get detailed incentive information for a specific vault including delegated farm rewards, reserve farm incentives, and direct vault farm incentives. ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const vault = new KaminoVault(rpc, address('')); const kaminoManager = new KaminoManager(rpc); const vaultTokenPrice = new Decimal(1.0); // adjust for non-stablecoin vaults const vaultOverview = await kaminoManager.getVaultOverview(vault, vaultTokenPrice); console.log('Delegated farm incentives:', vaultOverview.delegatedFarmIncentives); console.log('Reserve farm incentives:', vaultOverview.reservesFarmsIncentives); console.log('Vault farm incentives:', vaultOverview.vaultFarmIncentives); ``` ### Incentive Types | Type | Description | | - | - | | **Delegated Farm Incentives** | Rewards delegated from the vault farm to depositors | | **Reserve Farm Incentives** | Rewards from individual lending reserve farms that the vault participates in | | **Vault Farm Incentives** | Direct rewards distributed through the vault's own farm | ## Reward APY Calculation Calculate the total reward APY for a vault by combining incentive data from the vault overview. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const vault = new KaminoVault(rpc, address('')); const kaminoManager = new KaminoManager(rpc); const vaultTokenPrice = new Decimal(1.0); const vaultOverview = await kaminoManager.getVaultOverview(vault, vaultTokenPrice); // The vault overview contains APY breakdown by source console.log('Full vault overview:', vaultOverview); ``` > [!NOTE] > > Reward APYs are dynamic and depend on total deposits, reward emission rates, and token prices. Query this data regularly for accurate dashboard displays. ## Additional Resources > [card] [Full API Reference](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) # Vault Data Source: https://docs.kamino.com/curators/data/vault-data Query vault details, metrics, holdings, and historical performance Access vault state, metrics, and historical data via the REST API and TypeScript SDK. Use these endpoints to build dashboards, monitoring tools, and analysis pipelines. ## List All Vaults Fetch all available Kamino vaults with their state and configuration. ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc } from '@solana/kit'; import { KaminoManager } from '@kamino-finance/klend-sdk'; const manager = new KaminoManager( createSolanaRpc('https://api.mainnet-beta.solana.com') ); // Use the API for listing all vaults (SDK reads individual vaults on-chain) ``` ```typescript API theme={"theme":"css-variables"} const response = await fetch('https://api.kamino.finance/kvaults/vaults'); const vaults = await response.json(); vaults.forEach((vault: any) => { console.log({ address: vault.address, name: vault.state.name, tokenMint: vault.state.tokenMint, sharesIssued: vault.state.sharesIssued, tokenAvailable: vault.state.tokenAvailable, }); }); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/vaults ``` ## Vault Details Get the full state and configuration for a specific vault. ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), address('') ); const holdings = await vault.getVaultHoldings(); console.log('Holdings:', holdings.asJSON()); ``` ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/vaults/' ); const vault = await response.json(); console.log('Name:', vault.state.name); console.log('Token mint:', vault.state.tokenMint); console.log('Shares issued:', vault.state.sharesIssued); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/vaults/ ``` ## Current Metrics Get real-time metrics including APY, exchange rate, and TVL. ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), address('') ); console.log({ apys: await vault.getAPYs(), exchangeRate: (await vault.getExchangeRate()).toString(), holdings: (await vault.getVaultHoldings()).asJSON(), }); ``` ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/vaults//metrics' ); const metrics = await response.json(); console.log('Current metrics:', metrics); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/vaults//metrics ``` ## Metrics History Query historical vault performance over a time range. Returns time-series data including TVL, APY, and exchange rate changes. > [!NOTE] > > Historical data is only available via the API. ```typescript API theme={"theme":"css-variables"} const params = new URLSearchParams({ start: '2025-01-01T00:00:00.000Z', end: '2025-12-31T00:00:00.000Z', }).toString(); const response = await fetch( `https://api.kamino.finance/kvaults/vaults//metrics/history?${params}` ); const history = await response.json(); console.log('Historical metrics:', history); ``` ```bash curl theme={"theme":"css-variables"} curl "https://api.kamino.finance/kvaults/vaults//metrics/history?start=2025-01-01T00:00:00.000Z&end=2025-12-31T00:00:00.000Z" ``` ## Vault Summary Get aggregated summary statistics for all vaults. ```typescript API theme={"theme":"css-variables"} const response = await fetch('https://api.kamino.finance/kvaults/summary'); const summary = await response.json(); console.log('Program summary:', summary); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/summary ``` ## Token Metadata Get the receipt token metadata for a vault. ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kvaults/vaults//mint/metadata' ); const metadata = await response.json(); console.log('Token metadata:', metadata); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kvaults/vaults//mint/metadata ``` ## Additional Resources > [card] [Full API Reference](https://api-docs.kamino.com/) > [card] [SDK Examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples/kvault-tutorial) # Curators Source: https://docs.kamino.com/curators/index Create and manage lending vaults and markets on Kamino ## Overview Kamino Curators create and manage lending infrastructure on Solana. Curators can deploy **lending vaults** that route depositor capital across reserves, or create **lending markets** that enable peer-to-pool borrowing and lending for specific asset ecosystems. **Vaults** accept a single deposit token, distribute capital across reserves according to your allocation weights and caps, and issue share tokens to depositors. You control allocation strategy, fee structure, risk parameters, and rewards distribution — all managed through [kamino.com/curators/vaults](https://kamino.com/curators/vaults). **Markets** are isolated lending environments with their own reserves, risk parameters, and oracle configurations. Market curators configure reserve parameters (LTV, liquidation thresholds, interest rate curves), manage oracle feeds, and set market-wide settings via the Kamino CLI. ## What You Can Do ### Vaults > [card] [Create vaults](/curators/vaults/guides/create-a-vault) > > Deploy vaults with custom fee structures, deposit parameters, and security settings. > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > Distribute capital across lending reserves using relative weights, caps, and Conditional allocation logic. > [card] [Configure farms](/curators/vaults/guides/configure-farms) > > Attach the Vault Farm, Insurance Pool farm, and Autocompound Farm for reward distribution. > [card] [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) > > Configure the loss backstop and trigger the Kamino match. ### Markets > [card] [Create Markets](/curators/markets/creating-a-market) > > Deploy isolated lending markets with custom risk parameters and reserve configurations. > [card] [Manage Reserves](/curators/markets/reserve-management) > > Add reserves, configure LTV ratios, liquidation thresholds, and interest rate curves. > [card] [Configure Market Rewards](/curators/markets/farms-and-rewards) > > Set up collateral and debt farms to distribute rewards to depositors and borrowers. > [card] [Market Settings](/curators/markets/market-settings) > > Manage market-wide parameters, oracle configurations, and ownership via CLI. ## Getting Started ### For Vaults **1. Create a Vault** Configure your vault's deposit token, receipt token, fees, and advanced parameters on [kamino.com/curators/vaults](https://kamino.com/curators/vaults). See [Create a vault](/curators/vaults/guides/create-a-vault). **2. Complete post-creation setup** Configure allocations, set up the Insurance Pool, enable Whitelisted Reserves, attach farms, and transfer admin to a multisig. See the [Vaults overview](/curators/vaults) for the full guide list. **3. Manage Ongoing Operations** Adjust allocations, update fees, manage rewards, and sync vault state as needed. ### For Markets **1. Create a Market** Deploy a new lending market using the Kamino CLI. See [Creating a Market](/curators/markets/creating-a-market). **2. Add Reserves** Configure and add token reserves with LTV ratios, rate curves, and oracle feeds. See [Adding Reserves](/curators/markets/adding-reserves). **3. Transfer to Multisig** Transfer market ownership to a Squads multisig before going live. All subsequent operations use multisig mode. ## Reference > [card] [Vault Parameters](/curators/reference/parameters) > > Complete reference for all vault, allocation, and farm parameters. > [card] [Vault Glossary](/curators/reference/glossary) > > Definitions for key vault terms. > [card] [Reserve Parameters](/curators/markets/reserve-parameters) > > Complete reference for all reserve configuration parameters. > [card] [Market Glossary](/curators/markets/glossary) > > Definitions for key market and lending terms. > [!NOTE] > > All vault operations are managed via [kamino.com/curators/vaults](https://kamino.com/curators/vaults) and executed through [Squads](https://squads.so) multisig. Market operations use the Kamino CLI with multisig mode after initial setup. # Add Reserves Source: https://docs.kamino.com/curators/markets/adding-reserves Add token reserves to your market A reserve is the per-asset lending pool inside a market. Each reserve holds one mint, has its own LTV / liquidation threshold / IR curve, and connects to one oracle. A market without reserves accepts nothing; reserves are how you list assets. > [!NOTE] > > Each (mint, market) pair can have at most one reserve. If you need multiple reserves for the same asset (e.g., separate fixed-term tracks), each one needs its own market. ## Prerequisites | Item | Where to get it | | - | - | | Market address | Output of [Create a market](/curators/markets/creating-a-market) | | Token mint address | The SPL Token or Token-2022 mint of the asset | | Mint program ID | `TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA` for SPL Token, `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb` for Token-2022 | | Oracle ID | Scope feed pubkey (see [Configure oracles](/curators/markets/configuring-oracles)) | | Risk parameters | LTV, liquidation threshold, IR curve, caps (see [Risk parameters](/curators/markets/risk-parameters)) | > [tab] SDK > > ## Add a reserve via SDK > > The SDK exposes `kaminoManager.addAssetToMarketIxs(params)` which returns instructions for both creating the reserve account and applying its initial config. Build the asset config using `AssetReserveConfig` (or `AssetReserveConfigCli` if you want to load a JSON-shaped config). > > **1. Import dependencies** > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > generateKeyPairSigner, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > AssetReserveConfig, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; > import { findAssociatedTokenPda } from '@solana-program/token-2022'; > import { Decimal } from 'decimal.js'; > ``` > > **2. Initialize KaminoManager** > > ```typescript theme={"theme":"css-variables"} > const adminSigner = await parseKeypairFile('/path/to/admin.json'); > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > ``` > > **3. Build the asset config** > > ```typescript theme={"theme":"css-variables"} > const assetConfig = new AssetReserveConfig({ > mint: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), // USDC > mintTokenProgram: TOKEN_PROGRAM_ADDRESS, > tokenName: 'USDC', > mintDecimals: 6, > priceFeed: { > scopePriceConfigAddress: address(''), > scopeChain: [0], // Scope chain indices > scopeTwapChain: [52], > }, > loanToValuePct: 90, > liquidationThresholdPct: 92, > borrowRateCurve: { > points: [ > { utilizationRateBps: 0, borrowRateBps: 0 }, > { utilizationRateBps: 7000, borrowRateBps: 400 }, > { utilizationRateBps: 9000, borrowRateBps: 1500 }, > { utilizationRateBps: 10000, borrowRateBps: 5000 }, > // pad to 11 points by repeating the final point > { utilizationRateBps: 10000, borrowRateBps: 5000 }, > { utilizationRateBps: 10000, borrowRateBps: 5000 }, > { utilizationRateBps: 10000, borrowRateBps: 5000 }, > { utilizationRateBps: 10000, borrowRateBps: 5000 }, > { utilizationRateBps: 10000, borrowRateBps: 5000 }, > { utilizationRateBps: 10000, borrowRateBps: 5000 }, > { utilizationRateBps: 10000, borrowRateBps: 5000 }, > ], > }, > depositLimit: new Decimal(1_000_000), > borrowLimit: new Decimal(900_000), > }); > ``` > > For full control over every reserve field (including elevation-groups, fixed-term, withdrawal caps, etc.), use `AssetReserveConfigCli` and load a `ReserveConfig` JSON object: > > ```typescript theme={"theme":"css-variables"} > import { AssetReserveConfigCli } from '@kamino-finance/klend-sdk'; > import { ReserveConfig } from '@kamino-finance/klend-sdk/dist/@codegen/klend/types'; > > const reserveConfig: ReserveConfig = /* fully-populated ReserveConfig object */; > const assetConfig = new AssetReserveConfigCli( > address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), > TOKEN_PROGRAM_ADDRESS, > reserveConfig, > ); > ``` > > **4. Generate the reserve keypair and admin liquidity source** > > ```typescript theme={"theme":"css-variables"} > const reserveKeypair = await generateKeyPairSigner(); > > // The admin's associated token account for the asset (used to seed the reserve at init) > const [adminLiquiditySource] = await findAssociatedTokenPda({ > mint: assetConfig.mint, > owner: adminSigner.address, > tokenProgram: TOKEN_PROGRAM_ADDRESS, > }); > ``` > > **5. Build and submit the transactions** > > `addAssetToMarketIxs` returns two batches of instructions — one for creating the reserve account, another for applying the config. Submit them in order. > > ```typescript theme={"theme":"css-variables"} > const { createReserveIxs, configUpdateIxs } = await kaminoManager.addAssetToMarketIxs({ > admin: adminSigner, > adminLiquiditySource, > marketAddress: address(''), > assetConfig, > reserveKeypair, > }); > > async function buildAndSendTx(ixs: any[]) { > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), > (tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > (tx) => appendTransactionMessageInstructions(ixs, tx) > ) > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > }); > } > > // Step 1: create the reserve account > await buildAndSendTx(createReserveIxs); > > // Step 2: apply the config (may be split across multiple transactions for size reasons) > for (const { ixs } of configUpdateIxs) { > await buildAndSendTx(ixs); > } > > console.log('Reserve created:', reserveKeypair.address); > ``` > > `configUpdateIxs` is an array because a full config update may exceed a single transaction's size limit; the SDK splits it into chunks. Submit each chunk in order. > > ### Cloning an existing reserve config via SDK > > To spawn a sibling reserve with the same parameters as an existing one, fetch the source's config and pass it through `AssetReserveConfigCli`: > > ```typescript theme={"theme":"css-variables"} > import { Reserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > > const sourceReserve = await Reserve.fetch(rpc, address('')); > if (!sourceReserve) throw new Error('Reserve not found'); > > const clonedConfig = sourceReserve.config; > // Update tokenInfo and any reserve-specific fields before applying > clonedConfig.tokenInfo.name = encodeTokenName('NEW_TOKEN'); > clonedConfig.tokenInfo.scopeConfiguration.priceFeed = address(''); > > const newAssetConfig = new AssetReserveConfigCli( > address(''), > TOKEN_PROGRAM_ADDRESS, > clonedConfig, > ); > // Use newAssetConfig in addAssetToMarketIxs > ``` > [tab] API > > > [!NOTE] > > > > **Adding reserves is not available via the REST API.** The Kamino API supports reading reserve metrics and historical data; reserve creation and configuration is an admin operation available through the **SDK** or **Kamino CLI**. > > To add a reserve, use the **SDK** or **Kamino CLI** tabs. > > For reading reserve data after creation, see [Read market data](/curators/markets/market-data) and the [API reference](/build/api-reference/introduction). > [tab] Kamino CLI > > ## Add a reserve via CLI > > A reserve is added with a single CLI call referencing a JSON config file. > > ### The reserve config file > > The reserve config is a JSON file authored once per reserve. Fields use camelCase in JSON; the on-chain Rust struct uses snake_case. The CLI handles the conversion. > > A reference config ships with klend-sdk: > > [ klend-sdk/configs/reserve_config_example.json](https://github.com/Kamino-Finance/klend-sdk/blob/master/configs/reserve_config_example.json) > > > [!WARNING] > > > > The example file may contain legacy fields that the program ignores (`assetTier`, `multiplierSideBoost`, `multiplierTagBoost`). Treat them as no-ops; the canonical schema is in the [Reserve config reference](/curators/markets/reserve-parameters). > > A minimum viable reserve config: > > ```json theme={"theme":"css-variables"} > { > "status": 0, > "loanToValuePct": 65, > "liquidationThresholdPct": 75, > "minLiquidationBonusBps": 500, > "maxLiquidationBonusBps": 1000, > "badDebtLiquidationBonusBps": 99, > "borrowFactorPct": 100, > "depositLimit": "1000000000000", > "borrowLimit": "900000000000", > "fees": { > "borrowFee": "0", > "flashLoanFee": "0" > }, > "borrowRateCurve": { > "points": [ > { "utilizationRateBps": 0, "borrowRateBps": 0 }, > { "utilizationRateBps": 7000, "borrowRateBps": 500 }, > { "utilizationRateBps": 8500, "borrowRateBps": 1000 }, > { "utilizationRateBps": 10000, "borrowRateBps": 5000 } > ] > }, > "tokenInfo": { > "name": "USDC", > "maxAgePriceSeconds": 120, > "maxAgeTwapSeconds": 240, > "maxTwapDivergenceBps": 4050, > "scopeConfiguration": { > "priceFeed": "", > "priceChain": [0, 65535, 65535, 65535], > "twapChain": [52, 65535, 65535, 65535] > } > }, > "depositWithdrawalCap": { > "configCapacity": "0", > "configIntervalLengthSeconds": "86400" > }, > "debtWithdrawalCap": { > "configCapacity": "0", > "configIntervalLengthSeconds": "86400" > } > } > ``` > > ### Add the reserve > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager add-asset-to-market \ > --market \ > --mint \ > --mint-program-id TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA \ > --reserve-config-path ./configs/my_reserve_config.json \ > --mode execute > ``` > > For a Token-2022 asset, replace the mint program ID: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager add-asset-to-market \ > --market \ > --mint \ > --mint-program-id TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb \ > --reserve-config-path ./configs/my_reserve_config.json \ > --mode execute > ``` > > The CLI prints the new reserve address. Repeat for each additional asset. > > ### Cloning an existing reserve config > > To spawn a sibling reserve with similar parameters: > > ```bash theme={"theme":"css-variables"} > # 1. Download the source reserve's config > yarn kamino-manager download-reserve-config \ > --reserve \ > --output ./configs/cloned_reserve.json > > # 2. Edit ./configs/cloned_reserve.json — update tokenInfo.name and the oracle config > > # 3. Add the new reserve using the cloned file > yarn kamino-manager add-asset-to-market \ > --market \ > --mint \ > --mint-program-id \ > --reserve-config-path ./configs/cloned_reserve.json \ > --mode execute > ``` ## What the program does on-chain 1. Allocates a new `Reserve` zero-copy account 2. Initializes its `ReserveConfig` from your input 3. Sets `Reserve.lending_market` to your market address 4. Validates that the oracle accounts referenced in `tokenInfo` actually match the configured pubkeys 5. Initializes the reserve's `liquidity` and `collateral` substructures (zero balances) 6. Initializes the reserve's `WithdrawQueue` (empty) The reserve immediately accepts deposits if `status: 0` (Active) and `depositLimit > 0`. Borrows additionally require `borrowLimit > 0`. ## Verify After creation: | Channel | How | | - | - | | SDK | `Reserve.fetch(rpc, reserveAddress)` and inspect `config` | | CLI | `yarn kamino-manager download-reserve-config --reserve ` | | API | `GET https://api.kamino.finance/kamino-market//reserves/metrics` | Confirm: * `status: 0` * `tokenInfo.scopeConfiguration.priceFeed` is populated * `borrowRateCurve.points[0].utilizationRateBps == 0` * `depositLimit > 0` and `borrowLimit > 0` if you want both directions usable ## Common errors | Error | Cause | | - | - | | `InvalidOracleConfig` | The oracle account in `tokenInfo` doesn't match the on-chain account passed to the instruction. Run `get-oracle-mappings`. | | `InvalidScopePriceAccount` | Same as above, oracle-specific. | | `InvalidTwapConfig` | TWAP enabled (`maxTwapDivergenceBps > 0`) but `maxAgeTwapSeconds == 0`, or the configured oracle source has no TWAP. | | `Reserve already exists for this mint` | This (mint, market) pair already has a reserve. Use `update-reserve-config` instead. | ## What's next > [card] [Configure oracles](/curators/markets/configuring-oracles) > > Pick the right oracle source and set TWAP and staleness guards. > [card] [Risk parameters](/curators/markets/risk-parameters) > > Choose LTV, thresholds, IR curves, and caps for the asset. # Auto-Deleverage Source: https://docs.kamino.com/curators/markets/auto-deleverage Margin-call grace window with a ramped liquidation bonus over time Auto-deleverage is a softer alternative to immediate liquidation. When a position crosses an unhealthy threshold, the curator (or an off-chain bot) marks it for deleveraging: the borrower receives a grace period to self-deleverage, and only after the grace period elapses does liquidation become available — at a ramped bonus that grows over time. This is a niche feature most curators leave disabled. Standard [Liquidations](/curators/markets/liquidations) (immediate, threshold-triggered) are sufficient for most markets. Enable auto-deleverage when you specifically want a borrower-friendly margin-call window before liquidations open up. ## When this is useful | Curator profile | Recommendation | | - | - | | Public market with retail borrowers | Optional. The grace period is borrower-friendly but adds operational complexity | | Institutional / fixed-term market | Skip. Institutional borrowers prefer immediate, predictable liquidation behavior | | Stable-only / eMode-heavy market | Skip. Correlated-asset liquidations are small and fast | | Newly-listed volatile asset | Optional. If enabled, use a shorter `margin_call_period` (e.g., 4 hours) | ## Market-level enablement | Field | What it does | | - | - | | `autodeleverage_enabled` | Master switch. `1` enables auto-deleverage on the market | | `individual_autodeleverage_margin_call_period_secs` | Default grace period (seconds) between when a position is margin-called and when liquidation opens up. `86400` = 24 hours | | `insolvency_risk_unhealthy_ltv_pct` | LTV at which a position is considered to be in insolvency risk territory and may be marked for auto-deleverage. Default `100` | ## Reserve-level config | Field | What it does | | - | - | | `autodeleverage_enabled` | Per-reserve enablement. Both market and reserve must be `1` for auto-deleverage to apply to positions involving this reserve | | `deleveraging_margin_call_period_secs` | Per-reserve override for the margin-call period. `0` falls back to the market-level value | | `deleveraging_threshold_decrease_bps_per_day` | The position's effective liquidation threshold drops by this many bps per day after margin call. Allows liquidators in over time | | `deleveraging_bonus_increase_bps_per_day` | Liquidator bonus rises by this many bps per day after margin call. Compounds the incentive over time | | `min_deleveraging_bonus_bps` | Floor on the deleveraging-specific bonus | > [tab] SDK > > ## Configure auto-deleverage via SDK > > Auto-deleverage is enabled through standard market and reserve config updates. > > ### Enable on the market > > ```typescript theme={"theme":"css-variables"} > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { address } from '@solana/kit'; > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > > const newLendingMarket = { ...marketState }; > newLendingMarket.autodeleverageEnabled = 1; > newLendingMarket.individualAutodeleverageMarginCallPeriodSecs = 86_400n; // 24 hours > newLendingMarket.insolvencyRiskUnhealthyLtvPct = 100; > > const ixs = kaminoManager.updateLendingMarketIxs(adminSigner, marketWithAddress, newLendingMarket); > // submit each ix in order > ``` > > ### Enable on a reserve > > ```typescript theme={"theme":"css-variables"} > import { Reserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > > const reserve = await Reserve.fetch(rpc, reserveAddress); > if (!reserve) throw new Error('Reserve not found'); > > const newConfig = { ...reserve.config }; > newConfig.autodeleverageEnabled = 1; > newConfig.deleveragingMarginCallPeriodSecs = 0n; // 0 = use market default > newConfig.deleveragingThresholdDecreaseBpsPerDay = 24n; // 0.24% per day > newConfig.deleveragingBonusIncreaseBpsPerDay = 100n; // 1% per day > newConfig.minDeleveragingBonusBps = 0; > > const updateIxs = await kaminoManager.updateReserveIxs( > adminSigner, > marketWithAddress, > reserveAddress, > newConfig, > ); > // submit each chunk in order > ``` > > ### Marking a position for deleveraging > > The `markObligationForDeleveraging` instruction is exposed via the SDK codegen. An off-chain monitor (or any wallet) can submit it once a position breaches `insolvency_risk_unhealthy_ltv_pct`. > > ```typescript theme={"theme":"css-variables"} > import { markObligationForDeleveraging } from '@kamino-finance/klend-sdk/dist/@codegen/klend/instructions'; > import { PROGRAM_ID } from '@kamino-finance/klend-sdk'; > > // Build args and accounts per the instruction's signature, then: > const ix = markObligationForDeleveraging(args, accounts, PROGRAM_ID); > // Sign with the marker's wallet and submit > ``` > > For full args / accounts shapes, see `klend-sdk/src/@codegen/klend/instructions/markObligationForDeleveraging.ts`. > [tab] API > > > [!NOTE] > > > > **Configuring auto-deleverage is not available via the REST API.** The flags live on `LendingMarket` and `ReserveConfig` and are flipped through the **SDK** or **Kamino CLI**. The `markObligationForDeleveraging` instruction is a permissionless on-chain call; off-chain monitors typically submit it directly. > > To monitor positions that have entered or are eligible for the auto-deleverage state, query the on-chain obligation accounts directly. See [Read market data](/curators/markets/market-data). > [tab] Kamino CLI > > ## Configure auto-deleverage via CLI > > Both the market-level and reserve-level fields are part of the standard config schemas. Apply via `update-lending-market-from-config` and `update-reserve-config`. > > ### Market-level > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-lending-market-config \ > --lending-market > > # Edit ./configs//market-.json — set: > # "autodeleverage_enabled": 1 > # "individual_autodeleverage_margin_call_period_secs": 86400 > # "insolvency_risk_unhealthy_ltv_pct": 100 > > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode multisig \ > --multisig > ``` > > ### Reserve-level > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-reserve-config \ > --reserve \ > --output ./configs/.json > > # Edit ./configs/.json — set: > # "autodeleverage_enabled": 1 > # "deleveraging_margin_call_period_secs": 0 > # "deleveraging_threshold_decrease_bps_per_day": 24 > # "deleveraging_bonus_increase_bps_per_day": 100 > # "min_deleveraging_bonus_bps": 0 > > yarn kamino-manager update-reserve-config \ > --reserve \ > --reserve-config-path ./configs/.json \ > --mode multisig \ > --multisig > ``` ## The lifecycle When a position's LTV crosses `insolvency_risk_unhealthy_ltv_pct`, an off-chain monitor (anyone, typically a bot) calls `mark-obligation-for-deleveraging`. The position is now margin-called and the program records a timestamp. Standard liquidation is gated by the auto-deleverage state from this point forward. For `deleveraging_margin_call_period_secs` (or the market default if the reserve doesn't override), the borrower has a grace window to repay or add collateral. Once grace ends, the deleveraging state begins to ramp: the effective liquidation threshold drops by `deleveraging_threshold_decrease_bps_per_day` and the liquidator bonus rises by `deleveraging_bonus_increase_bps_per_day`. Each elapsed day makes the position progressively easier to liquidate and progressively more profitable to clear, until a liquidator finally executes. ## Tuning the ramp Two reserve-level fields shape how aggressively the deleveraging state ramps after grace ends. | Field | Higher value means | | - | - | | `deleveraging_threshold_decrease_bps_per_day` | Liquidation threshold drops faster, opening up the position to liquidators sooner | | `deleveraging_bonus_increase_bps_per_day` | Liquidator bonus grows faster, paying executors more for clearing the position | Reference settings: | Risk profile | threshold_decrease | bonus_increase | margin_call_period | | - | - | - | - | | Borrower-friendly | 12 bps/day | 50 bps/day | 48 hours | | Standard | 24 bps/day | 100 bps/day | 24 hours | | Aggressive (volatile asset) | 50 bps/day | 200 bps/day | 4 hours | ## Off-chain infrastructure Auto-deleverage is useful in proportion to the off-chain monitoring around it. A typical setup: * **Position monitor**: an off-chain service watches `insolvency_risk_unhealthy_ltv_pct` breaches and submits `mark-obligation-for-deleveraging` * **Borrower notification**: when a position is marked, notify the borrower (email / push / wallet message) so they can react inside the grace window * **Liquidator coordination**: standard liquidator infrastructure picks up margin-called positions once the grace window expires For curator markets, you either rely on Kamino's existing infrastructure (for whitelisted markets) or run your own. ## Reference * [Liquidations](/curators/markets/liquidations) — base liquidation mechanics * [Reserve config reference](/curators/markets/reserve-parameters) — `autodeleverage_enabled`, `deleveraging_*` fields * [Market config reference](/curators/markets/market-config-reference) — `autodeleverage_enabled`, `individual_autodeleverage_margin_call_period_secs`, `insolvency_risk_unhealthy_ltv_pct` # Borrow Orders Source: https://docs.kamino.com/curators/markets/borrow-orders Peer-to-peer fixed-rate matching between borrowers and lenders Borrow orders let a borrower place a limit-style order specifying the rate they're willing to pay, the term, and the size — lenders then fill it directly, bypassing the IR curve. They are most useful on fixed-term reserves where pricing is set by direct counterparty matching. When a borrow order is filled, the matched debt is locked in at the agreed rate for the agreed term. The fill creates a normal fixed-term position; from that point forward, the position behaves like any other fixed-term borrow on the reserve. ## Market-level enablement | Field | What it does | | - | - | | `borrow_order_creation_enabled` | If `1`, borrowers can place new orders | | `borrow_order_execution_enabled` | If `1`, lenders can fill placed orders | | `min_borrow_order_fill_value` | Minimum USD value (scaled fraction) for any single fill. Applies both at order placement and on partial fills | A typical `min_borrow_order_fill_value` is large enough to make fills economically meaningful (e.g., \$50–\$1,000 equivalent). Set it to filter out dust orders that would crowd the orderbook. > [tab] SDK > > ## Enable borrow orders via SDK > > Curator-side: flip the market flags via `updateLendingMarketIxs`. End-user-side: place orders via the `setBorrowOrder` instruction; lenders fill via `fillBorrowOrder`. > > ### Curator: enable on the market > > ```typescript theme={"theme":"css-variables"} > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { address } from '@solana/kit'; > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > > const newLendingMarket = { ...marketState }; > newLendingMarket.borrowOrderCreationEnabled = 1; > newLendingMarket.borrowOrderExecutionEnabled = 1; > newLendingMarket.minBorrowOrderFillValue = 50_000n; // adjust per asset > > const ixs = kaminoManager.updateLendingMarketIxs(adminSigner, marketWithAddress, newLendingMarket); > // submit each ix in order > ``` > > ### Borrower: place an order > > The SDK exposes the raw `setBorrowOrder` instruction builder via the codegen module. Build the instruction with the order parameters and submit it from the borrower's wallet. > > ```typescript theme={"theme":"css-variables"} > import { setBorrowOrder } from '@kamino-finance/klend-sdk/dist/@codegen/klend/instructions'; > > // Build args and accounts per the instruction's signature, then: > const ix = setBorrowOrder(args, accounts, PROGRAM_ID); > // Sign with the borrower's wallet and submit > ``` > > ### Lender: fill an order > > ```typescript theme={"theme":"css-variables"} > import { fillBorrowOrder } from '@kamino-finance/klend-sdk/dist/@codegen/klend/instructions'; > > const ix = fillBorrowOrder(args, accounts, PROGRAM_ID); > // Sign with the lender's wallet and submit > ``` > > For full args / accounts shapes, see the auto-generated source at `klend-sdk/src/@codegen/klend/instructions/setBorrowOrder.ts` and `fillBorrowOrder.ts`. > [tab] API > > > [!NOTE] > > > > **Configuring borrow orders is not available via the REST API.** The curator-side flags live on `LendingMarket` and are flipped through the **SDK** or **Kamino CLI**. User-facing order creation and filling happen on-chain via the program's instructions. > > To configure borrow orders, use the **SDK** or **Kamino CLI** tabs. > > Live order data may be surfaced through Kamino's indexer / API for whitelisted markets. For non-whitelisted curator markets, run your own indexer. > [tab] Kamino CLI > > ## Enable borrow orders via CLI > > ```bash theme={"theme":"css-variables"} > # 1. Download > yarn kamino-manager download-lending-market-config \ > --lending-market > > # 2. Edit ./configs//market-.json — set: > # "borrow_order_creation_enabled": 1 > # "borrow_order_execution_enabled": 1 > # "min_borrow_order_fill_value": "" > > # 3. Inspect > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode inspect > > # 4. Apply > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode multisig \ > --multisig > ``` > > User-side order creation and filling are not currently exposed through the kamino-manager CLI; users place orders via the Kamino webapp or via SDK-built transactions. ## The order itself A borrow order is stored on the borrower's obligation account. Each order specifies: | Field | What it does | | - | - | | `remaining_debt_amount` | The principal still seeking a fill. Decreases as partial fills happen | | `max_borrow_rate_bps` | The highest interest rate (bps) the borrower will accept. A lender can fill at any rate ≤ this value | | `min_debt_term_seconds` | The minimum term (seconds) the borrower will accept. Lenders' fills must use a fixed-term reserve with `debt_term_seconds >= min_debt_term_seconds` | | `fillable_until_timestamp` | Order expires after this timestamp | | `enable_auto_rollover_on_filled_borrows` | If `1`, filled borrows from this order auto-roll on maturity (subject to market-level rollover settings) | **Hard limit**: each obligation can hold **one open borrow order at a time**. This is a deliberate business-logic constraint enforced by the program; it keeps the orderbook clean and the matching logic simple. ## The matching flow The borrower calls `set-borrow-order` on their obligation, specifying the parameters above. At this stage no target reserve is named: the order is a pure expression of "what I'm willing to take" — max rate, min term, expiry, size. A lender (or filler bot, or vault) finds the order, picks a fixed-term reserve whose `debt_term_seconds` and current borrow rate sit inside the order's `min_debt_term_seconds` and `max_borrow_rate_bps` bounds, and calls `fill-borrow-order` referencing the borrower's obligation, the chosen reserve, and the amount to fill. The program verifies expiry, term, rate, and fill-size constraints; on success, principal flows from the reserve to the borrower's debt position with the matched fixed term. The order's `remaining_debt_amount` decreases by the filled size. When it reaches zero, the order closes. The borrower can also cancel the order at any time, and the order is automatically void after `fillable_until_timestamp` passes. ## Three liquidity flows that fill orders | Flow | Source of liquidity | | - | - | | **Repaid liquidity matching** | Repayments into a fixed-term reserve free up liquidity. Bots monitor and fill outstanding borrow orders against that reserve | | **Vault-driven fills** | A Kamino vault sitting on top can route deposits into a fixed-term reserve to fill matching orders, capturing the rate as yield for the vault's depositors | | **Direct seeding** | A privileged lender deposits directly into a fixed-term reserve. The deposit sits as available liquidity until a borrow order fills it | ## Cancelling an order A borrower can cancel their open order at any time (subject to no in-flight partial fill). Cancellation closes the order without affecting the borrows that have already been filled — those positions persist as normal fixed-term debt. ## Interaction with obligation ownership transfer When a borrower has an open borrow order, transferring obligation ownership has a constraint: the order's debt destination is tied to the original owner's authority. If the new owner accepts the obligation while an order is open, the order becomes unfillable. **Recommended flow**: cancel any open borrow orders before initiating an obligation transfer. See [Obligation ownership transfer](/curators/markets/obligation-ownership-transfer). ## Off-chain infrastructure Borrow orders are useful in proportion to the off-chain matching infrastructure around them. A typical setup: * **Order indexer**: an off-chain service watches `set-borrow-order` events and maintains an orderbook view per reserve * **Filler bot**: a service that detects fillable orders and submits `fill-borrow-order` transactions * **UI**: the borrower's UI shows the orderbook and lets them place / cancel orders Curators running their own market typically rely on Kamino's existing infrastructure (for whitelisted markets) or build their own around the on-chain primitives. ## Common errors | Error | Cause | | - | - | | `BorrowOrderCreationDisabled` | `borrow_order_creation_enabled = 0`. Enable | | `BorrowOrderExecutionDisabled` | `borrow_order_execution_enabled = 0`. Enable | | `BorrowOrderAlreadyExists` | The obligation already has an open order. Cancel the existing one first | | `BorrowOrderFillValueTooSmall` | Fill amount is below `min_borrow_order_fill_value` | | `BorrowOrderExpired` | `now > fillable_until_timestamp`. Borrower must place a new order | | `BorrowOrderTermNotAcceptable` | Lender's chosen reserve has `debt_term_seconds < order.min_debt_term_seconds` | | `BorrowOrderRateNotAcceptable` | Fill rate exceeds `max_borrow_rate_bps` | ## Reference * [Market config reference](/curators/markets/market-config-reference) — `borrow_order_*` flags and `min_borrow_order_fill_value` * [Fixed rate reserves](/curators/markets/fixed-rate-reserves) — the underlying lending mechanics * [Obligation ownership transfer](/curators/markets/obligation-ownership-transfer) — interaction with open orders # CLI Command Index Source: https://docs.kamino.com/curators/markets/cli-command-index Quick lookup of every market-related kamino-manager CLI command A flat reference of every `kamino-manager` command that touches a market or its reserves. Each row links to the workflow page that uses it. For full flag detail on any command, see the [Market Operations CLI page](/build/cli/market-operations). For installation and `.env` setup, see [CLI installation & setup](/build/cli/installation-setup). ## Market lifecycle | Command | Purpose | Workflow page | | - | - | - | | `create-market` | Initialize a new `LendingMarket` account | [Create a market](/curators/markets/creating-a-market) | | `update-lending-market-name` | Rename the market | [Market settings](/curators/markets/market-settings) | | `update-lending-market-from-config` | Apply a full market config update from JSON | [Market settings](/curators/markets/market-settings) | | `update-lending-market-owner` | Promote `lending_market_owner_cached` to active owner | [Transfer to multisig](/curators/markets/transfer-to-multisig) | | `download-lending-market-config` | Export the current market config to JSON | [Market settings](/curators/markets/market-settings) | | `download-lending-market-config-and-all-reserves-configs` | Export market + all reserves in one call | [Market settings](/curators/markets/market-settings) | | `get-market-or-vault-admin-info` | Query admin metadata (owner, cached owner, council) | [Market settings](/curators/markets/market-settings) | ## Reserve lifecycle | Command | Purpose | Workflow page | | - | - | - | | `add-asset-to-market` | Add a new reserve to the market with a config | [Add reserves](/curators/markets/adding-reserves) | | `update-reserve-config` | Apply a full reserve config update from JSON | [Updating reserves](/curators/markets/reserve-management) | | `update-reserve-config-debt-cap` | Focused update of just the borrow cap | [Updating reserves](/curators/markets/reserve-management) | | `download-reserve-config` | Export the current reserve config to JSON | [Updating reserves](/curators/markets/reserve-management) | | `simulate-reserve-apy` | Compute live supply and borrow APY for a reserve | [Read market data](/curators/markets/market-data) | ## Oracles | Command | Purpose | Workflow page | | - | - | - | | `get-oracle-mappings` | List Scope oracle addresses for known mints | [Configure oracles](/curators/markets/configuring-oracles) | ## Farms Farm initialization happens through the KFarms tooling and is bundled into `add-asset-to-market` for the initial setup. Read-side queries: | Command | Purpose | Workflow page | | - | - | - | | `get-reserve-farms-apy` | Reward APY for a reserve's collateral and debt farms | [Farms & rewards](/curators/markets/farms-and-rewards) | For farm initialization, funding, and emission configuration, use the KFarms CLI and SDK. ## Execution modes Every command supports four `--mode` values: | Mode | What it does | | - | - | | `inspect` | Prints a Solana Explorer URL where you can simulate the transaction | | `simulate` | Runs simulation server-side and prints the result | | `execute` | Signs with the admin keypair and lands the transaction | | `multisig` | Outputs a base58-encoded transaction for submission to a Squads proposal | Multisig mode requires `--multisig ` to identify the multisig the proposal targets. ## Network selection | Flag | Target | | - | - | | (none) | Mainnet (default) | | `--staging` | Staging program on Solana mainnet | | `--devnet` | Solana devnet | ## Vault commands The kamino-manager CLI also exposes a large set of vault-related commands (e.g., `create-vault`, `update-vault-config`, `update-vault-reserve-allocation`, etc.). These are documented under [Create a vault](/curators/vaults/guides/create-a-vault) and the [Vault Operations CLI page](/build/cli/vault-operations). ## Reference * [Market Operations CLI](/build/cli/market-operations) — full flag detail for every command * [CLI installation & setup](/build/cli/installation-setup) — `.env`, keypair, RPC * [Updating reserves](/curators/markets/reserve-management) — the standard workflow * [Market settings](/curators/markets/market-settings) — market-level workflow # Configure Oracles Source: https://docs.kamino.com/curators/markets/configuring-oracles Wire each reserve to a price feed with the right TWAP and staleness guards Every reserve needs a valid oracle. Oracle configuration lives inside the reserve config under `tokenInfo`. Reserves are priced through **Scope**, Kamino's price aggregator. ## How pricing works Scope combines provider feeds (**Chainlink** and **Pyth Pro**) into a single, manipulation-resistant chain of indices, and exposes [custom oracle types](/curators/markets/scope-oracle-types) for fixed-income, pegged, multi-source, and LST assets. You wire a reserve to a Scope feed by setting `scopeConfiguration` in `tokenInfo`: the price chain, TWAP chain, and guards. For an asset that isn't in Scope yet, coordinate with the Kamino team to add it before listing. ## Required tokenInfo fields | Field | Type | What it does | | - | - | - | | `name` | string (≤32 bytes UTF-8) | Asset symbol | | `maxAgePriceSeconds` | u64 | Reject the spot price if older than this many seconds | | `maxAgeTwapSeconds` | u64 | Reject the TWAP if older than this many seconds. Required if TWAP is enabled | | `maxTwapDivergenceBps` | u64 | Maximum divergence between spot and TWAP in basis points. `0` disables the guard | | `heuristic` | `{ lower, upper, exp }` | Sanity bounds. Reject prices outside `[lower * 10^exp, upper * 10^exp]`. All zeros disables | | `blockPriceUsage` | `0` or `1` | If `1`, the reserve is configured but the program rejects any operation needing a price (emergency switch) | Plus the Scope feed: * `scopeConfiguration` — Scope feed pubkey + price chain + TWAP chain > [tab] SDK > > ## Update oracle config via SDK > > The most direct path for changing just the Scope oracle on an existing reserve is `kaminoManager.updateReserveScopeOracleConfigurationIxs`. For broader reserve updates that include oracle changes, use `updateReserveIxs` with a full `ReserveConfig`. > > **1. Initialize KaminoManager and fetch the reserve** > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket, Reserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > > const adminSigner = await parseKeypairFile('/path/to/admin.json'); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketAddress = address(''); > const reserveAddress = address(''); > > const market = await LendingMarket.fetch(rpc, marketAddress); > if (!market) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: market }; > ``` > > **2. Update Scope oracle configuration** > > ```typescript theme={"theme":"css-variables"} > const updateIxs = await kaminoManager.updateReserveScopeOracleConfigurationIxs( > adminSigner, > marketWithAddress, > reserveAddress, > { > scopePriceConfigAddress: address('3NJYftD5sjVfxSnUdZ1wVML8f3aC6mp1CXCL6L7TnU8C'), > scopeChain: [0, 65535, 65535, 65535], > scopeTwapChain: [52, 65535, 65535, 65535], > }, > ); > > async function buildAndSendTx(ixs: any[]) { > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), > (tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > (tx) => appendTransactionMessageInstructions(ixs, tx) > ) > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > }); > } > > for (const { ixs } of updateIxs) { > await buildAndSendTx(ixs); > } > ``` > > `65535` (`u16::MAX`) is the unused-slot sentinel. A single-hop Scope chain uses `[N, 65535, 65535, 65535]`. > > **3. Adjusting the TWAP / staleness guards** > > To change the staleness and TWAP guards, fetch the reserve's full config, mutate the relevant `tokenInfo` fields, and apply via `updateReserveIxs`: > > ```typescript theme={"theme":"css-variables"} > const reserve = await Reserve.fetch(rpc, reserveAddress); > if (!reserve) throw new Error('Reserve not found'); > > const newConfig = { ...reserve.config }; > newConfig.tokenInfo = { > ...reserve.config.tokenInfo, > maxAgePriceSeconds: 120n, > maxAgeTwapSeconds: 240n, > maxTwapDivergenceBps: 4050n, > }; > > const updateIxs = await kaminoManager.updateReserveIxs( > adminSigner, > marketWithAddress, > reserveAddress, > newConfig, > ); > > for (const { ixs } of updateIxs) { > await buildAndSendTx(ixs); > } > ``` > > ### Looking up oracle IDs > > List every named slot on a Scope feed with its index, then use the index of your asset in the reserve's oracle config. > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc } from '@solana/kit'; > import { Scope, SCOPE_MAINNET_HUBBLE_FEED } from '@kamino-finance/scope-sdk'; > import { fetchTokenMetadatas } from '@kamino-finance/scope-sdk/dist/@codegen/scope/accounts'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const scope = new Scope('mainnet-beta', rpc); > const feed = { config: SCOPE_MAINNET_HUBBLE_FEED.configuration }; > const NONE = 65535; > > const [, config] = await scope.getSingleFeedConfiguration(feed); > const mappings = await scope.getOracleMappings(feed); > const { data: metadatas } = await fetchTokenMetadatas(rpc, config.tokensMetadata); > > mappings.priceTypes.forEach((_, slot) => { > const [entry] = Scope.getChainMetadataSync(mappings, metadatas, [slot, NONE, NONE, NONE]); > if (entry?.name) console.log(slot, entry.name); > }); > ``` > > > [!NOTE] > > > > This reads the Hubble feed. To read another Scope feed, replace `SCOPE_MAINNET_HUBBLE_FEED.configuration` with that feed's configuration address. > > Or call the kamino-manager CLI's `get-oracle-mappings` command (next tab) to retrieve the canonical IDs. > [tab] API > > > [!NOTE] > > > > **Oracle configuration is not available via the REST API.** The API serves read access to oracle-derived prices and reserve metrics; oracle configuration is an admin operation available through the **SDK** or **Kamino CLI**. > > To update a reserve's oracle config, use the **SDK** or **Kamino CLI** tabs. > > To read current price data via API, see the [API reference](/build/api-reference/introduction). > [tab] Kamino CLI > > ## Configure oracles via CLI > > Oracle configuration sits inside the reserve config JSON under the `tokenInfo` key. Edit it like any other reserve field, then apply via `update-reserve-config`. For a focused command that only updates the Scope oracle, use the SDK (no dedicated CLI command exists). > > ### Find the right oracle IDs > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager get-oracle-mappings > ``` > > Returns the Scope feed pubkeys and indices that klend supports for known mints. Copy the IDs for your asset into the reserve config. > > If your asset isn't in `get-oracle-mappings`, coordinate with the Kamino team to add a Scope feed for it before listing. > > ### Scope configuration > > ```json theme={"theme":"css-variables"} > "tokenInfo": { > "name": "USDC", > "maxAgePriceSeconds": 120, > "maxAgeTwapSeconds": 240, > "maxTwapDivergenceBps": 4050, > "scopeConfiguration": { > "priceFeed": "3NJYftD5sjVfxSnUdZ1wVML8f3aC6mp1CXCL6L7TnU8C", > "priceChain": [0, 65535, 65535, 65535], > "twapChain": [52, 65535, 65535, 65535] > } > } > ``` > > | Field | What it is | > | - | - | > | `priceFeed` | The Scope `OraclePrices` account pubkey | > | `priceChain` | Up to four `u16` indices into the Scope feed; the first non-`65535` entry is the primary price | > | `twapChain` | Same shape, for the TWAP indices | > > `65535` is the sentinel for "unused slot." A single-hop price uses `[N, 65535, 65535, 65535]`. > > ### Apply the update > > ```bash theme={"theme":"css-variables"} > # Download the current reserve config > yarn kamino-manager download-reserve-config \ > --reserve \ > --output ./configs/.json > > # Edit ./configs/.json — update tokenInfo > > # Inspect the change > yarn kamino-manager update-reserve-config \ > --reserve \ > --reserve-config-path ./configs/.json \ > --mode inspect > > # Apply > yarn kamino-manager update-reserve-config \ > --reserve \ > --reserve-config-path ./configs/.json \ > --mode execute > ``` ## TWAP and staleness guards The two guards work together to reject manipulated or stale prices. | Guard | What it catches | | - | - | | `maxAgePriceSeconds` | Spot price older than this is rejected. Set to `120` for liquid assets, lower for high-stakes reserves | | `maxAgeTwapSeconds` | TWAP older than this is rejected. Typically 2–4× `maxAgePriceSeconds` | | `maxTwapDivergenceBps` | If spot deviates from TWAP by more than this, the price is rejected. Set to `4050` (≈40.5%) for volatile assets, lower for stables. `0` disables | If TWAP is enabled (`maxTwapDivergenceBps > 0`) the Scope feed must expose a TWAP chain. The on-chain validator returns `InvalidTwapConfig` if you enable the guard against a feed with no TWAP. ## Price heuristic The heuristic is an absolute price band: ```json theme={"theme":"css-variables"} "heuristic": { "lower": 9, "upper": 11, "exp": 1 } ``` With `exp: 1`, the price is accepted only when `0.9 ≤ price ≤ 1.1`. Useful for stables you expect to peg. Set all zeros to disable. ## Block price usage (emergency) `blockPriceUsage: 1` is an emergency switch: the reserve is configured normally but the program refuses any operation that needs the price. Use it when you need to halt a reserve immediately while preparing a real config update. ## Choosing for new assets | Asset type | Recommended setup | | - | - | | Major stablecoins (USDC, USDT, USDS) | Scope, with a tight heuristic and TWAP guard | | Major liquid assets (SOL, BTC, ETH) | Scope | | LSTs (mSOL, jitoSOL, INF, etc.) | Scope (uses LST → SOL → USD chain) | | Pegged or fixed-income assets | Scope [custom oracle types](/curators/markets/scope-oracle-types) (CappedFloored, DiscountToMaturity) | | Tokenized off-chain assets | Coordinate with the Kamino team to add to Scope | ## Reference * [Reserve config reference](/curators/markets/reserve-parameters) — every `tokenInfo` field documented * [Oracle architecture overview](/security/oracles) — Scope, price protection, manipulation resistance # Create a Market Source: https://docs.kamino.com/curators/markets/creating-a-market Initialize a new Kamino lending market A market is created by a single transaction. The transaction initializes a `LendingMarket` account on-chain with default settings and your wallet (or a multisig) as the owner. Reserves, oracles, and feature flags are configured in subsequent steps. The market is empty (no reserves) until you [add reserves](/curators/markets/adding-reserves), and cannot accept deposits or borrows until at least one reserve is active. > [tab] SDK > > ## Create a market via SDK > > Use `KaminoManager` from `@kamino-finance/klend-sdk` to build and submit the create-market instruction. > > **1. Import dependencies** > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > ``` > > **2. Initialize KaminoManager** > > ```typescript theme={"theme":"css-variables"} > const adminSigner = await parseKeypairFile('/path/to/admin.json'); > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > ``` > > > [!NOTE] > > > > Use a private RPC endpoint for production. Public RPCs are rate-limited. > > **3. Build the create-market instructions** > > ```typescript theme={"theme":"css-variables"} > const { market: marketSigner, ixs: createMarketIxs } = await kaminoManager.createMarketIxs({ > admin: adminSigner, > }); > > console.log('New market address:', marketSigner.address); > ``` > > `createMarketIxs` returns: > > * `market`: a `TransactionSigner` for the market account; its `address` is the new market's pubkey > * `ixs`: the instructions needed to create and initialize the market > > Save the `marketSigner.address` value — every subsequent operation references it. > > **4. Sign and send the transaction** > > ```typescript theme={"theme":"css-variables"} > const { value: latestBlockhash } = await rpc > .getLatestBlockhash({ commitment: 'finalized' }) > .send(); > > const transactionMessage = pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), > (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), > (tx) => appendTransactionMessageInstructions(createMarketIxs, tx) > ); > > const signedTransaction = await signTransactionMessageWithSigners(transactionMessage); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction, { > commitment: 'confirmed', > }); > > console.log('Market created:', marketSigner.address); > ``` > > The market signer (`marketSigner`) is automatically included as a signer because `KaminoManager.createMarketIxs` returns it as a `TransactionSigner`. > > ### Targeting staging or devnet > > Pass the staging or devnet program ID when constructing `KaminoManager`: > > ```typescript theme={"theme":"css-variables"} > import { STAGING_PROGRAM_ID } from '@kamino-finance/klend-sdk'; > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, STAGING_PROGRAM_ID); > ``` > > For devnet, point the RPC at `https://api.devnet.solana.com` and use the devnet program ID from your environment. > > ### Multisig from the start > > If you want the market owned by a multisig from inception, pass the multisig pubkey as a noop signer for `admin`: > > ```typescript theme={"theme":"css-variables"} > import { noopSigner, address } from '@kamino-finance/klend-sdk'; > > const multisigAdmin = noopSigner(address('')); > > const { market, ixs } = await kaminoManager.createMarketIxs({ > admin: multisigAdmin, > }); > > // Don't sign and send. Instead, encode the transaction as base58 and submit it > // as a Squads proposal. The multisig itself will sign and execute. > ``` > > For most curators, the simpler path is to create under a hot wallet, add reserves, validate, then [transfer to a multisig](/curators/markets/transfer-to-multisig). > [tab] API > > > [!NOTE] > > > > **Market creation is not available via the REST API.** The Kamino API supports reading market and reserve data and building user-facing deposit/borrow transactions. Market creation is an admin operation available through the **SDK** or **Kamino CLI**. > > To create a market programmatically, use the **SDK** or **Kamino CLI** tabs. > > For reading market data after creation, see [Read market data](/curators/markets/market-data) and the [API reference](/build/api-reference/introduction). > [tab] Kamino CLI > > ## Create a market via CLI > > A market is created by a single CLI call. The command initializes a `LendingMarket` account on-chain and prints the new market's address. > > > [!NOTE] > > > > Before running the command, complete the [CLI installation & setup](/build/cli/installation-setup). The CLI requires `ADMIN`, `RPC`, `KLEND_PROGRAM_ID_MAINNET`, and `KLEND_PROGRAM_ID_STAGING` in `.env`. > > ### Command > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager create-market --mode execute > ``` > > That's it. The market is created against mainnet by default. Save the address from the output. > > ### Network selection > > | Flag | Target | Notes | > | - | - | - | > | (no flag) | Mainnet | Production deployment | > | `--staging` | Staging program on Solana mainnet | Real prices, real oracles, isolated program ID | > | `--devnet` | Solana devnet | Fully isolated sandbox | > > ### Execution modes > > Every CLI command supports four `--mode` values. Use them to validate before committing. > > | Mode | What it does | > | - | - | > | `inspect` | Prints a Solana Explorer URL where you can simulate the transaction | > | `simulate` | Runs simulation server-side and prints the result | > | `execute` | Signs with the admin keypair and lands the transaction | > | `multisig` | Outputs a base58-encoded transaction for submission to a Squads proposal | > > A standard production rhythm is `inspect` → `execute` (or `multisig` for production-owned markets). > > ### Multisig from the start > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager create-market \ > --mode multisig \ > --multisig > ``` > > Submit the printed base58 transaction as a Squads proposal. The multisig owns the market once the proposal executes. ## What happens on-chain The instruction initializes a `LendingMarket` account with: * `lending_market_owner` set to your admin * `quote_currency` set to a default (override later via `update-lending-market-from-config`) * All feature flags (`borrow_disabled`, `emergency_mode`, `withdraw_ticket_*`, `borrow_order_*`, `obligation_order_*`, `autodeleverage_enabled`, `immutable`) initialized to `0` * All elevation groups empty * Default values for liquidation tunables and minimum deposit thresholds Every default is overridable post-creation via [Market settings](/curators/markets/market-settings). ## What's next > [card] [Add reserves](/curators/markets/adding-reserves) > > Add the first asset to your market with a reserve config. > [card] [Configure oracles](/curators/markets/configuring-oracles) > > Wire each reserve to a Scope price feed. ## Reference * [Market config reference](/curators/markets/market-config-reference) — every editable `LendingMarket` field * [CLI command index](/curators/markets/cli-command-index) — every market-related kamino-manager command * [`market-operations` CLI reference](/build/cli/market-operations) — full flag detail # Elevation Groups (eMode) Source: https://docs.kamino.com/curators/markets/elevation-groups Configure relaxed risk parameters for correlated assets Elevation groups (eMode, "efficiency mode") let a curator define a cluster of correlated assets, such as stablecoins together, liquid staking tokens paired with their underlying, or wrapped assets paired with their natives. Group members get higher LTV than they would individually, because price movement between them is small and recoverable. A user enters an elevation group voluntarily; the program then applies the group's relaxed parameters to their position, overriding the default per-reserve parameters. If they leave the group or borrow an asset outside it, the per-reserve defaults take effect again. A market supports **up to 32 elevation groups**. ## Anatomy of an elevation group ```rust theme={"theme":"css-variables"} struct ElevationGroup { id: u8, // 1..=32 (0 = ELEVATION_GROUP_NONE) ltv_pct: u8, // 0..=100 liquidation_threshold_pct: u8, // 0..=100, must be >= ltv_pct max_liquidation_bonus_bps: u16, // tighter than default for correlated assets allow_new_loans: u8, // 0 = paused, 1 = active max_reserves_as_collateral: u8, // limits diversification within group debt_reserve: Pubkey, // the single permitted debt asset for this group } ``` | Field | What it does | | - | - | | `id` | Group identifier, 1–32. `0` is reserved as the "no group" sentinel. | | `ltv_pct` | LTV applied to *all* group-resident positions in this group | | `liquidation_threshold_pct` | Liquidation threshold applied to all group-resident positions | | `max_liquidation_bonus_bps` | Cap on liquidator bonus inside the group; usually tighter than default | | `allow_new_loans` | `0` pauses new borrows in this group; `1` keeps it open | | `max_reserves_as_collateral` | Maximum number of distinct reserves a single position may hold as collateral while in the group | | `debt_reserve` | The single reserve a group member may borrow. All other reserves are unborrowable while in this group. | ## Per-reserve eMode opt-in A reserve only appears in the groups it explicitly opts into. ```jsonc theme={"theme":"css-variables"} { "elevation_groups": [1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "disable_usage_as_coll_outside_emode": 0, "borrow_limit_outside_elevation_group": "18446744073709551615", "borrow_limit_against_this_collateral_in_elevation_group": [ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" ] } ``` | Field | What it does | | - | - | | `elevation_groups` | Up to 20 group IDs this reserve belongs to. `0` slots are unused. | | `disable_usage_as_coll_outside_emode` | If `1`, the reserve can only be used as collateral within an eMode group | | `borrow_limit_outside_elevation_group` | Hard cap on borrows against this asset as collateral when the borrower is outside any group. `u64::MAX` (`18446744073709551615`) = no cap | | `borrow_limit_against_this_collateral_in_elevation_group[i]` | Per-group cap on borrows using this asset as collateral, indexed by `group_id - 1` | > [tab] SDK > > ## Configure an elevation group via SDK > > Elevation groups live on the market's `LendingMarket` struct. Reserves opt in via their `ReserveConfig.elevationGroups` array. Both updates use the standard market and reserve update flows. > > **1. Initialize KaminoManager and fetch the market** > > ```typescript theme={"theme":"css-variables"} > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket, Reserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { address } from '@solana/kit'; > > // ... rpc setup, adminSigner ... > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > const marketAddress = address(''); > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > ``` > > **2. Define the group on the market** > > ```typescript theme={"theme":"css-variables"} > const newLendingMarket = { ...marketState }; > const elevationGroups = [...marketState.elevationGroups]; > > // Set group 1 (index 0) > elevationGroups[0] = { > id: 1, > ltvPct: 90, > liquidationThresholdPct: 92, > maxLiquidationBonusBps: 200, > allowNewLoans: 1, > maxReservesAsCollateral: 3, > debtReserve: address(''), > paddingPadding0: 0, > padding1: [0n, 0n, 0n, 0n], > }; > > newLendingMarket.elevationGroups = elevationGroups as typeof marketState.elevationGroups; > > const updateIxs = kaminoManager.updateLendingMarketIxs( > adminSigner, > marketWithAddress, > newLendingMarket, > ); > // submit each ix in order > ``` > > **3. Opt each reserve into the group** > > For each reserve participating in the group, fetch its config, set its `elevationGroups` array, and apply via `updateReserveIxs`. > > ```typescript theme={"theme":"css-variables"} > const reserveAddress = address(''); > const reserve = await Reserve.fetch(rpc, reserveAddress); > if (!reserve) throw new Error('Reserve not found'); > > const newConfig = { ...reserve.config }; > const elevationGroupsList = [...newConfig.elevationGroups]; > elevationGroupsList[0] = 1; // opt this reserve into group 1 > newConfig.elevationGroups = elevationGroupsList as typeof newConfig.elevationGroups; > > // Optional: restrict this reserve to eMode-only collateral usage > newConfig.disableUsageAsCollOutsideEmode = 1; > > const updateIxs = await kaminoManager.updateReserveIxs( > adminSigner, > marketWithAddress, > reserveAddress, > newConfig, > ); > // submit each chunk in order > ``` > [tab] API > > > [!NOTE] > > > > **Elevation group configuration is not available via the REST API.** The Kamino API serves read access to market and reserve state (including current elevation group configuration); configuration is an admin operation available through the **SDK** or **Kamino CLI**. > > To configure elevation groups, use the **SDK** or **Kamino CLI** tabs. > [tab] Kamino CLI > > ## Configure an elevation group via CLI > > Elevation groups are set via the market config. Each participating reserve must also be opted in via its own reserve config. > > **1. Define the group on the market** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-lending-market-config \ > --lending-market > ``` > > Edit the downloaded `./configs//market-.json`, locate the `elevation_groups` array, fill the relevant slot: > > ```jsonc theme={"theme":"css-variables"} > { > "elevation_groups": [ > { > "id": 1, > "ltv_pct": 90, > "liquidation_threshold_pct": 92, > "max_liquidation_bonus_bps": 200, > "allow_new_loans": 1, > "max_reserves_as_collateral": 3, > "debt_reserve": "" > } > // ... 31 more slots, populated or left at defaults ... > ] > } > ``` > > Apply: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode multisig \ > --multisig > ``` > > **2. Opt each reserve into the group** > > For each participating reserve: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-reserve-config \ > --reserve \ > --output ./configs/.json > ``` > > Edit `elevation_groups`: > > ```jsonc theme={"theme":"css-variables"} > { > "elevation_groups": [1, 0, 0, 0, ...] > } > ``` > > Apply: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-reserve-config \ > --reserve \ > --reserve-config-path ./configs/.json \ > --mode multisig \ > --multisig > ``` ## Worked example: stablecoin group A market with USDC, USDT, USDS reserves wants stables-only positions to enjoy 95% LTV with a 96% liquidation threshold and a 1% max liquidator bonus. **Group definition** (in market config): ```jsonc theme={"theme":"css-variables"} { "id": 1, "ltv_pct": 95, "liquidation_threshold_pct": 96, "max_liquidation_bonus_bps": 100, "allow_new_loans": 1, "max_reserves_as_collateral": 3, "debt_reserve": "" } ``` **USDC reserve config:** ```jsonc theme={"theme":"css-variables"} { "elevation_groups": [1, 0, 0, 0, ...], "borrow_limit_against_this_collateral_in_elevation_group": [ "100000000000", "0", "0", "0", ... ] } ``` **USDT and USDS reserves:** same shape, opting into group 1. A borrower enters the group via `request-elevation-group`, deposits any combination of USDC, USDT, USDS, and borrows USDC. Their position runs at the group's 95% LTV (overriding each reserve's default LTV). ## Worked example: SOL + LST group A market with SOL, mSOL, jitoSOL, INF wants LST holders to borrow SOL at 90% LTV. **Group definition:** ```jsonc theme={"theme":"css-variables"} { "id": 1, "ltv_pct": 90, "liquidation_threshold_pct": 92, "max_liquidation_bonus_bps": 200, "allow_new_loans": 1, "max_reserves_as_collateral": 4, "debt_reserve": "" } ``` **LST reserves (mSOL, jitoSOL, INF):** opt into group 1, and consider setting `disable_usage_as_coll_outside_emode: 1` so these only function as collateral inside the group. **SOL reserve:** also opt into group 1 (a borrower can deposit SOL alongside LSTs as collateral and still borrow SOL). ## Pausing a group Set `allow_new_loans: 0` on the group definition. Existing positions continue to operate; their parameters stay relaxed; they can repay and exit. Used for incident response on a specific group without halting the whole market. ## Checklist before enabling | Check | Why it matters | | - | - | | Confirmed correlation between members | A group is only safe if its assets move together. Test depeg / divergence history | | Picked the right `debt_reserve` | The single permitted borrow asset. Pick the most liquid stable in the group, or the asset borrowers actually want | | Set `max_reserves_as_collateral` | Caps diversification inside the group. Stricter limits reduce the cost of resolving a stuck position | | Tightened `max_liquidation_bonus_bps` | Bonus should reflect actual liquidation slippage between correlated assets — usually tighter than defaults | | Reserves are opted in | The group's parameters apply only to reserves that include the group ID in their `elevation_groups` array | | Per-group borrow limits set | Without `borrow_limit_against_this_collateral_in_elevation_group`, the group has no per-asset cap and may concentrate too much risk | | `disable_usage_as_coll_outside_emode` decided | For LSTs and similar, set to `1`. For stables, often `0` so they remain collateral outside the group too | ## Reference * [Risk parameters](/curators/markets/risk-parameters) — default per-reserve LTV, threshold, borrow factor * [Reserve config reference](/curators/markets/reserve-parameters) — `elevation_groups` field shape * [Market config reference](/curators/markets/market-config-reference) — `ElevationGroup` struct shape # Emergency Controls Source: https://docs.kamino.com/curators/markets/emergency-controls Pause borrowing, halt liquidations, freeze the market, and socialize unrecoverable loss When something goes wrong, such as a bad oracle, suspicious activity, or an incident, the curator has a graduated set of switches to limit damage while a fix is prepared. This page covers each switch, when to use it, and what's still possible after it's flipped. The emergency switches range from softest (pause new borrows) to hardest (freeze the market permanently). Each is a single flag flip on `LendingMarket` or `ReserveConfig`, applied via the standard config-update flow. ## The graduated controls | Severity | Control | Effect | Reversible | | - | - | - | - | | Low | `borrow_disabled` (market) | New borrows revert. Existing borrows, deposits, withdrawals, repayments continue | Yes | | Low-mid | `utilizationLimitBlockBorrowingAbovePct` (reserve) | Borrows above utilization threshold revert | Yes | | Mid | `block_price_usage: 1` (reserve `tokenInfo`) | Any operation needing this reserve's price reverts. Market continues; affected reserve is offline | Yes | | Mid | `emergency_mode: 1` (reserve `ReserveConfig`) | Per-reserve emergency mode. Reserve operations are halted; other reserves unaffected | Yes | | Mid-high | `price_triggered_liquidation_disabled: 1` (market) | All price-triggered liquidations market-wide are blocked. Standard non-price flows continue | Yes | | High | `emergency_mode: 1` (market) | Market-wide emergency mode. Operations are restricted across all reserves | Yes | | Highest | `immutable: 1` (market) | All curator-side updates are permanently disabled. The market is frozen at its current state | **No** | > [tab] SDK > > ## Flip emergency flags via SDK > > All emergency controls are single-field updates on `LendingMarket` or `ReserveConfig`. Use the standard market or reserve update flow. > > ### Market-level flags > > ```typescript theme={"theme":"css-variables"} > import { KaminoManager, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID, MarketWithAddress } from '@kamino-finance/klend-sdk'; > import { LendingMarket } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { address } from '@solana/kit'; > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > > const newLendingMarket = { ...marketState }; > > // Examples — pick the flag that matches the situation: > newLendingMarket.borrowDisabled = 1; // pause new borrows > newLendingMarket.priceTriggeredLiquidationDisabled = 1; // pause price-triggered liquidations > newLendingMarket.emergencyMode = 1; // market-wide emergency > newLendingMarket.emergencyCouncil = address(''); > // newLendingMarket.immutable = 1; // **IRREVERSIBLE** — only set when winding down > > const ixs = kaminoManager.updateLendingMarketIxs(adminSigner, marketWithAddress, newLendingMarket); > // submit each ix in order > ``` > > ### Reserve-level flags > > ```typescript theme={"theme":"css-variables"} > import { Reserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > > const reserve = await Reserve.fetch(rpc, reserveAddress); > if (!reserve) throw new Error('Reserve not found'); > > const newConfig = { ...reserve.config }; > > // Examples — pick the flag that matches the situation: > newConfig.emergencyMode = 1; // halt this reserve > newConfig.tokenInfo = { ...newConfig.tokenInfo, blockPriceUsage: 1 }; // refuse any price-using op > newConfig.utilizationLimitBlockBorrowingAbovePct = 80; // block borrows above 80% utilization > > const ixs = await kaminoManager.updateReserveIxs( > adminSigner, > marketWithAddress, > reserveAddress, > newConfig, > ); > // submit each chunk in order > ``` > > To re-enable, set the flag back to `0` (or `0` on the relevant numeric field) and re-apply. > [tab] API > > > [!NOTE] > > > > **Emergency controls are not available via the REST API.** They are admin-level config flips on `LendingMarket` and `ReserveConfig`, applied through the **SDK** or **Kamino CLI**. > > To flip an emergency flag, use the **SDK** or **Kamino CLI** tabs. > > To monitor live state during an incident, query the on-chain accounts directly or use the [API reference](/build/api-reference/introduction). > [tab] Kamino CLI > > ## Flip emergency flags via CLI > > Emergency flags are single-field changes inside a market or reserve config JSON. Apply via the standard `update-lending-market-from-config` (market-level) or `update-reserve-config` (reserve-level) flow. > > ### Market-level flag flips > > ```bash theme={"theme":"css-variables"} > # 1. Download > yarn kamino-manager download-lending-market-config \ > --lending-market > > # 2. Edit ./configs//market-.json — flip the flag: > # "borrow_disabled": 1 > # or "emergency_mode": 1 > # or "price_triggered_liquidation_disabled": 1 > # or "immutable": 1 (IRREVERSIBLE) > > # 3. Inspect > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode inspect > > # 4. Execute or propose > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode multisig \ > --multisig > ``` > > ### Reserve-level flag flips > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-reserve-config \ > --reserve \ > --output ./configs/.json > > # Edit — flip "emergency_mode": 1 or set tokenInfo.blockPriceUsage: 1 > > yarn kamino-manager update-reserve-config \ > --reserve \ > --reserve-config-path ./configs/.json \ > --mode multisig \ > --multisig > ``` ## What each control does ### Soft pause: stop new borrows `borrow_disabled: 1` on the market. The minimal-disruption switch. Existing positions continue accruing interest. Repayments, deposits, withdrawals work. New borrows revert with `BorrowingDisabled`. Use when: you've noticed something off and want to limit new exposure while you investigate. ### Reserve-level utilization brake `utilizationLimitBlockBorrowingAbovePct: 80` on the reserve. A softer alternative to `borrow_disabled` for situations where you want to throttle borrowing only when the reserve is highly utilized. Borrows that would push utilization above the configured percentage revert; borrows at lower utilization continue. `0` disables. ### Reserve-level disable: block price usage `tokenInfo.blockPriceUsage: 1` on the reserve. The reserve's price feed is treated as unusable. Every operation that needs to read the price reverts. The reserve is effectively offline; the rest of the market continues normally. Use when: a specific reserve's oracle is misbehaving and you want to halt that reserve while replacing the oracle config. ### Reserve-level emergency mode `emergency_mode: 1` on the reserve. Stricter than `blockPriceUsage`. Halts the reserve at the program level — operations targeting the reserve revert. ### Pause price-triggered liquidations `price_triggered_liquidation_disabled: 1` on the market. Blocks every liquidation triggered by oracle price movement, including obligation orders that fire on price conditions. Standard liquidations driven by manual triggers (e.g., obligation orders with `Always` condition) still work. Use when: an oracle is misbehaving market-wide and you want to prevent cascading liquidations on bad prices. ### Market-wide emergency mode `emergency_mode: 1` on the market. The strongest reversible switch. Restricts most operations market-wide. Use only when the market needs to be brought to a near-complete stop. Pair with `emergency_council` to delegate emergency-only powers to a fast multisig. ### Permanent freeze: immutable `immutable: 1` on the market. Once flipped to `1`, the program rejects every owner-initiated config change. Existing positions continue with current parameters; no flag, threshold, cap, or oracle can be modified by anyone. Use when: * The market is being archived * You're providing a trust-minimization commitment to depositors * A migration to a new market is complete and you want the old market frozen > [!WARNING] > > `immutable: 1` is irreversible. The program has no path to undo it. Confirm twice on a multisig review before signing. ## Socialize loss (last-resort) If a position becomes truly unrecoverable — debt exceeds collateral, even the bad-debt liquidation bonus can't make liquidators whole — the curator can call `socialize-loss` to spread the loss across the affected reserve's depositors. The mechanics: 1. The `lending_market_owner` (or `emergency_council` if configured) calls `socialize-loss` for the affected obligation. 2. The unrecoverable debt is written off. 3. Each depositor's claim on the reserve is reduced proportionally to their share of total deposits. This is depositor-affecting and irreversible. Use only when: * The position is genuinely unrecoverable * Standard liquidation paths (including bad-debt liquidation) have been exhausted * The reserve has a credible plan for handling the impact (curator-funded backfill, treasury, etc.) ## Configuring the emergency council `emergency_council: ` on the market. Setting an `emergency_council` distinct from the main `lending_market_owner` lets you keep ordinary operations on a slow timelocked multisig while keeping incident response on a fast one. Recommended setup: | Authority | Multisig | Timelock | Powers | | - | - | - | - | | `lending_market_owner` | 3-of-5 multisig | 12 hours | Standard config updates, parameter changes | | `emergency_council` | 2-of-3 multisig | 0 or 1 hour | Emergency mode, socialize-loss, fast pauses | ## Operational playbook A rough decision tree for incident response: | Situation | First action | | - | - | | Suspicious borrow activity | `borrow_disabled: 1` | | One reserve's oracle looks wrong | That reserve's `blockPriceUsage: 1` | | Multiple oracles misbehaving | `price_triggered_liquidation_disabled: 1` | | Smart-contract level issue or partner-asset issue | `emergency_mode: 1` (market-wide) | | Position underwater past liquidator economics | First: confirm liquidators have tried. Then: `socialize-loss` | | Winding down a deprecated market | Eventually: `immutable: 1` | Always fix the root cause before re-enabling. Pausing then immediately unpausing without addressing the issue achieves nothing. ## Reference * [Market config reference](/curators/markets/market-config-reference) — every emergency-related field * [Reserve config reference](/curators/markets/reserve-parameters) — `emergency_mode`, `blockPriceUsage` * [Updating reserves](/curators/markets/reserve-management) — the standard reserve update flow * [Liquidations](/curators/markets/liquidations) — bad debt and liquidator economics # Emergency Council Source: https://docs.kamino.com/curators/markets/emergency-council The market-level authority for one-way, risk-reducing emergency actions, and exactly what it can and cannot do The emergency council is a market-level authority stored on `LendingMarket.emergency_council`. It is intentionally limited to one-way, risk-reducing actions: the council can enable circuit breakers or set limits to zero, but it cannot restore normal operation, relax risk parameters, or change ownership and admin settings. The market owner sets or rotates the council via `UpdateLendingMarketMode::UpdateEmergencyCouncil`. Pairing a fast emergency-council multisig with a slower, timelocked `lending_market_owner` keeps incident response quick while routine changes stay deliberate. > [!NOTE] > > Every council power is one-way. The council can only tighten (enable a breaker, zero a limit), never loosen. Only the `lending_market_owner` can reverse an emergency action. ## Market-level actions When signing `update_lending_market`, the emergency council can: * Enable global emergency mode: `UpdateEmergencyMode = true`. * Disable all new borrowing at the market level: `UpdateBorrowingDisabled = true`. * Disable price-triggered liquidations: `UpdatePriceTriggeredLiquidationDisabled = true`. It cannot set any of those flags back to `false`. Only the lending market owner can do that. Global emergency mode is broad: most user-facing instructions are guarded by `emergency_mode_disabled`, including refreshes, deposits, withdrawals, borrows, repays, liquidations, flash loans, obligation orders, rollover and fill flows, and queued-withdrawal flows. ## Reserve-level actions When signing `update_reserve_config`, the emergency council can only make the following restrictive config changes: | Mode | Allowed value | Effect | | - | - | - | | `UpdateBorrowLimit` | `0` | Blocks new borrows from the reserve. | | `UpdateDepositLimit` | `0` | Blocks new deposits into the reserve. | | `UpdateLoanToValuePct` | `0` | Disables using the reserve as collateral for borrowing. | | `UpdateBlockPriceUsage` | `1` | Marks the reserve price as unusable. | | `UpdateReserveEmergencyMode` | `1` | Enables reserve emergency mode. | | `UpdateDisableUsageAsCollateralOutsideEmode` | `1` | Disables use as collateral outside e-mode. | For all other reserve config modes, or for the opposite values above, the emergency council is not authorized. The lending market owner remains the fallback authority for normal reserve config changes, while global-admin-only reserve modes still require the global admin. Reserve emergency mode blocks most user operations involving that reserve. Refreshing a reserve in emergency mode does not update the oracle price and clears the saved price status instead. The reserve-level flag can still be enabled even if the market has been made immutable; disabling it requires the normal owner path. ## Not emergency council powers The emergency council cannot: * Change the lending market owner, emergency council, global admin, proposer authority, or permissioning authority. * Disable global or reserve emergency mode after it was enabled. * Raise borrow, deposit, or LTV limits, or re-enable price usage or collateral usage. * Execute owner-only operations such as `socialize_loss`. * Bypass global-admin-only reserve config ownership for protocol fees, take rates, flash-loan fees, fixed-interest host fees, order execution fees, or cToken blocking. > [!WARNING] > > Enabling emergency mode or zeroing a limit has effects the council cannot undo. Confirm the action on a multisig review before signing; reversing it requires the `lending_market_owner`. ## Code references * Market allowlist: `programs/klend/src/handlers/handler_update_lending_market.rs` * Reserve allowlist: `programs/klend/src/lending_market/lending_operations.rs` * Reserve emergency mode behavior: `programs/klend/src/state/reserve.rs`, `programs/klend/src/lending_market/lending_checks.rs` * Global emergency mode guard: `programs/klend/src/utils/constraints.rs`, `programs/klend/src/lib.rs` ## Reference * [Emergency controls](/curators/markets/emergency-controls) — the operational switches and incident playbook * [Market config reference](/curators/markets/market-config-reference) — every market-level field * [Reserve parameters](/curators/markets/reserve-parameters) — reserve config fields # Farms & Rewards Source: https://docs.kamino.com/curators/markets/farms-and-rewards Initialize collateral and debt farms on reserves, fund emissions, claim rewards Each reserve in a market can run two independent farms — one for depositors (collateral side) and one for borrowers (debt side). Farms distribute reward emissions over time to position holders, denominated in any token. They're the curator's primary lever for attracting deposits or driving borrow demand. Farms are managed by the [KFarms](https://github.com/Kamino-Finance/kfarms) program. The klend `Reserve` account holds two `Pubkey` fields — `farm_collateral` and `farm_debt` — that link the reserve to its farm accounts on KFarms. Once linked, klend automatically updates the farm whenever a depositor or borrower's balance changes. ## Two farms per reserve ```rust theme={"theme":"css-variables"} struct Reserve { // ... farm_collateral: Pubkey, // Pubkey::default() if no farm farm_debt: Pubkey, // ... } ``` | Farm | Who earns | Use case | | - | - | - | | Collateral farm | Depositors / suppliers | Attract liquidity to a reserve. Most common | | Debt farm | Borrowers | Subsidize borrowing. Used to bootstrap utilization or reward leveraged-yield strategies | Each farm can distribute multiple reward tokens simultaneously, with independent emission rates and start/end times. > [tab] SDK > > ## Initialize a reserve farm via SDK > > The klend `initFarmsForReserve` instruction creates a KFarms `FarmState` account and links it to the reserve's `farm_collateral` or `farm_debt` slot. The instruction is exposed in the SDK codegen. > > ```typescript theme={"theme":"css-variables"} > import { initFarmsForReserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/instructions'; > import { PROGRAM_ID } from '@kamino-finance/klend-sdk'; > > // Build args and accounts per the instruction's signature, then: > const ix = initFarmsForReserve( > { mode: 0 }, // 0 = collateral, 1 = debt > accounts, > PROGRAM_ID, > ); > // Sign with the curator's wallet and submit > ``` > > For full args / accounts shapes, see the auto-generated source at `klend-sdk/src/@codegen/klend/instructions/initFarmsForReserve.ts`. > > After the farm is created, configure emission rates and reward mints via the KFarms admin tooling — see the [farms-sdk](https://github.com/Kamino-Finance/farms-sdk) repository. > > ### Read farm state > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; > import { FarmState } from '@kamino-finance/farms-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const market = await KaminoMarket.load(rpc, address(''), slotDuration); > > for (const reserve of market!.getReserves()) { > const collFarm = reserve.getCollateralFarmAddress(); > const debtFarm = reserve.getDebtFarmAddress(); > > if (collFarm) { > const farmState = await FarmState.fetch(rpc, collFarm); > console.log(`${reserve.symbol} collateral farm:`, farmState); > } > if (debtFarm) { > const farmState = await FarmState.fetch(rpc, debtFarm); > console.log(`${reserve.symbol} debt farm:`, farmState); > } > } > ``` > > ### Claim rewards > > ```typescript theme={"theme":"css-variables"} > import { Farms } from '@kamino-finance/farms-sdk'; > > const farms = new Farms(rpc); > > const claimIxs = await farms.claimForUserForFarmAllRewardsIx( > payer, // TransactionSigner > address(''), > address(''), > false, // isDelegated > ); > // Bundle into a transaction and submit > ``` > > For a step-by-step claiming walkthrough, see [Claim user rewards](/build/tutorials/borrow/claim-user-rewards). > [tab] API > > The Kamino API exposes farm and reward data as REST endpoints: > > | Endpoint | Returns | > | - | - | > | `GET /klend/rewards` | All active reward programs across reserves on klend | > | `GET /klend/users/{pubkey}/rewards` | Per-user claimable rewards across reserves | > > ```bash theme={"theme":"css-variables"} > curl https://api.kamino.finance/klend/rewards > curl https://api.kamino.finance/klend/users//rewards > ``` > > > [!NOTE] > > > > **Farm initialization, funding, and emission configuration is not available via the REST API.** Farms are initialized through the **SDK** or via klend's `initFarmsForReserve` instruction. Emissions are configured through the KFarms admin tooling. > > For computing farm APYs from on-chain state, see [Calculate reserve reward APY](/build/tutorials/borrow/calculate-reserve-reward-apy). > [tab] Kamino CLI > > ## Read farm state via CLI > > The kamino-manager CLI exposes a read-side query for farm APYs: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager get-reserve-farms-apy \ > --reserve > ``` > > For farm initialization, funding, and emission configuration, use the KFarms admin tooling — see the [farms-sdk](https://github.com/Kamino-Finance/farms-sdk) repository for the canonical command set. ## Initialization workflow **1. Decide collateral side, debt side, or both** Most markets initialize the collateral farm only. Initialize the debt farm only if you plan to incentivize borrowers. **2. Generate the farm state keypair** Each farm is its own on-chain account. Generate a fresh keypair to use as the farm address. **3. Call init-farms-for-reserve** The klend program initializes the farm via CPI to KFarms and stores the farm address on the reserve. After this, klend automatically refreshes the farm on every deposit / withdraw / borrow / repay touching the reserve. **4. Configure emissions** Use KFarms admin tooling to set reward tokens, emission rates, and start/end timestamps. The standard pattern is one reward mint per active campaign; multiple mints can run in parallel. **5. Fund the farm** Transfer the reward tokens to the farm's reward vault. Without funding, emissions accrue notionally but cannot be claimed. ## How emissions accrue Once a farm is active and funded: * klend auto-refreshes the farm on every position-changing operation (deposit, withdraw, borrow, repay) * Each user's pending rewards accumulate proportionally to their share of the farm's total weight (collateral side: their share of total deposits; debt side: their share of total borrows) * Rewards are claimable at any time via the KFarms `claim-rewards` instruction * Emission rates are tokens-per-unit-time set on the KFarms `FarmState` ## Operating a farm Common adjustments after launch: | Action | How | | - | - | | Add a new reward token | Add the mint to the farm's reward set via KFarms admin instructions | | Change emission rate | Update the rate via KFarms; the change applies prospectively | | End a campaign | Set the campaign's end timestamp via KFarms; emissions stop accruing after that point | | Top up reward funds | Transfer more tokens to the farm's reward vault | | Drain unused rewards | Use KFarms admin to withdraw remaining unclaimed funds (subject to KFarms admin rules) | Most curators operate the farm via Squads multisig once it's live. The KFarms admin authority should match the operational posture of the market itself. ## When to use a debt farm Debt farms (rewards for borrowers) are less common than collateral farms but valuable in specific scenarios: | Scenario | Why a debt farm makes sense | | - | - | | Bootstrapping a new fixed-term reserve | Subsidize borrowers until natural demand develops | | Yield-leverage strategies (looping) | Rewards on the debt side compound the strategy's effective APY | | Cross-incentive program | Reward both depositors (collateral) and borrowers (debt) on the same reserve to drive utilization toward a target | Debt farms have the same mechanical structure as collateral farms (emission rates, reward mints, claim flow); only the underlying weight (borrow balances vs deposit balances) changes. ## Reference * [KFarms repository](https://github.com/Kamino-Finance/kfarms) — the program source * [farms-sdk](https://github.com/Kamino-Finance/farms-sdk) — TypeScript helpers for farm administration * [Reserve reward APY tutorial](/build/tutorials/borrow/calculate-reserve-reward-apy) * [Claim user rewards](/build/tutorials/borrow/claim-user-rewards) * [Read market data → Rewards](/curators/markets/market-data#rewards-data) # Fixed Rate Reserves Source: https://docs.kamino.com/curators/markets/fixed-rate-reserves Reserves with a host fixed rate, debt maturity, rollover windows, and early-repay penalties A fixed rate reserve locks borrowers into a predictable rate for a defined duration. The reserve's `borrow_rate_curve` is configured as a flat curve at the target rate, so borrowers pay the same rate regardless of utilization. At maturity, the borrower must repay, roll over, or face liquidation. Each (rate, term) combination lives on its own reserve. A market that offers, say, 4%/30-day, 5%/60-day, and 6%/90-day USDC borrows would have three USDC fixed rate reserves — one per (rate, term) pair — each with its own debt maturity. ## Reserve-level configuration The fixed-rate mechanics are controlled by these `ReserveConfig` fields: | Field | What it does | | - | - | | `debt_term_seconds` | Duration of the fixed term, in seconds. `0` = open-term reserve. Setting any positive value makes every borrow on this reserve a fixed-term borrow | | `debt_maturity_timestamp` | Optional absolute Unix timestamp when *all* debt on this reserve matures simultaneously. `0` = each borrow rolls forward `debt_term_seconds` from origination | | `host_fixed_interest_rate_bps` | Optional additional spread (bps) layered on top of the flat borrow rate curve, accruing 100% to the protocol. Default `0` | | `early_repay_remaining_interest_pct` | Penalty for repaying during the first term, expressed as percent (0–100) of the *remaining* interest to maturity. After rollover, no penalty applies | ## Market-level rollover settings | Field | What it does | | - | - | | `fixed_term_rollover_window_duration_seconds` | Window before maturity allowing fixed→fixed rollover. `0` disables | | `open_term_rollover_window_duration_seconds` | Window before maturity allowing fixed→open rollover. `0` disables | | `obligation_borrow_migration_to_fixed_execution_enabled` | If `1`, allows open→fixed migration anytime | | `obligation_borrow_rollover_configuration_enabled` | If `1`, allows borrowers to pre-configure rollover behavior | | `min_partial_rollover_value` | Minimum size for a partial rollover. `0` requires full rollovers only | | `term_based_full_liquidation_duration_secs` | Time after maturity before full (close-factor-bypassing) liquidation is available | | `mature_reserve_debt_liquidation_enabled` | Master switch for mature-debt liquidation flow | | `obligation_borrow_debt_term_liquidation_enabled` | Per-feature switch for the term-based liquidation path | > [tab] SDK > > ## Configure a fixed rate reserve via SDK > > Reserve-level fields are set via `kaminoManager.updateReserveIxs` (or at creation via `addAssetToMarketIxs`). Market-level rollover and liquidation flags are set via `updateLendingMarketIxs`. > > ### Reserve config > > ```typescript theme={"theme":"css-variables"} > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket, Reserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { address } from '@solana/kit'; > > // ... rpc setup, adminSigner ... > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > > const reserve = await Reserve.fetch(rpc, reserveAddress); > if (!reserve) throw new Error('Reserve not found'); > > const newConfig = { ...reserve.config }; > newConfig.debtTermSeconds = 2_592_000n; // 30 days > newConfig.debtMaturityTimestamp = 0n; // 0 = per-borrow rolling term > newConfig.hostFixedInterestRateBps = 500; // 5% > newConfig.earlyRepayRemainingInterestPct = 50; // 50% penalty on remaining interest > > const updateIxs = await kaminoManager.updateReserveIxs( > adminSigner, > marketWithAddress, > reserveAddress, > newConfig, > ); > // submit each chunk in order > ``` > > ### Market-level rollover and liquidation flags > > ```typescript theme={"theme":"css-variables"} > const newLendingMarket = { ...marketState }; > newLendingMarket.fixedTermRolloverWindowDurationSeconds = 172_800n; // 48 hours > newLendingMarket.openTermRolloverWindowDurationSeconds = 0n; > newLendingMarket.obligationBorrowMigrationToFixedExecutionEnabled = 0; > newLendingMarket.obligationBorrowRolloverConfigurationEnabled = 1; > newLendingMarket.minPartialRolloverValue = 100_000n; > newLendingMarket.termBasedFullLiquidationDurationSecs = 86_400n; // 24h after maturity > newLendingMarket.matureReserveDebtLiquidationEnabled = 1; > newLendingMarket.obligationBorrowDebtTermLiquidationEnabled = 1; > > const ixs = kaminoManager.updateLendingMarketIxs(adminSigner, marketWithAddress, newLendingMarket); > // submit each ix in order > ``` > > ### User-side rollover > > The user-facing rollover instruction (`rolloverFixedTermBorrow`) is part of the on-chain klend program. The current public klend-sdk does not yet expose a dedicated TypeScript helper for it; until it ships, end-user apps integrate the rollover via the Kamino webapp or by building the instruction manually from the program IDL. > [tab] API > > > [!NOTE] > > > > **Configuring fixed-rate parameters is not available via the REST API.** The fields live on `ReserveConfig` and `LendingMarket` and are set through the **SDK** or **Kamino CLI**. > > To configure fixed rate reserves and rollover behavior, use the **SDK** or **Kamino CLI** tabs. > > For reading reserve maturity and debt term state, see [Read market data](/curators/markets/market-data). > [tab] Kamino CLI > > ## Configure a fixed rate reserve via CLI > > Fixed-rate parameters are part of the standard reserve config JSON. Apply via `update-reserve-config`. > > ### Reserve config > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-reserve-config \ > --reserve \ > --output ./configs/.json > ``` > > Edit the JSON: > > ```jsonc theme={"theme":"css-variables"} > { > "debt_term_seconds": 2592000, > "debt_maturity_timestamp": 0, > "host_fixed_interest_rate_bps": 500, > "early_repay_remaining_interest_pct": 50 > } > ``` > > Apply: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-reserve-config \ > --reserve \ > --reserve-config-path ./configs/.json \ > --mode multisig \ > --multisig > ``` > > ### Market-level rollover and liquidation flags > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-lending-market-config \ > --lending-market > ``` > > Edit `./configs//market-.json`: > > ```jsonc theme={"theme":"css-variables"} > { > "fixed_term_rollover_window_duration_seconds": 172800, > "open_term_rollover_window_duration_seconds": 0, > "obligation_borrow_migration_to_fixed_execution_enabled": 0, > "obligation_borrow_rollover_configuration_enabled": 1, > "min_partial_rollover_value": "100000", > "term_based_full_liquidation_duration_secs": 86400, > "mature_reserve_debt_liquidation_enabled": 1, > "obligation_borrow_debt_term_liquidation_enabled": 1 > } > ``` > > Apply via `update-lending-market-from-config`. ## Open-term vs. fixed-rate | Mode | Configuration | | - | - | | Open-term (default) | `debt_term_seconds = 0`, `debt_maturity_timestamp = 0`, `host_fixed_interest_rate_bps = 0` | | Per-borrow rolling fixed term | `debt_term_seconds > 0`, `debt_maturity_timestamp = 0`. Every borrow matures `debt_term_seconds` after origination | | Cohort fixed term | `debt_term_seconds > 0`, `debt_maturity_timestamp > 0`. All debt matures at the absolute timestamp | Mixing fixed and open on the same reserve isn't supported. To run both, deploy two reserves for the same mint. ## How interest accrues Total borrow rate = `borrow_rate_curve value at current utilization` + `host_fixed_interest_rate_bps`. For a fixed-rate reserve, the `borrow_rate_curve` is configured as a **flat curve** (both endpoints set to the same rate), so the base rate is constant regardless of utilization. With `host_fixed_interest_rate_bps` at its default of `0`, the borrower pays exactly the flat curve rate. Set a non-zero `host_fixed_interest_rate_bps` only when you intentionally want a protocol-side spread on top of the lender-facing rate. See [Reserve Configuration](/curators/markets/fixed-rates/reserve-configuration#what-pins-a-fixed-rate-reserve) for full details on configuring the flat curve. ## Maturity and what happens at it When a borrow reaches its `debt_maturity_timestamp` (per-borrow or cohort): | Outcome | Trigger | | - | - | | Repay in full | The borrower repays. The position closes | | Roll over | The borrower rolls into a new fixed term — same reserve, different reserve, or migrates to open-term. Subject to market-level rollover flags | | Liquidation as mature debt | If `mature_reserve_debt_liquidation_enabled = 1` and `obligation_borrow_debt_term_liquidation_enabled = 1`, mature debt becomes liquidatable | | Forced full liquidation | After `term_based_full_liquidation_duration_secs` past maturity, the position is eligible for full (close-factor-bypassing) liquidation | ## The rollover modes | Mode | Source | Destination | Constraints | | - | - | - | - | | Fixed → Fixed | A fixed rate reserve | Another (or same) fixed rate reserve | Allowed only inside `fixed_term_rollover_window_duration_seconds` of original maturity | | Fixed → Open | A fixed rate reserve | An open-term reserve for the same mint | Allowed only inside `open_term_rollover_window_duration_seconds` of original maturity | | Open → Fixed | An open-term reserve | A fixed rate reserve for the same mint | Allowed any time, gated by `obligation_borrow_migration_to_fixed_execution_enabled` | Rollover preserves the principal but resets accrual: the new term starts fresh. Penalties from the prior term do not carry over. ## Early-repay penalty The early-repay penalty applies during the **first term only**. Once a loan rolls over into a subsequent term, the borrower can repay at any time without penalty. ``` penalty = early_repay_remaining_interest_pct% × (interest that would have accrued from now to maturity) ``` | `early_repay_remaining_interest_pct` | Effect | | - | - | | `0` | No penalty. Borrowers can repay any time at no extra cost | | `50` | 50% of remaining interest is owed at repay during the first term. Mild discouragement of early exit | | `100` | Full first term's interest is locked in. The borrower owes the same regardless of repay time | > [!NOTE] > > If the borrower borrows additional principal on an already-active fixed-term position, the borrow timestamp is reset for the entire position. Effectively, the new top-up creates a new fixed term covering the combined balance. After a rollover, the penalty no longer applies. ## Curator workflow: launching a fixed rate reserve **1. Decide the (rate, term) matrix** Pick the durations and rates you want to offer (e.g., 30/60/90 days at 4%/5%/6%). Each combination is a separate reserve. **2. Configure each reserve** Set `debt_term_seconds`, `host_fixed_interest_rate_bps`, `early_repay_remaining_interest_pct`. Choose risk parameters (LTV, threshold, IR curve) appropriate for the duration. **3. Set market-level rollover windows** Decide the rollover window — how far before maturity borrowers can roll. Common settings: 24–72 hours. **4. Enable mature-debt liquidation** Set `mature_reserve_debt_liquidation_enabled = 1` and `obligation_borrow_debt_term_liquidation_enabled = 1`. Choose `term_based_full_liquidation_duration_secs` (typically 12–48 hours after maturity). **5. Test on staging** Take a fixed-term borrow on staging, fast-forward time using a test scenario, exercise rollover, exercise repay, exercise mature-debt liquidation. Confirm the lifecycle works before mainnet. ## Common errors | Error | Cause | | - | - | | `BorrowRolloverExecutionDisabled` | Market-level rollover window is `0`. Set `fixed_term_rollover_window_duration_seconds` (or `open_term_rollover_window_duration_seconds`) to a positive value | | `RolloverWindowNotOpen` | Borrower tried to roll outside the configured window before maturity | | `MatureDebtLiquidationDisabled` | The position is mature but liquidation flags are off. Either enable the liquidation flags or repay | | Sub-\$2 obligations stuck near maturity | A known edge case where dust positions interact poorly with the close-factor cap. Set `min_full_liquidation_value_threshold` low enough that mature dust positions can be fully liquidated | ## Reference * [Reserve config reference](/curators/markets/reserve-parameters) — fixed-rate reserve fields * [Market config reference](/curators/markets/market-config-reference) — rollover and term-liquidation flags * [Borrow orders](/curators/markets/borrow-orders) — peer-to-peer matching for fixed-rate liquidity * [Liquidations](/curators/markets/liquidations) — base liquidation mechanics # Fixed Rates Source: https://docs.kamino.com/curators/markets/fixed-rates/index Creating and configuring fixed-rate reserves and the market-level settings that govern them Fixed-rate reserves are a distinct reserve type within a Kamino lending market. Each fixed-rate reserve has a constant borrow rate and a fixed term (e.g. `USDC 5.5% 3M`) and exists alongside the floating-rate reserve for the same debt token. This section is for **market managers** — the curators who create reserves, set rates and terms, configure rollover and liquidation windows, and decide when fixed-rate features go live on a market. For the allocator-side view (curators allocating capital into fixed-rate reserves), see [Fixed Rates (Vaults)](/curators/vaults/fixed-rates). ## Read in this order > [card] [Reserve Configuration](/curators/markets/fixed-rates/reserve-configuration) > > Anatomy of a fixed-rate reserve, the four fields that pin rate and term, and how to create one via CLI. > [card] [Market Settings](/curators/markets/fixed-rates/market-settings) > > Feature flags, rollover windows, the post-maturity liquidation throttle, and the recommended enablement sequence. > [card] [Lifecycle Operations](/curators/markets/fixed-rates/lifecycle-operations) > > Updating an existing reserve, what can and cannot be changed, soft and hard sunsetting, and operational notes. > [card] [Risk Considerations](/curators/markets/fixed-rates/risk) > > Risks specific to running fixed-rate reserves and how to set parameters that mitigate them. # Lifecycle Operations Source: https://docs.kamino.com/curators/markets/fixed-rates/lifecycle-operations Updating an existing fixed-rate reserve, what can and cannot be changed, and sunsetting patterns This page covers operating an existing fixed-rate reserve over its lifecycle: making parameter changes, what's mutable vs. immutable, and how to wind a reserve down when it's no longer needed. ## Updating an existing fixed-rate reserve The general reserve-update flow at [Reserve Management](/curators/markets/reserve-management) applies — download config, edit, preview, apply. A few constraints are specific to fixed-rate reserves: | Change | Constraint | | - | - | | Lower the borrow rate | Allowed. Affects only new borrows; existing borrows keep their original rate. | | Raise the borrow rate | Allowed. Same — affects only new borrows. | | Shorten `debt_term_seconds` | **Blocked** if the reserve has any active borrows. Existing commitments are protected from retroactive shortening. | | Lengthen `debt_term_seconds` | Allowed. Affects only new borrows. | | Set `debt_maturity_timestamp` to the past | Blocked — must not be in the past at update time. | | Move `debt_maturity_timestamp` later | Allowed. Reserve sunset extends. | | Move `debt_maturity_timestamp` earlier | Allowed, but only to a future timestamp. Existing borrows past the new maturity become liquidatable when the maturity arrives. | | Change `early_repay_remaining_interest_pct` | Allowed. Penalty for new borrows uses the new value. | | Change `host_fixed_interest_rate_bps` | Allowed. Affects new borrow accrual. | > [!WARNING] > > **Existing borrows keep the rate they were originated at.** If you change the rate or term on a reserve, current positions are unaffected — the change applies only to new borrows. This means a "USDC 5.5% 3M" reserve can simultaneously hold borrows at 5.5%, 5.0%, and 6.0% if the rate has been changed over time. Plan rate adjustments around expected position turnover. ## Sunsetting a fixed-rate reserve Two patterns: ### Soft sunset — gradual wind-down Set `debt_maturity_timestamp` to a future date. New borrows are blocked from that moment; existing borrows continue running. As they hit their per-borrow term ends, they roll, repay, or get protocol-liquidated. Once the reserve maturity hits and `mature_reserve_debt_liquidation_enabled` is on, any remaining debt becomes fully liquidatable with no throttle. This is the normal path. It gives existing borrowers fair notice and lets the reserve unwind through normal maturity flow. ### Hard sunset — immediate stop Set the reserve `status` to `Inactive` (1) — blocks all new operations. Existing debt remains and must wind down through normal repayment, rollover (if pointed elsewhere), or liquidation paths. Use this only when the reserve must stop serving new borrowers immediately for risk reasons. Hard sunset is a circuit breaker — reach for it only when there's an active reason to halt activity, because it prevents borrowers from rolling within the reserve. ## Operational notes * **Lock time.** Reserve config updates typically have a \~4-hour lock between commitment and on-chain effect. Plan parameter changes around testing windows. * **Simulate first.** Always use `--mode inspect` before `--mode execute`. The simulation will surface invalid parameter combinations (e.g. attempts to shorten an active reserve's term) before they hit the chain. * **Rate changes don't affect existing borrows.** This is a feature, not a bug — borrowers locked in a rate keep that rate. Adjust rates expecting the change to flow through over time as positions turn over. * **Rollover-in-elevation-groups is unsupported.** Borrowers using elevation modes (eMode) on the market cannot have their fixed-term positions rolled over. If your market makes heavy use of eMode, expect those positions to require manual repayment at maturity. * **The withdrawal queue requires the kvault program to be on a recent version.** Vaults integrating with your market need their kvault upgraded before they can interact with FR reserves correctly. Coordinate the rollout with vault curators. * **Penalty interest accrues to protocol fees on the debt reserve**, not to the lender side. The early-repay penalty design protects lenders by discouraging premature exits but doesn't directly compensate them. ## What's next > [card] [Risk Considerations](/curators/markets/fixed-rates/risk) > > Risks specific to running fixed-rate reserves and how to set parameters that mitigate them. # Market Settings Source: https://docs.kamino.com/curators/markets/fixed-rates/market-settings Feature flags, rollover windows, and the post-maturity liquidation throttle Fixed-rate reserves require several **market-level** flags and parameters to be set before borrowers can place orders, fills can execute, withdrawal tickets can be issued, and rollovers can run. These live on the `LendingMarket` account and apply to every reserve in the market. ## Feature flags — turn capabilities on Every flag defaults to **off** at market init. You enable each one explicitly when the market is ready for that capability. | Flag | Effect when enabled | | - | - | | `borrow_order_creation_enabled` | Borrowers can place new borrow orders | | `borrow_order_execution_enabled` | Permissionless fillers (and fill bots) can execute borrow orders | | `withdraw_ticket_issuance_enabled` | Lenders and vaults can submit withdrawal tickets | | `withdraw_ticket_redemption_enabled` | Queued tickets can be redeemed | | `withdraw_ticket_cancellation_enabled` | Tickets can be cancelled before fill | | `mature_reserve_debt_liquidation_enabled` | Liquidation triggers when a reserve passes its `debt_maturity_timestamp` | | `obligation_borrow_debt_term_liquidation_enabled` | Liquidation triggers when a per-borrow term ends | | `obligation_borrow_rollover_configuration_enabled` | Borrowers can opt into rollover on their existing borrows | | `obligation_borrow_migration_to_fixed_execution_enabled` | Allows rollover from open-term to fixed-term | ### Recommended enablement sequence When standing up fixed rates on a market: 1. Create the fixed-rate reserves (with terms and rates set, but features still off). 2. Enable `borrow_order_creation_enabled` and `borrow_order_execution_enabled` together. 3. Enable `withdraw_ticket_issuance_enabled` + `withdraw_ticket_redemption_enabled` + `withdraw_ticket_cancellation_enabled` together. 4. Enable `obligation_borrow_rollover_configuration_enabled` and the rollover window durations (below) before the first borrow's maturity arrives. 5. Enable `mature_reserve_debt_liquidation_enabled` and `obligation_borrow_debt_term_liquidation_enabled` last — these activate the protocol-enforced liquidation paths. > [!NOTE] > > Borrower interactions with a fixed-rate reserve fall back to standard floating behaviour if the matching feature flags aren't on. In practice, leaving rollover or liquidation flags off means borrowers must repay manually at maturity, and matured loans cannot be force-closed — keep this in mind during a phased rollout. ## Rate-grid sizing parameters | Parameter | Default | Meaning | | - | - | - | | `min_borrow_order_fill_value` | `2` | Minimum value of any partial fill, and the minimum stump value left after a partial fill. Anti-dust. Adjust upward to discourage thin orders. | | `min_withdraw_queued_liquidity_value` | `2` | Minimum value for any withdrawal ticket and any partial-fill remainder. Same anti-dust function for the queue side. | Both values are denominated in the market's quote currency scaling (effectively dollars for a USD-quote market). For most markets the default `2` is the right floor; only raise these if you're seeing dust attacks against the queue or the order book. ## Rollover windows Rollover is a **pre-expiration** operation. The market defines two distinct windows, each governing one rollover mode: | Parameter | Effect | | - | - | | `fixed_term_rollover_window_duration_seconds` | The window before a fixed-term borrow's maturity during which rollover *into the same or another fixed-term reserve* is allowed. `0` disables fixed→fixed rollover entirely. | | `open_term_rollover_window_duration_seconds` | The window before maturity during which rollover *from a fixed-term borrow into an open-term (floating) reserve* is allowed. `0` disables fixed→open rollover. | A typical configuration sets both windows to the same duration (e.g. 24 hours). The windows must be long enough that the rollover keeper bot can complete the operation across all eligible positions before each cohort of maturities passes. Past the term end, rollover is no longer possible — the borrow transitions directly to liquidation eligibility. `obligation_borrow_migration_to_fixed_execution_enabled` enables a third, separate rollover mode — open-term to fixed-term — which has no time window; it can be performed at any time once the flag is on. ## Post-maturity liquidation throttle | Parameter | Effect | | - | - | | `term_based_full_liquidation_duration_secs` | When a borrow passes its term without rollover or repay, the liquidatable fraction ramps linearly from 0% (at term end) to 100% over this duration. `0` disables the throttle (full liquidation immediately at term end). | | `min_partial_rollover_value` | Minimum value for a partial rollover. Below this, partial rollover is rejected to avoid dust state. | The throttle gives borrowers a graceful window to react after they've missed the rollover window — partial liquidation provides increasing pressure rather than a cliff. Set it long enough that a missed-rollover position has time to be repaid voluntarily before being fully unwound, but short enough that capital doesn't sit indefinitely against expired terms. A few days is typical. The per-reserve `min_deleveraging_bonus_bps`, `max_liquidation_bonus_bps`, and `deleveraging_bonus_increase_bps_per_day` (set on each reserve, not the market) drive the *bonus* paid to liquidators across the throttle window. If those are zero, liquidators have no incentive — set them to produce meaningful per-day increase capped at a reasonable maximum. ## Configuring market settings All of the above parameters live in the market config JSON and are applied through the standard `update-lending-market-from-config` flow: ```bash theme={"theme":"css-variables"} # Download current config yarn kamino-manager download-lending-market-config \ --lending-market # Edit ./configs/{MARKET_ADDRESS}/market-{MARKET_ADDRESS}.json # Set the FR-related flags and durations # Preview yarn kamino-manager update-lending-market-from-config \ --lending-market \ --lending-market-config-path ./configs//market-.json \ --mode inspect # Apply yarn kamino-manager update-lending-market-from-config \ --lending-market \ --lending-market-config-path ./configs//market-.json \ --mode execute ``` See [Market Settings](/curators/markets/market-settings) for the broader market-config workflow including ownership transfer and multisig mode. ## What's next > [card] [Lifecycle Operations](/curators/markets/fixed-rates/lifecycle-operations) > > Updating an existing fixed-rate reserve and sunsetting patterns. > [card] [Risk Considerations](/curators/markets/fixed-rates/risk) > > Risks specific to running fixed-rate reserves. # Reserve Configuration Source: https://docs.kamino.com/curators/markets/fixed-rates/reserve-configuration Anatomy of a fixed-rate reserve and how to create one A fixed-rate reserve uses the same primitives as a floating reserve plus four config fields that pin the rate and impose a term. This page covers what those fields mean and the workflow for creating a reserve. ## What pins a fixed-rate reserve | Field | Type | Meaning | | - | - | - | | `borrow_rate_curve` | piecewise-linear curve | For a fixed-rate reserve, configured as a **flat curve** at the target rate. Borrowers pay this rate regardless of utilization. | | `host_fixed_interest_rate_bps` | u16 | Optional **additional** spread layered on top of the curve, charged to the borrower and accruing 100% to the protocol (not lenders). Default `0`. | | `debt_term_seconds` | u64 | Per-borrow term. The borrower's loan matures at `last_borrowed_at_timestamp + debt_term_seconds`. `0` = open-term (the reserve behaves as floating). | | `debt_maturity_timestamp` | u64 | Reserve-wide sunset timestamp. After this, no new borrows are accepted and existing borrows become liquidatable. `0` = no sunset. | | `early_repay_remaining_interest_pct` | u8 (0–100) | Penalty for repaying inside the first term. Penalty = projected interest for the remaining term × this percentage. Accrues to protocol fees on the debt reserve. | `debt_term_seconds` and `debt_maturity_timestamp` are independent. Set neither (effectively a floating reserve), one, or both. Use `debt_term_seconds` to express *every borrow gets a 3-month clock starting at borrow time*. Use `debt_maturity_timestamp` to express *this whole reserve sunsets on January 1*. The two compose: a reserve with both constraints requires every borrow to fit inside the remaining time until reserve maturity. > [!NOTE] > > **The borrower's effective rate is the `borrow_rate_curve` value at current utilization plus `host_fixed_interest_rate_bps`.** For most fixed-rate reserves you want a flat `borrow_rate_curve` at the desired rate and `host_fixed_interest_rate_bps = 0`. Set a non-zero `host_fixed_interest_rate_bps` only when you intentionally want a protocol-side spread on top of the lender-facing rate. ## Creating a fixed-rate reserve A fixed-rate reserve is created the same way as a floating one — the difference is in the config you supply. > [tab] Kamino CLI > > **1. Add the reserve to your market** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager add-asset-to-market \ > --market \ > --token-mint \ > --mode execute > ``` > > This creates a new reserve account against the specified mint. Multiple reserves for the same mint can coexist in a market — each one is its own independent pool with its own config. > > **2. Download the default reserve config** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-reserve-config \ > --market \ > --reserve \ > --output ./configs/fixed_rate_reserve_config.json \ > --mode inspect > ``` > > **3. Edit the config for fixed-rate behaviour** > > In the JSON, set: > > * `borrowRateCurve.points` — flat curve at the target rate. Both endpoints set to the same `borrowRateBps`. See pattern below. > * `debtTermSeconds` — term in seconds (e.g. `7776000` for 90 days, `2592000` for 30 days). > * `debtMaturityTimestamp` — only if you want the entire reserve to sunset on a specific date; otherwise leave at `0`. > * `earlyRepayRemainingInterestPct` — typical values are 10–25% (the first-term-only penalty). > * `hostFixedInterestRateBps` — usually `0`. Only set if you want a protocol-side spread. > > **Example flat curve at 5.5%:** > > ```json theme={"theme":"css-variables"} > "borrowRateCurve": { > "points": [ > { "utilizationRateBps": 0, "borrowRateBps": 550 }, > { "utilizationRateBps": 10000, "borrowRateBps": 550 } > ] > } > ``` > > The remaining points in the curve array should be padded to the same final value (the SDK and CLI handle padding automatically when you start from a flat curve). > > **4. Set risk parameters** > > Standard reserve risk params still apply — set them appropriate to the collateral, not to the term: > > * `loanToValuePct`, `liquidationThresholdPct` — the same curve as the floating-rate reserve for the same debt token typically applies. Term doesn't change credit risk; collateral does. > * `minLiquidationBonusBps`, `maxLiquidationBonusBps`, `deleveragingBonusIncreaseBpsPerDay` — these matter especially for fixed-rate because protocol-enforced liquidation (term/maturity breach) ramps the bonus from min to max linearly per day. Set values that produce a meaningful incentive curve for liquidators. > > See [Reserve Parameters](/curators/markets/reserve-parameters) for the full parameter reference. > > **5. Preview and apply** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-reserve-config \ > --market \ > --reserve \ > --reserve-config ./configs/fixed_rate_reserve_config.json \ > --mode inspect > ``` > > Then re-run with `--mode execute` (or `--mode multisig` to produce a Squads payload). > > > [!WARNING] > > > > Reserve config changes typically have a lock time (\~4 hours) before they take effect on-chain. Plan parameter changes ahead of testing windows; the change won't be live immediately even after the multisig executes. > [tab] SDK > > > [!NOTE] > > > > **Reserve creation and configuration are not available via the TypeScript SDK.** Use the Kamino CLI for these admin operations. The SDK supports reading reserve data and building borrower-facing transactions. > > For reading FR-specific reserve fields: > > ```typescript theme={"theme":"css-variables"} > import { KaminoReserve, Reserve } from '@kamino-finance/klend-sdk'; > > const reserve = await KaminoReserve.fetch(rpc, reserveAddress); > const kind = reserve.getKind(); > > if (kind.isFixedRate()) { > console.log({ > borrowRateBps: kind.borrowRateBps, > debtTermSeconds: kind.debtTermSeconds.toString(), > fixedHostRate: reserve.getFixedHostInterestRate().toString(), > }); > } > ``` > > For market-level discovery: > > ```typescript theme={"theme":"css-variables"} > import { KaminoMarket } from '@kamino-finance/klend-sdk'; > > const market = await KaminoMarket.load(rpc, marketAddress); > > // All reserves for a debt token, split by rate model: > const allUsdcReserves = market.getReservesByMint(usdcMint); > const floatingUsdcReserves = market.getFloatReservesByMint(usdcMint); > const fixedUsdcReserves = market.getFixedReservesByMint(usdcMint); > ``` > [tab] API > > > [!NOTE] > > > > **Reserve creation and configuration are not available via the REST API.** Use the Kamino CLI. The API supports reading reserve metrics and historical data. > > To read raw reserve account data including FR-specific fields: > > ```bash theme={"theme":"css-variables"} > GET /kamino-market/reserves/account-data > ``` > > Returns base64-encoded reserve accounts. Decode using the SDK's `Reserve` codegen to access `hostFixedInterestRateBps`, `debtTermSeconds`, `debtMaturityTimestamp`, and `earlyRepayRemainingInterestPct`. The standard metrics endpoint `GET /kamino-market/{pubkey}/reserves/metrics` does not currently surface these fields. ## What's next > [card] [Market Settings](/curators/markets/fixed-rates/market-settings) > > Enable the market-level features that fixed-rate reserves depend on. > [card] [Lifecycle Operations](/curators/markets/fixed-rates/lifecycle-operations) > > Update or sunset an existing fixed-rate reserve. # Risk Considerations Source: https://docs.kamino.com/curators/markets/fixed-rates/risk Risks specific to running fixed-rate reserves and the parameters that mitigate them Running a fixed-rate reserve introduces a few risk surfaces that don't exist for floating reserves. This page is the framework for thinking about them and the parameters you control to manage them. ## Risk-mitigation matrix | Risk | Description | Mitigation | | - | - | - | | **Term too short for asset volatility** | A 1-month term on a volatile collateral may not give borrowers enough time to manage drawdowns through one cycle. | Match term to collateral volatility profile. Stable collateral can carry longer terms; volatile collateral should be capped at shorter durations. | | **Rate too low → no demand** | Set below floating-market clearing rates and conditional liquidity won't be deployed; reserve sits empty. | Reference the floating reserve's recent borrow rate and add a small term premium. Adjust based on the rate grid's emerging shape. | | **Rate too high → no fills** | Set well above floating, and vaults won't allocate, borrowers won't post matching orders. | Same — calibrate against the floating curve. | | **Insufficient rollover window** | Window too short for the keeper bot to clear a maturity cohort. | Set windows long enough to accommodate the largest expected cohort. Watch keeper success rates as live signal. | | **Throttle ramp too aggressive** | Liquidatable fraction climbs faster than borrowers can react after a missed rollover. | Pair `term_based_full_liquidation_duration_secs` with reasonable bonus parameters. The ramp should give voluntary repay time before forced unwind. | | **`mature_reserve_debt_liquidation_enabled` flipped on prematurely** | A reserve passes its `debt_maturity_timestamp` and immediately becomes fully liquidatable with no warning. | Coordinate the maturity-liquidation flag with reserve maturity dates. Only enable when liquidator infrastructure is ready and the maturity is intentional. | | **Stale `host_fixed_interest_rate_bps`** | Setting a non-zero host fixed rate creates a permanent protocol spread on top of the curve, invisible to lenders looking at the curve alone. | Default `host_fixed_interest_rate_bps` to `0` unless the protocol-side spread is intentional. Document publicly when non-zero. | | **Liquidation bonus parameters unset** | Without `min_deleveraging_bonus_bps` / `deleveraging_bonus_increase_bps_per_day` / `max_liquidation_bonus_bps`, post-maturity liquidations carry no incentive. | Configure all three on every fixed-rate reserve. Mirror typical floating-reserve values, adjusted for the protocol-enforced nature of these liquidations. | ## Pricing the rate The fixed rate you set should fall in a corridor: * **Floor:** the floating reserve's expected average borrow rate over the term — below this and lenders prefer floating. * **Ceiling:** what borrowers will actually accept — above this and demand evaporates. Read the floating reserve's recent borrow-rate history (over a duration matching your fixed term) and add the term premium you observe in adjacent cells of the rate grid. If you're the first reserve at that duration, start near the floating rate's recent average and adjust as demand develops. ## Calibrating windows Two windows work together — the pre-expiration rollover window and the post-expiration liquidation throttle. * **Rollover window** should be long enough that the keeper can rollover an entire maturity cohort even under network congestion. Default suggestion: 24 hours. Shorter than 4 hours starts risking missed cohorts. * **Liquidation throttle** should be long enough that a borrower who missed the rollover window has time to come back, repay, and exit cleanly. Default suggestion: 2–7 days. Shorter creates a cliff; longer means matured capital sits unproductive. Together, the two define the borrower's "off-ramp" between voluntary action and forced liquidation. A reasonable shape: rollover window 24h, throttle 3 days, bonus ramp from 50 bps at term-end to 500 bps over the throttle duration. ## Calibrating bonuses The liquidator's incentive ramp is governed by three reserve-level parameters: * `min_deleveraging_bonus_bps` — what a liquidator earns at term-end + 0 seconds. * `deleveraging_bonus_increase_bps_per_day` — how fast the bonus grows. * `max_liquidation_bonus_bps` — the cap. Set these such that: * The bonus is just attractive enough at the start of the throttle that a fast liquidator will take action. * The bonus grows enough across the throttle window that a slow liquidator is incentivised to act before others outrun them. * The cap is high enough to ensure the liquidation actually clears even on adverse market movement. Mirror your floating-reserve liquidation-bonus shape, then tune slightly — protocol-enforced liquidations typically warrant slightly higher bonuses since they're not price-driven. ## Coordinating with vault curators Vaults are the primary source of fixed-rate liquidity (both Standard and Conditional). Operational coordination matters: * **Communicate parameter changes ahead of the lock time** so vault curators can adjust. * **Surface new fixed-rate reserves** through your curator-relations channel before going live, so vault curators can plan allocation strategy. * **Confirm vault versions support withdrawal-queue accounting** before enabling the queue features. Vaults running older kvault versions cannot interact correctly with queued tickets. ## What's next > [card] [Reserve Configuration](/curators/markets/fixed-rates/reserve-configuration) > > Back to the reserve creation walkthrough. > [card] [Allocator's view](/curators/vaults/fixed-rates) > > How vault curators allocate into the reserves you create. # Glossary Source: https://docs.kamino.com/curators/markets/glossary Definitions for terms used across Kamino Markets documentation | Term | Definition | | - | - | | **Auto-Deleverage** | Margin-call mechanism that gives a borrower a grace period to self-deleverage before forced liquidation. Configured per reserve and at the market level. | | **Bad Debt** | A position where debt value exceeds collateral value; even a fully-priced liquidation cannot make the depositor whole. Triggers the `badDebtLiquidationBonusBps` and may require socialize-loss to clear. | | **Borrow Factor** | A multiplier on the debt-side valuation of an asset (`borrowFactorPct`). `100` = no adjustment; values above `100` make borrowing the asset more expensive in risk terms. | | **Borrow Order** | A limit-order request placed by a borrower specifying max acceptable rate, min term, and expiry. Lenders fill it via `fill-borrow-order`. One open order per obligation. | | **Borrow Rate Curve** | Piecewise linear function mapping reserve utilization to borrow rate. Defined as up to 11 `(utilizationRateBps, borrowRateBps)` breakpoints. | | **Cached Owner** | The `lending_market_owner_cached` field. A staging slot used in the two-step ownership transfer flow. | | **Close Factor** | The maximum portion of debt a liquidator can repay in a single liquidation round. Configured market-wide via `liquidation_max_debt_close_factor_pct`. | | **Collateral Farm** | A reward farm attached to a reserve that distributes incentives to depositors. | | **Crank** | Off-chain bot that triggers on-chain state updates (interest accrual, oracle refreshes, queue progression). | | **cToken** | Receipt token issued to depositors representing their share of a reserve's deposits. Burned on withdrawal. | | **Debt Farm** | A reward farm attached to a reserve that distributes incentives to borrowers. | | **Debt Maturity Timestamp** | The Unix timestamp at which all debt on a fixed-term reserve matures. `0` = per-borrow rolling term. | | **Debt Reserve** (in eMode) | The single reserve that members of an elevation group are permitted to borrow. | | **Debt Term Seconds** | Duration of fixed-term borrows on a reserve. `0` = open-term (no maturity). | | **Early Repay Penalty** | A penalty (`earlyRepayRemainingInterestPct`) applied when a fixed-term borrower repays during the first term before maturity. Charged as a percentage of remaining interest. After rollover, no penalty applies. | | **Elevation Group** (eMode) | A cluster of correlated assets with relaxed risk parameters when used together. Up to 32 groups per market. | | **Emergency Council** | A separate authority (often a fast-response multisig) configured via `emergency_council` to call emergency-only handlers. | | **Emergency Mode** | Market-wide or reserve-level pause. Halts most operations until reset. Reversible. | | **Flash Loan** | An uncollateralized loan that must be borrowed and repaid within the same transaction. | | **Heuristic** (price) | Sanity bounds for an oracle price. Set via `tokenInfo.heuristic.{lower, upper, exp}`. Rejects prices outside the band. | | **Host Fixed Interest Rate** | A fixed-rate add-on (`hostFixedInterestRateBps`) on top of the IR curve, charged on fixed-term reserves. | | **Immutable** | A one-way market flag (`immutable: 1`) that permanently blocks all curator-side updates. Irreversible. | | **Insolvency Risk LTV** | The LTV (`insolvency_risk_unhealthy_ltv_pct`) at which a position is considered to be in insolvency-risk territory and may be marked for auto-deleverage. | | **IR Curve** | See **Borrow Rate Curve**. | | **Kink** | The breakpoint on the borrow rate curve where rates start climbing steeply. Used to keep utilization at a target level. | | **klend** | The Kamino lending program. The on-chain Anchor program that defines markets, reserves, obligations, and the lending operations. | | **kvault** | The Kamino vault program. Optional layer that sits on top of klend markets, aggregating depositor capital and routing it across reserves. | | **KFarms** | The Kamino farms program. Manages reward distribution to klend depositors and borrowers. | | **Lamports** | The smallest unit of a token on Solana. `1 SOL = 10^9 lamports`. Reserve caps and on-chain values are denominated in token base units (lamports for SOL, smallest unit for other mints). | | **Lending Market** | The top-level on-chain account that groups reserves. Has its own owner, settings, and reserve set. The `LendingMarket` Rust struct. | | **Liquidation Threshold** | The LTV at which a position becomes liquidatable. Per-reserve via `liquidationThresholdPct`; can be overridden by an elevation group. | | **Loan-to-Value (LTV)** | Maximum borrowing capacity against collateral, as a percent of collateral USD value. Per-reserve via `loanToValuePct`. | | **Margin Call Period** | Grace period (`deleveragingMarginCallPeriodSecs`) between when a position is marked for auto-deleverage and when liquidation becomes available. | | **Mature Debt** | Fixed-term debt that has passed its `debt_maturity_timestamp`. Liquidatable as mature debt if the relevant flags are set. | | **Min Initial Deposit** | Market-level threshold (`min_initial_deposit_amount`) for the first deposit on an obligation. Prevents dust-spam attacks. | | **Min Net Obligation Value** | Market-level threshold (`min_net_value_in_obligation_sf`) for the residual value after any operation. Operations that would leave less are rejected. | | **Mirror Token** | An on-chain token that represents an off-chain asset 1:1. Typically minted in full at issuance with mint authority subsequently revoked. | | **Multisig** | Multi-signature wallet requiring multiple approvals to execute transactions. Kamino recommends [Squads v4](https://squads.so) for production market ownership. | | **Obligation** | The on-chain account tracking a user's deposits and borrows in a market. Per-user, per-market, per-obligation-type. | | **Obligation Order** | A user-set, price-triggered self-deleverage instruction stored on an obligation. Fired by permissionless executors when the condition is met. | | **Oracle** | External price feed providing asset valuations. Kamino prices reserves through Scope, configured per reserve via `tokenInfo`. | | **Origination Fee** | Fee charged at borrow time, configured via `fees.borrowFee`. | | **Permissioned Market** | A market where access is gated. On-chain klend has no allowlist field; permissioning today is achieved via Token-2022 transfer hooks, UI gating, or vault-layer terms acceptance. First-class support is on the roadmap. | | **Price Heuristic** | See **Heuristic**. | | **Progress Callback** | An optional callback on `WithdrawTicket` invoked when a ticket is fully redeemed. Used by kvault to update vault-side accounting. | | **Proposer Authority** | An authority (`proposer_authority`) that can propose certain config updates without holding full owner privileges. | | **Protocol Fee** | Fees accrued by the curator from interest take rate, origination, flash loans, liquidations, and order executions. Withdrawn via `redeem-fees`. | | **Quote Currency** | The reference unit for prices on a market. Stored on `LendingMarket.quote_currency`. Almost always `"USD"`. | | **Receipt Token** | Token issued by a vault to depositors representing their share of vault assets. Distinct from cTokens (which are reserve-level deposit receipts inside klend). | | **Referral Fee** | Portion of borrow interest, in basis points (`referral_fee_bps`), routed to integrators registered as referrers. | | **Reserve** | A specific lending pool inside a market for a single token. Holds deposits, borrows, the IR curve, oracle config, and risk parameters for that asset. | | **Reserve Status** | Reserve-level flag with values `0` Active, `1` Obsolete, `2` Hidden. | | **Rollover** | Migrating a fixed-term position to a new term (fixed→fixed, fixed→open, or open→fixed). Subject to market-level rollover window settings. | | **Scope** | Kamino's oracle aggregator. Combines Chainlink and Pyth Pro into a manipulation-resistant chain of price indices. | | **Sequence Number** (queue) | The position number assigned to a `WithdrawTicket` when it enters the queue. Tickets are redeemable in FIFO sequence-number order. | | **Socialize Loss** | The `socialize_loss` instruction that distributes unrecoverable bad debt across a reserve's depositors. Last-resort, irreversible. | | **Squads** | Solana multisig product. Kamino's recommended multisig solution for production market ownership. | | **Take Rate** | Protocol's cut of interest accrual, configured per reserve via `protocolTakeRatePct`. | | **Timelock** | Delay between proposal creation and execution on a Squads multisig. Kamino reference: 12h on SOL/BTC Market, 4h on satellite markets. | | **Token-2022** | The SPL Token-2022 program. Supports token extensions including transfer hooks. Used for regulated and compliance-constrained tokens on klend. | | **Transfer Hook** | A Token-2022 extension that invokes an external program on every transfer. The hook program can approve or reject the transfer based on custom logic. | | **TWAP** | Time-Weighted Average Price. A smoothed price that mitigates manipulation. Configured via `maxAgeTwapSeconds` and `maxTwapDivergenceBps`. | | **Utilization Rate** | The ratio `borrowed / deposited` on a reserve. Drives the borrow rate via the IR curve. | | **Withdrawal Cap** | Per-reserve, per-interval limit on net flow. Two independent caps: `depositWithdrawalCap` (collateral side), `debtWithdrawalCap` (debt side). | | **Withdraw Queue** | Reserve-level FIFO queue for withdrawals when a reserve is fully utilized. Counters: `next_issued_ticket_sequence_number`, `next_withdrawable_ticket_sequence_number`. | | **Withdraw Ticket** | Per-user account representing a position in the withdrawal queue. Holds the depositor's queued collateral and their sequence number. | ## Reference * [Reserve config reference](/curators/markets/reserve-parameters) * [Market config reference](/curators/markets/market-config-reference) * [Lifecycle overview](/curators/markets/lifecycle) # Curator Markets Source: https://docs.kamino.com/curators/markets/index Deploy and operate isolated lending markets on Kamino A Kamino market is a deployable, isolated instance of the Kamino lending program (klend). You own it, you configure its reserves, you set its risk parameters, you choose its oracles, you transfer it to a multisig, and you run it. Each market is independent. Liquidations, interest accrual, and risk surface all stay inside its boundaries — a position in your market has no exposure to any other Kamino market. ## Anatomy of a market A Kamino market is composed of three layers. The **`LendingMarket`** is the top-level account you own. It holds the configuration that applies across the market: name, owner, emergency flags, the elevation-group definitions, the close-factor and other liquidation tunables, the cosigner authority for permissioning. Every reserve underneath it inherits these settings. A **reserve** is a per-asset lending pool listed inside the market. Each reserve sets its own LTV, liquidation threshold, borrow factor, IR curve, oracle config, and deposit/borrow capacity. A market holds one reserve per token; a market that lists USDC, USDT, SOL, mSOL, and JLP has five reserves. A **`KaminoVault`** is an optional layer that sits on top. A vault accepts a single deposit token, routes capital across one or more reserves according to allocation weights, and issues a single receipt token to depositors. Vaults exist outside the market account itself; deploy a vault when your depositors should see a single-token deposit UX, with allocation across reserves handled automatically. ## Who deploys a market > [card] Institutions > > Run a lending venue with risk parameters, asset selection, and oracle configuration tuned to your mandate. Transfer ownership to a multisig and operate via signed proposals. > [card] Asset issuers > > Scale on-chain usage of your token by listing it as collateral or debt with parameters you control. Supports SPL Token and SPL Token-2022, including transfer hooks for permissioned tokens. > [card] Fintechs > > Deploy a market for the assets your app supports, surface it in your own UI, and offload program correctness, oracle integrity, and liquidator economics to klend. > [card] Curators with a thesis > > Run a market expressing a specific view on assets, leverage, and risk. Add reserves selectively, tune the IR curves, layer farms for incentives. ## What you control | Surface | Examples | | - | - | | Asset selection | Which reserves exist, mint program (SPL Token or Token-2022), transfer hook compatibility | | Risk parameters | LTV, liquidation threshold, borrow factor, deposit and borrow caps, IR curve | | Oracle configuration | Scope, TWAP guards, staleness limits, price heuristic bands | | Liquidation behavior | Close factor, max debt liquidatable per tx, bonus min/max, bad-debt bonus | | Optional features | Withdrawal queue, borrow orders, obligation orders, eMode groups, permissioning, fixed rate reserves | | Incentives | Collateral and debt farms per reserve, reward emissions | | Governance | Owner pubkey (single key or multisig), emergency council, immutability | | Operations | Updating reserves, pausing the market, withdrawing protocol fees, transferring obligations | ## What klend gives you | Layer | Provided by klend | | - | - | | Program correctness | Audited Anchor program with formal verification and fuzzing | | Interest accrual | Per-reserve compound interest, host-fixed rate optional | | Liquidator economy | Permissionless liquidations across all markets sharing the program | | Oracle plumbing | Scope aggregator, multi-source TWAP, staleness checks | | Risk safeguards | Auto-deleverage, daily withdrawal caps, eMode | | Composability | Any wallet, vault, or program can integrate with the on-chain market accounts | ## Market vs. vault Both are curator-deployed. The decision tree: | You want to... | Deploy a... | | - | - | | Create a new lending venue with your own reserve set and risk model | Market | | List an asset that doesn't exist on any market today | Market (with that reserve) | | Run a strategy that allocates capital across reserves on existing markets | Vault | | Wrap your strategy in a single-token deposit / receipt-token withdraw UX | Vault on top of one or more markets | | Provide gated access to a curated set of reserves for your users | Vault (Whitelisted Reserves feature) | A vault on top of a market is a common composition. The market does the lending mechanics; the vault does the depositor UX, allocation logic, and fee collection. See the [Create a vault](/curators/vaults/guides/create-a-vault) guide for vault-specific documentation. ## Where to go next > [card] [Lifecycle overview](/curators/markets/lifecycle) > > The full path from create → operate → migrate, in one page. > [card] [Quickstart](/curators/markets/quickstart) > > Stand up a working market on staging in \~10 minutes. > [card] [Create a market](/curators/markets/creating-a-market) > > The single CLI command and what it does on-chain. > [card] [Risk parameters](/curators/markets/risk-parameters) > > How to choose LTV, thresholds, IR curves, and caps for a new asset. > [card] [Withdrawal queue](/curators/markets/withdrawal-queue) > > FIFO redemption when reserves are fully utilized. > [card] [Fixed rate reserves](/curators/markets/fixed-rate-reserves) > > Maturity-based debt, host fixed rate, rollover windows, early-repay penalties. > [!NOTE] > > All market creation and configuration runs through the Kamino Manager CLI (`kamino-manager`). The web app at [manage.kamino.com](https://manage.kamino.com) is for managing existing vaults; market deployment is CLI-driven and signed via a [Squads](https://squads.so) multisig in production. # Lifecycle Overview Source: https://docs.kamino.com/curators/markets/lifecycle The full path from market creation to day-2 operations Setting up a Kamino market splits cleanly into two phases. Phase 1 is **market setup**: a small, fixed set of global, one-time actions that bring a market into existence and put it under multisig control. Phase 2 is **reserve setup**: the per-asset configuration work, repeated once for each token you want to list. Almost every meaningful risk decision a curator makes is at the reserve level. After that, you operate the market: ongoing reserve updates, optional feature toggles, incident response. ## Phase 1 · Market setup (global) Three actions, done once. Nothing here touches a specific asset. **1. Create the market** Run `create-market`. The CLI returns a market address. The market exists on-chain but has no reserves yet, so it accepts nothing. → [Create a market](/curators/markets/creating-a-market) **2. Set market-wide config** Set the market name, referral fee, emergency council, and any other market-level fields you want to override from defaults. Most curators take defaults and revisit this only when a specific market-wide flag needs flipping. → [Market settings](/curators/markets/market-settings) **3. Transfer ownership to a multisig** Move the `lending_market_owner` from your hot wallet to a Squads multisig. Two-step: cache the new owner, then promote it. From here on, every market or reserve update goes through a multisig proposal. → [Transfer to multisig](/curators/markets/transfer-to-multisig) ## Phase 2 · Reserve setup (per asset) The bulk of curator work. Repeat for each token you want to list. Each reserve has its own LTV, liquidation threshold, IR curve, oracle config, capacity caps, fees, and farm wiring; risk decisions are made here, per asset. **1. Add the reserve** Submit `add-asset-to-market` with a reserve config JSON for the asset's mint. The reserve account is created on-chain with its initial parameters. → [Add a reserve](/curators/markets/adding-reserves) **2. Configure the oracle** Wire the reserve to a Scope price feed and set TWAP and staleness guards. → [Configure oracles](/curators/markets/configuring-oracles) **3. Set risk parameters** LTV, liquidation threshold, borrow factor, IR curve, deposit and borrow caps, liquidation bonus min/max. → [Risk parameters](/curators/markets/risk-parameters) **4. Set withdrawal caps (optional)** Per-interval flow limits on the reserve. Useful for newly-listed assets and regulated tokens. → [Withdrawal caps](/curators/markets/withdrawal-caps) **5. Wire farms and rewards** Most curators set up at least a collateral farm at launch to attract depositors. Debt farms are optional, used to subsidize borrowing. → [Farms & rewards](/curators/markets/farms-and-rewards) **6. Make it a fixed rate reserve (optional)** For lending venues that offer fixed-rate / fixed-term debt: set `debt_term_seconds`, `host_fixed_interest_rate_bps`, and the early-repay penalty on the reserve, and the rollover windows on the market. → [Fixed rate reserves](/curators/markets/fixed-rate-reserves) ## Phase 3 · Optional features Features that toggle on top of a market. Most curators leave them off by default; enable per the use case. | Feature | When it makes sense | | - | - | | [Liquidations](/curators/markets/liquidations) | Tuning beyond defaults — close factor, value caps, pause flags. Most curators take defaults | | [Withdrawal queue](/curators/markets/withdrawal-queue) | Reserves expected to run at high utilization, or institutional vaults sitting on top | | [Borrow orders](/curators/markets/borrow-orders) | Peer-to-peer fixed-rate matching between borrowers and lenders | | [Obligation orders](/curators/markets/obligation-orders) | Letting users set their own price-triggered self-deleverage rules | | [Auto-deleverage](/curators/markets/auto-deleverage) | Niche: markets where you specifically want a margin-call grace window before liquidations open up | | [Elevation groups (eMode)](/curators/markets/elevation-groups) | Niche: correlated-asset clusters where higher LTV is appropriate | | [Permissioned markets](/curators/markets/permissioned-markets) | Gated venues — KYC'd depositor base, accredited-investor restrictions, app-internal markets | A minimal market (one reserve, defaults across the board, no advanced features) is fully functional. Reach for these only when there's a use case. ## Phase 4 · Operate After the market is live, the recurring operations: | Cadence | Action | | - | - | | Daily / weekly | Monitor utilization, oracle health, liquidations, fee accrual | | Weekly / monthly | Adjust deposit and borrow caps as TVL grows | | As needed | Update IR curve, add a new reserve, enable a new feature, rotate the multisig signer set | | Quarterly | Withdraw protocol fees | | Incident | Pause the market via `borrow_disabled` or `emergency_mode`; run socialize-loss if a position becomes irrecoverable | Every change after the multisig transfer goes through a Squads proposal subject to the configured timelock. → [Updating reserves](/curators/markets/reserve-management) · [Emergency controls](/curators/markets/emergency-controls) · [Withdrawing protocol fees](/curators/markets/protocol-fees) ## What's mandatory before deposits can happen Phase 1 + at least one reserve fully through Phase 2: | Requirement | Where it's set | | - | - | | Market account exists | `create-market` | | At least one reserve added | `add-asset-to-market` | | Reserve has a working Scope oracle | Reserve config `tokenInfo` | | Reserve `status = 0` (Active) | Reserve config `status` | | Reserve `depositLimit > 0` | Reserve config | | Reserve `borrowLimit > 0` (if borrows allowed) | Reserve config | | Owner is the wallet (or multisig) you intend to operate from | `update-lending-market-owner` | Multisig ownership transfer is not strictly enforced by the program. It is the production prerequisite Kamino recommends before any external user touches the market. ## Where the work happens | Surface | Use it for | | - | - | | `kamino-manager` CLI | All market and reserve creation, configuration, and updates | | [Squads](https://squads.so) | Multisig proposal creation, signing, execution | | Solana Explorer | Verifying transactions, inspecting account state | | `manage.kamino.com` | Vault-side curator UI (for vaults sitting on top of your market) | | `app.kamino.com` | Public-facing UI for users (markets surface here only after listing in Kamino's resources file) | ## Continue > [card] [Quickstart](/curators/markets/quickstart) > > Stand up a working market on staging in \~10 minutes. > [card] [Create a market](/curators/markets/creating-a-market) > > The single CLI command and what it does on-chain. # Liquidations Source: https://docs.kamino.com/curators/markets/liquidations Configure liquidation thresholds, close factors, bonuses, and bad-debt handling When a borrower's health crosses `liquidationThresholdPct`, their position becomes liquidatable. klend exposes a set of curator-tunable parameters governing how aggressively liquidations happen and how much liquidators earn for clearing positions. This page covers the market-level and reserve-level fields that shape liquidator behavior. For threshold setting and IR curve choices, see [Risk parameters](/curators/markets/risk-parameters). For the auto-deleverage (margin call) mechanism, see [Auto-deleverage](/curators/markets/auto-deleverage). ## The liquidation flow at a glance When a borrower's LTV crosses `liquidationThresholdPct`, the position becomes liquidatable. Any wallet can call `liquidate-obligation-and-redeem-reserve-collateral` against it. In a single instruction, the liquidator repays up to `close_factor × debt`, seizes collateral of equal value plus the configured bonus, and the obligation is restored at or above the liquidation threshold. Liquidations are permissionless: the program holds the safety net, an open market of liquidators races to act on it. ## Close factor and value caps (market-level) Tunables on `LendingMarket`: ```jsonc theme={"theme":"css-variables"} { "liquidation_max_debt_close_factor_pct": 25, "max_liquidatable_debt_market_value_at_once": "", "min_full_liquidation_value_threshold": "", "min_value_skip_liquidation_ltv_checks": "", "min_value_skip_liquidation_bf_checks": "" } ``` | Field | What it does | | - | - | | `liquidation_max_debt_close_factor_pct` | Maximum portion of debt a liquidator can repay in a single liquidation, in percent. Default `25` means a borrower's position can be liquidated by 25% per round. Lower values protect borrowers from one-shot wipeout; higher values let liquidators clear damaged positions faster | | `max_liquidatable_debt_market_value_at_once` | Hard ceiling on market-value liquidated per liquidation (in the market's quote currency, scaled). Throttles whale liquidations to prevent a single liquidator from clearing too much at once | | `min_full_liquidation_value_threshold` | Below this debt market value, the close-factor cap is bypassed and the entire position can be liquidated. Used to cleanly clear dust positions where partial liquidation is uneconomical | | `min_value_skip_liquidation_ltv_checks` | Below this market value, the program skips the LTV health check during liquidation. Allows a liquidator to clear a dust position regardless of whether it's underwater on standard checks | | `min_value_skip_liquidation_bf_checks` | Same idea for the borrow-factor check | ### Tuning the close factor Default close factor of 25% is sized so a borrower has multiple rounds to add collateral or repay before being fully wiped out. Each liquidation round drives the position back toward health; if the market continues moving against them, subsequent rounds re-engage. Reasons to deviate: | Setting | Use case | | - | - | | `15-25%` | Default. Borrower-protective | | `30-50%` | Faster cleanup of unhealthy positions; appropriate for high-volatility assets where multi-round liquidation creates more risk than it prevents | | `100%` | Single-round full liquidation. Use only for fixed-term reserves at maturity, or in incident response | ## Liquidation bonus (reserve-level) Liquidator incentive lives on each reserve: ```jsonc theme={"theme":"css-variables"} { "minLiquidationBonusBps": 500, "maxLiquidationBonusBps": 1000, "badDebtLiquidationBonusBps": 99, "protocolLiquidationFeePct": 0 } ``` | Field | What it does | | - | - | | `minLiquidationBonusBps` | Floor on the bonus a liquidator earns. Applied when a position is just past Liquidation LTV | | `maxLiquidationBonusBps` | Cap on the bonus. The bonus scales with the LTV breach depth but cannot exceed this value | | `badDebtLiquidationBonusBps` | Near-insolvency bonus applied when LTV reaches 99% or higher. Set low (\~1%) because near-insolvent positions cannot sustain a large bonus without creating bad debt | | `protocolLiquidationFeePct` | Percentage (0–100) of liquidation proceeds that route to protocol fees; the liquidator receives the remainder | Reference values: | Asset class | min | max | bad debt | | - | - | - | - | | Stablecoins (in eMode) | 100 (1%) | 200 (2%) | 99 (≈1%) | | Major liquid (SOL, BTC, ETH) | 300–500 (3–5%) | 700–1000 (7–10%) | 99 | | Long-tail | 500–800 | 1500–2500 | 99 | The on-chain bonus is calculated in three steps (all values in bps, where 10,000 bps = 100%): 1. **Floor**: `bonus = max(minLiquidationBonusBps, currentLTV_bps - liquidationLTV_bps)`. The bonus is at least the min, and grows with the depth of the LTV breach. 2. **Cap**: `bonus = min(bonus, maxLiquidationBonusBps)`. The bonus cannot exceed the reserve's max. 3. **Solvency cap**: `bonus = min(bonus, 10000 - currentLTV_bps)`. Near 100% LTV, the bonus is reduced so that the liquidation does not push the position into bad debt. When LTV exceeds the market's insolvency-risk threshold (typically \~95%), the close factor increases to 100% to allow full liquidation. When LTV reaches 99% or higher, the bonus switches to `badDebtLiquidationBonusBps`, enabling full liquidation at a minimal bonus to maximize recovery before insolvency; the solvency cap above still applies. ## Pausing liquidations ```jsonc theme={"theme":"css-variables"} { "price_triggered_liquidation_disabled": 0 } ``` | Value | Effect | | - | - | | `0` | Default. Liquidations triggered by price movement are allowed | | `1` | All price-triggered liquidations are blocked. Use during oracle incidents to prevent cascading liquidations on bad prices | This is a market-level kill switch. Combine with `borrow_disabled` for full incident-mode posture. See [Emergency controls](/curators/markets/emergency-controls). ## Liquidations on mature fixed-term debt ```jsonc theme={"theme":"css-variables"} { "mature_reserve_debt_liquidation_enabled": 1, "obligation_borrow_debt_term_liquidation_enabled": 1, "term_based_full_liquidation_duration_secs": 0 } ``` These flags govern liquidation of fixed-term positions. See [Fixed rate reserves](/curators/markets/fixed-rate-reserves) for details. ## Bad debt and socialized loss If a position can't be liquidated cleanly — collateral falls below debt and even the bad-debt bonus doesn't cover the gap — the curator (or `emergency_council`) can call `socialize-loss` to spread the loss across the affected reserve's depositors. This is an irreversible, depositor-affecting action. Use it only when: * The position is genuinely unrecoverable * All standard liquidation paths have been exhausted * The affected reserve has a credible loss-recovery plan (insurance, treasury backfill, etc.) `socialize-loss` is callable by the `lending_market_owner` or, if configured, the `emergency_council`. See [Emergency controls](/curators/markets/emergency-controls). ## Reference * [Reserve config reference](/curators/markets/reserve-parameters) — every reserve-level liquidation field * [Market config reference](/curators/markets/market-config-reference) — every market-level liquidation field * [Risk parameters](/curators/markets/risk-parameters) — choosing LTV, threshold, IR curve * [Auto-deleverage](/curators/markets/auto-deleverage) — margin-call grace window (advanced) * [Emergency controls](/curators/markets/emergency-controls) — pausing the market, socialize-loss # Market Config Reference Source: https://docs.kamino.com/curators/markets/market-config-reference Every editable field on the LendingMarket account This is the canonical reference for `LendingMarket` — the on-chain struct that holds market-level settings. Field names below use snake_case as they appear in the JSON returned by `download-lending-market-config` (which mirrors the on-chain Rust struct directly). For guidance on which fields to set, see [Market settings](/curators/markets/market-settings) and the topic-specific guides linked below. ## Identity and naming | Field | Type | Description | | - | - | - | | `version` | u64 | Program version, fixed at init | | `bump_seed` | u64 | PDA bump seed. Set at init | | `name` | UTF-8 string (≤32 bytes) | Human-readable market name. Editable via `update-lending-market-name` or full config update | | `quote_currency` | UTF-8 string (≤32 bytes) | Reference unit prices are denominated in. Almost always `"USD"` | ## Ownership | Field | Type | Description | | - | - | - | | `lending_market_owner` | Pubkey | Active market owner. Authorized for all updates | | `lending_market_owner_cached` | Pubkey | Staging slot for ownership transfer. The current owner sets it; only that pubkey can finalize the swap via `update-lending-market-owner` | | `emergency_council` | Pubkey | Optional separate authority for emergency-only handlers (e.g., `socialize_loss`) | | `proposer_authority` | Pubkey | Authority that can propose certain config updates without holding full owner privileges | | `immutable` | u8 (bool) | If `1`, all owner-side updates are permanently disabled. **Irreversible.** | ## Feature flags | Field | Type | Description | | - | - | - | | `borrow_disabled` | u8 (bool) | If `1`, new borrows are rejected market-wide. Existing positions continue | | `emergency_mode` | u8 (bool) | If `1`, market-wide emergency mode | | `autodeleverage_enabled` | u8 (bool) | If `1`, enables auto-deleverage market-wide. Per-reserve flag must also be set | | `price_triggered_liquidation_disabled` | u8 (bool) | If `1`, blocks all price-triggered liquidations | | `mature_reserve_debt_liquidation_enabled` | u8 (bool) | If `1`, allows liquidations of mature fixed-term debt | | `obligation_borrow_debt_term_liquidation_enabled` | u8 (bool) | If `1`, enables term-based liquidation flow specifically | ## Withdrawal queue | Field | Type | Description | | - | - | - | | `withdraw_ticket_issuance_enabled` | u8 (bool) | If `1`, users can call `enqueue-to-withdraw` | | `withdraw_ticket_redemption_enabled` | u8 (bool) | If `1`, users can call `withdraw-queued-liquidity` | | `withdraw_ticket_cancellation_enabled` | u8 (bool) | If `1`, users can call `cancel-withdraw-ticket` | | `min_withdraw_queued_liquidity_value` | u64 | Minimum USD value (scaled fraction) for a single ticket. Below this, `enqueue-to-withdraw` reverts | See [Withdrawal queue](/curators/markets/withdrawal-queue). ## Borrow orders | Field | Type | Description | | - | - | - | | `borrow_order_creation_enabled` | u8 (bool) | If `1`, users can call `set-borrow-order` | | `borrow_order_execution_enabled` | u8 (bool) | If `1`, lenders can call `fill-borrow-order` | | `min_borrow_order_fill_value` | u64 | Minimum USD value (scaled fraction) for a single fill | See [Borrow orders](/curators/markets/borrow-orders). ## Obligation orders | Field | Type | Description | | - | - | - | | `obligation_order_creation_enabled` | u8 (bool) | If `1`, users can call `set-obligation-order` | | `obligation_order_execution_enabled` | u8 (bool) | If `1`, executors can call `fill-obligation-order` | See [Obligation orders](/curators/markets/obligation-orders). ## Fixed-term rollover | Field | Type | Description | | - | - | - | | `fixed_term_rollover_window_duration_seconds` | u64 | Window before maturity allowing fixed→fixed rollover. `0` disables | | `open_term_rollover_window_duration_seconds` | u64 | Window before maturity allowing fixed→open rollover. `0` disables | | `obligation_borrow_migration_to_fixed_execution_enabled` | u8 (bool) | If `1`, allows open→fixed migration anytime | | `obligation_borrow_rollover_configuration_enabled` | u8 (bool) | If `1`, allows borrowers to pre-configure rollover behavior | | `min_partial_rollover_value` | u64 | Minimum USD value for a partial rollover. `0` requires full rollovers only | | `term_based_full_liquidation_duration_secs` | u64 | Time after maturity before full (close-factor-bypassing) liquidation is available. `0` disables | See [Fixed rate reserves](/curators/markets/fixed-rate-reserves). ## Liquidation tunables | Field | Type | Description | | - | - | - | | `liquidation_max_debt_close_factor_pct` | u8 (0–100) | Maximum portion of debt liquidatable per round | | `max_liquidatable_debt_market_value_at_once` | u64 | Hard ceiling on market value liquidated per liquidation | | `min_full_liquidation_value_threshold` | u64 | Below this debt market value, the close-factor cap is bypassed | | `insolvency_risk_unhealthy_ltv_pct` | u8 (0–100) | LTV threshold for the insolvency-risk auto-deleverage path | | `min_value_skip_liquidation_ltv_checks` | u64 | Below this market value, skip LTV health checks during liquidation | | `min_value_skip_liquidation_bf_checks` | u64 | Below this market value, skip borrow-factor health checks | | `individual_autodeleverage_margin_call_period_secs` | u64 | Default grace period (seconds) between margin call and forced liquidation | See [Liquidations](/curators/markets/liquidations) and [Auto-deleverage](/curators/markets/auto-deleverage). ## Elevation groups ```jsonc theme={"theme":"css-variables"} "elevation_groups": [ { "id": 1, "ltv_pct": 90, "liquidation_threshold_pct": 92, "max_liquidation_bonus_bps": 200, "allow_new_loans": 1, "max_reserves_as_collateral": 8, "debt_reserve": "" } // ... up to 32 entries ] ``` | Field | Type | Description | | - | - | - | | `id` | u8 (1–32) | Group identifier. `0` is the "no group" sentinel | | `ltv_pct` | u8 (0–100) | Group LTV; replaces per-reserve LTV for in-group positions | | `liquidation_threshold_pct` | u8 (0–100) | Group liquidation threshold | | `max_liquidation_bonus_bps` | u16 | Cap on liquidator bonus inside the group | | `allow_new_loans` | u8 (bool) | `0` blocks new borrows in the group; existing positions persist | | `max_reserves_as_collateral` | u8 | Maximum distinct collateral reserves a group-position may hold | | `debt_reserve` | Pubkey | Single permitted debt asset for the group | See [Elevation groups](/curators/markets/elevation-groups). ## Position thresholds | Field | Type | Description | | - | - | - | | `min_initial_deposit_amount` | u64 | Minimum amount required for a brand-new deposit to a reserve | | `min_net_value_in_obligation_sf` | u128 (scaled fraction) | Minimum USD value an obligation must hold after any operation | | `global_allowed_borrow_value` | u64 | Maximum total borrow value across all users on the market | ## Fees | Field | Type | Description | | - | - | - | | `referral_fee_bps` | u16 | Referral fee in basis points, shared with registered referrers | ## Oracle policy | Field | Type | Description | | - | - | - | | `price_refresh_trigger_to_max_age_pct` | u8 (0–100) | Percentage of `maxAgePriceSeconds` at which off-chain bots refresh proactively. `0` = on-demand only | ## Runtime / read-only These fields are program-managed and not user-editable: | Field | Type | Description | | - | - | - | | `version` | u64 | Program version | | `bump_seed` | u64 | PDA bump | | `reserved0`, `reserved1`, `padding1`, `padding2`, `elevation_group_padding` | varies | Struct alignment / future-use slots | ## Reading the live config ```bash theme={"theme":"css-variables"} yarn kamino-manager download-lending-market-config \ --lending-market ``` For market + every reserve in one call: ```bash theme={"theme":"css-variables"} yarn kamino-manager download-lending-market-config-and-all-reserves-configs \ --lending-market ``` ## Reference * [Market settings](/curators/markets/market-settings) — the workflow for editing these fields * [Reserve config reference](/curators/markets/reserve-parameters) — per-reserve fields * [CLI command index](/curators/markets/cli-command-index) — all market-related commands # Read Market Data Source: https://docs.kamino.com/curators/markets/market-data Query market state, reserve metrics, historical data, and rewards via API and SDK Market state is readable through three channels: the REST API (best for dashboards and monitoring), the TypeScript SDK (best for integrations that compute derived values on-chain), and direct Solana RPC reads (for the lowest-level access). Most curators use the API for monitoring and the SDK for any integration that needs to react to market state. ## Channels at a glance | Channel | Best for | Endpoint / package | | - | - | - | | REST API | Dashboards, alerts, integrations that need historical data | `https://api.kamino.finance` | | TypeScript SDK | Apps computing live APYs, building transactions, reacting to state | `@kamino-finance/klend-sdk` | | Direct RPC | Lowest-latency access, minimal dependencies | Solana RPC + the program's account decoders | ## List all markets ```typescript SDK theme={"theme":"css-variables"} // SDK loads individual markets by address; the API is the place to enumerate const response = await fetch('https://api.kamino.finance/v2/kamino-market'); const markets = await response.json(); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/v2/kamino-market ``` Returns the full set of klend markets the API knows about, with addresses and basic metadata. ## Market-wide TVL and totals ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const market = await KaminoMarket.load(rpc, address(''), slotDuration); console.log({ depositTVL: market!.getTotalDepositTVL().toString(), borrowTVL: market!.getTotalBorrowTVL().toString(), }); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kamino-market//reserves/metrics ``` ## Per-reserve metrics ```typescript SDK theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const market = await KaminoMarket.load(rpc, address(''), slotDuration); const slot = await rpc.getSlot().send(); for (const reserve of market!.getReserves()) { console.log(`Reserve ${reserve.symbol}:`); console.log(` Deposit TVL: ${reserve.getDepositTvl().toFixed(2)}`); console.log(` Borrow TVL: ${reserve.getBorrowTvl().toFixed(2)}`); console.log(` Borrow APY: ${reserve.totalBorrowAPY(slot)}%`); console.log(` Supply APY: ${reserve.totalSupplyAPY(slot)}%`); console.log(` Utilization: ${reserve.calculateUtilizationRatio()}%`); } ``` ```typescript API theme={"theme":"css-variables"} const response = await fetch( 'https://api.kamino.finance/kamino-market//reserves/metrics' ); const { reserves } = await response.json(); reserves.forEach((reserve: any) => { console.log({ address: reserve.reserve, symbol: reserve.symbol, depositTvl: reserve.metrics.depositTvl, borrowTvl: reserve.metrics.borrowTvl, supplyAPY: reserve.metrics.supplyInterestAPY, borrowAPY: reserve.metrics.borrowInterestAPY, }); }); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/kamino-market//reserves/metrics ``` ## Historical reserve metrics Historical time-series data is API-only. The SDK reads live state; the API serves historical series. ```typescript API theme={"theme":"css-variables"} const marketPubkey = ''; const reservePubkey = ''; const url = `https://api.kamino.finance/kamino-market/${marketPubkey}/reserves/${reservePubkey}/metrics/history`; const response = await fetch(url); const { history } = await response.json(); for (const item of history) { console.log({ timestamp: item.timestamp, symbol: item.metrics.symbol, supplyInterestAPY: item.metrics.supplyInterestAPY, borrowInterestAPY: item.metrics.borrowInterestAPY, depositTvl: item.metrics.depositTvl, borrowTvl: item.metrics.borrowTvl, }); } ``` ```bash curl theme={"theme":"css-variables"} curl "https://api.kamino.finance/kamino-market//reserves//metrics/history" ``` ## Rewards data The Kamino API exposes reward data such as active campaigns and per-user claimable amounts for klend reserves. ### All active reward programs ```typescript API theme={"theme":"css-variables"} const response = await fetch('https://api.kamino.finance/klend/rewards'); const rewards = await response.json(); console.log('Active KLend rewards:', rewards); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/klend/rewards ``` ### A user's claimable rewards across all reserves ```typescript API theme={"theme":"css-variables"} const userPubkey = ''; const response = await fetch( `https://api.kamino.finance/klend/users/${userPubkey}/rewards` ); const rewards = await response.json(); console.log('User rewards:', rewards); ``` ```bash curl theme={"theme":"css-variables"} curl https://api.kamino.finance/klend/users//rewards ``` ### Live farm state from the SDK For real-time emission rates and on-chain farm balances, read the KFarms `FarmState` directly: ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoMarket, getMedianSlotDurationInMsFromLastEpochs } from '@kamino-finance/klend-sdk'; import { FarmState } from '@kamino-finance/farms-sdk'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const market = await KaminoMarket.load(rpc, address(''), slotDuration); for (const reserve of market!.getReserves()) { const collFarm = reserve.getCollateralFarmAddress(); const debtFarm = reserve.getDebtFarmAddress(); if (collFarm) { const farmState = await FarmState.fetch(rpc, collFarm); console.log(`${reserve.symbol} collateral farm:`, farmState); } if (debtFarm) { const farmState = await FarmState.fetch(rpc, debtFarm); console.log(`${reserve.symbol} debt farm:`, farmState); } } ``` For the full APY calculation walkthrough, see [Calculate reserve reward APY](/build/tutorials/borrow/calculate-reserve-reward-apy). ## What the SDK exposes per reserve `reserve` instances loaded via `market.getReserves()` provide the following getters: | Method | Returns | | - | - | | `reserve.symbol` | Token symbol | | `reserve.address` | Reserve account pubkey | | `reserve.getDepositTvl()` | Total USD value deposited | | `reserve.getBorrowTvl()` | Total USD value borrowed | | `reserve.totalBorrowAPY(slot)` | Combined borrow APY (curve + host fixed) | | `reserve.totalSupplyAPY(slot)` | Supply-side APY paid to depositors | | `reserve.calculateUtilizationRatio()` | Borrowed / deposited, as a fraction | | `reserve.getCollateralFarmAddress()` | Farm address for the collateral side, or `null` | | `reserve.getDebtFarmAddress()` | Farm address for the debt side, or `null` | | `reserve.config` | The on-chain `ReserveConfig` (every editable parameter) | ## Direct RPC reads For the lowest-level access (minimal dependencies, fastest reads, no SDK abstraction), fetch the on-chain accounts directly via Solana RPC and decode them with the program's IDL or struct definitions. The relevant accounts: | Account | What it holds | | - | - | | `LendingMarket` | Market-level config + flags | | `Reserve` | Per-reserve config + live state (liquidity, collateral, withdraw queue) | | `Obligation` | Per-user position (deposits + borrows) | | `FarmState` | KFarms reward state for a collateral or debt farm | See [Programmatic integration](/curators/markets/programmatic-integration) for routing to the SDK and API documentation that covers each surface in depth. ## Reference > [card] [Full API Reference](/build/api-reference/introduction) > > OpenAPI-rendered reference for every endpoint > [card] [SDK examples](https://github.com/Kamino-Finance/klend-sdk/tree/master/examples) > > Working code examples in the klend-sdk repo > [card] [Programmatic integration](/curators/markets/programmatic-integration) > > Where to go for SDK / API / RPC integration docs > [card] [Farms & rewards](/curators/markets/farms-and-rewards) > > Curator-side farm management # Market Settings Source: https://docs.kamino.com/curators/markets/market-settings Configure market-level parameters: name, fees, flags, and global thresholds Market-level settings live on the `LendingMarket` account itself, separate from per-reserve config. They control the market's name, quote currency, referral fees, and dozens of feature flags and thresholds that apply to every reserve and every position. This page covers the routine settings. Topic-specific settings such as liquidation tunables, eMode groups, the withdrawal queue, fixed-term rollover windows, and borrow / obligation orders live on their own pages. > [tab] SDK > > ## Update market settings via SDK > > The SDK exposes `kaminoManager.updateLendingMarketIxs(signer, marketWithAddress, newLendingMarket)` for full market config updates. Fetch the current state, mutate the fields you care about, pass the new state in. > > **1. Initialize KaminoManager and fetch the market** > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > encodeTokenName, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > > const adminSigner = await parseKeypairFile('/path/to/admin.json'); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketAddress = address(''); > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > ``` > > **2. Mutate the fields you want to change** > > ```typescript theme={"theme":"css-variables"} > // Build the new state from the current state, change only what you intend to change > const newLendingMarket = { ...marketState }; > > // Examples — mix and match per your update: > newLendingMarket.name = encodeTokenName('My Market'); // up to 32 bytes UTF-8 > newLendingMarket.referralFeeBps = 100; // 1% referral fee > newLendingMarket.borrowDisabled = 1; // pause borrowing > newLendingMarket.minInitialDepositAmount = 1000n; // u64 > newLendingMarket.individualAutodeleverageMarginCallPeriodSecs = 86400n; // 24 hours > newLendingMarket.emergencyCouncil = address(''); > ``` > > **3. Build and submit the update** > > ```typescript theme={"theme":"css-variables"} > const updateIxs = kaminoManager.updateLendingMarketIxs( > adminSigner, > marketWithAddress, > newLendingMarket, > ); > > async function buildAndSendTx(ixs: any[]) { > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), > (tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > (tx) => appendTransactionMessageInstructions(ixs, tx) > ) > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > }); > } > > // The SDK splits large updates into multiple transactions for size reasons > for (const ix of updateIxs) { > await buildAndSendTx([ix]); > } > ``` > > The update only emits instructions for fields that actually changed against on-chain state. > > ### Multisig mode > > When the market is owned by a multisig, replace the admin signer with `noopSigner(multisigPubkey)`: > > ```typescript theme={"theme":"css-variables"} > import { noopSigner } from '@kamino-finance/klend-sdk'; > > const multisigSigner = noopSigner(address('')); > const updateIxs = kaminoManager.updateLendingMarketIxs(multisigSigner, marketWithAddress, newLendingMarket); > // Encode each ix as a base58 transaction and submit it as a Squads proposal > ``` > [tab] API > > > [!NOTE] > > > > **Updating market settings is not available via the REST API.** The Kamino API supports reading market state and reserve metrics; market configuration is an admin operation available through the **SDK** or **Kamino CLI**. > > To update market settings, use the **SDK** or **Kamino CLI** tabs. > > For reading market data via API, see [Read market data](/curators/markets/market-data). > [tab] Kamino CLI > > ## Update market settings via CLI > > All non-trivial market changes follow the download → edit → preview → execute cycle. > > **1. Download the current config** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-lending-market-config \ > --lending-market > ``` > > Saves to `./configs//market-.json`. This is the canonical, on-chain truth. > > **2. Edit the JSON** > > Change only the fields you intend to change. Leave everything else untouched. > > **3. Inspect** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode inspect > ``` > > Open the printed Solana Explorer URL; verify the diff matches your intent. > > **4. Execute or propose** > > Hot-wallet-owned: re-run with `--mode execute`. > > Multisig-owned: re-run with `--mode multisig --multisig `. Submit the printed base58 transaction as a Squads proposal. > > ### Focused commands > > For two common updates, focused CLI commands exist that touch fewer fields: > > ```bash theme={"theme":"css-variables"} > # Rename the market > yarn kamino-manager update-lending-market-name \ > --lending-market \ > --new-name "My Market" \ > --mode execute > > # Promote the cached owner (final step of multisig transfer) > yarn kamino-manager update-lending-market-owner \ > --lending-market \ > --mode multisig \ > --multisig > ``` ## Common edits ### Set or update the market name The market name is a 32-byte UTF-8 field (`name` on `LendingMarket`). ### Pause borrowing across the market Set `borrow_disabled: 1` and apply. Existing positions remain; new borrows are rejected program-side until you flip it back. For broader emergency response, see [Emergency controls](/curators/markets/emergency-controls). ### Change the referral fee `referral_fee_bps` is a u16 (basis points). It defaults to `0`. ### Set the emergency council The emergency council is a separate pubkey from the `lending_market_owner`. It has authority for `socialize_loss` and similar emergency-only handlers. Set `emergency_council` to a multisig address dedicated to incident response. ### Update minimum deposit and minimum net obligation value | Field | What it controls | | - | - | | `min_initial_deposit_amount` | The minimum amount required for a brand-new deposit to a reserve. Prevents 1-wei spam attacks. | | `min_net_value_in_obligation_sf` | The minimum USD value an obligation must hold (as a scaled fraction). Stops dust positions from existing. | > [!WARNING] > > Setting `min_net_value_in_obligation_sf` too high causes user-visible failures on partial repays. A common footgun is repaying down to a sub-threshold debt — the program rejects the operation. Document this for your users, or set the threshold low (the protocol-wide default is around `$0.000001`). ### Freeze the market permanently Set `immutable: 1` and apply. Once committed, the program rejects every owner-initiated update going forward. > [!WARNING] > > `immutable` is one-way. The program has no recovery path. ## Topic-specific settings (covered elsewhere) | Topic | Page | | - | - | | Liquidation tunables | [Liquidations](/curators/markets/liquidations) | | Auto-deleverage (margin-call grace window) | [Auto-deleverage](/curators/markets/auto-deleverage) | | Elevation groups | [Elevation groups](/curators/markets/elevation-groups) | | Withdrawal queue flags | [Withdrawal queue](/curators/markets/withdrawal-queue) | | Fixed-term rollover windows | [Fixed rate reserves](/curators/markets/fixed-rate-reserves) | | Borrow orders | [Borrow orders](/curators/markets/borrow-orders) | | Obligation orders | [Obligation orders](/curators/markets/obligation-orders) | | Per-reserve settings | [Updating reserves](/curators/markets/reserve-management), [Reserve config reference](/curators/markets/reserve-parameters) | ## Reference * [Market config reference](/curators/markets/market-config-reference) — every `LendingMarket` field * [CLI command index](/curators/markets/cli-command-index) — all market-related commands # Obligation Orders Source: https://docs.kamino.com/curators/markets/obligation-orders Price-triggered self-deleverage for borrower positions Obligation orders are user-set, price-triggered instructions that automatically deleverage a position when a condition is met. They're the on-chain equivalent of a stop-loss: a borrower creates an order saying "if my LTV crosses 75%, repay 30% of my debt by liquidating part of my collateral." Permissionless executors can then submit transactions that trigger the order when the condition becomes true. This is a tool for sophisticated borrowers (institutions, leveraged vault strategies) who want guaranteed self-deleverage rules separate from the protocol's standard liquidation flow. ## Market-level enablement | Field | What it does | | - | - | | `obligation_order_creation_enabled` | If `1`, borrowers can create new orders on their obligations | | `obligation_order_execution_enabled` | If `1`, executors can fill orders when conditions are met | | `price_triggered_liquidation_disabled` | If `1`, blocks all price-triggered liquidations market-wide (incident response) | ## Reserve-level fee | Field | What it does | | - | - | | `protocol_order_execution_fee_pct` | Percent (0–100) of order-execution proceeds routed to the protocol fee account | > [tab] SDK > > ## Enable obligation orders via SDK > > Curator-side: flip the market flags. User-side: build a price-based order via SDK helpers and submit `setObligationOrder`. > > ### Curator: enable on the market > > ```typescript theme={"theme":"css-variables"} > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { address } from '@solana/kit'; > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > > const newLendingMarket = { ...marketState }; > newLendingMarket.obligationOrderCreationEnabled = 1; > newLendingMarket.obligationOrderExecutionEnabled = 1; > newLendingMarket.priceTriggeredLiquidationDisabled = 0; > > const ixs = kaminoManager.updateLendingMarketIxs(adminSigner, marketWithAddress, newLendingMarket); > // submit each ix in order > ``` > > ### Curator: set the per-reserve execution fee > > Update `protocolOrderExecutionFeePct` in the reserve config (range 0–100): > > ```typescript theme={"theme":"css-variables"} > import { Reserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > > const reserve = await Reserve.fetch(rpc, reserveAddress); > if (!reserve) throw new Error('Reserve not found'); > > const newConfig = { ...reserve.config }; > newConfig.protocolOrderExecutionFeePct = 1; // 1% of execution proceeds > > const updateIxs = await kaminoManager.updateReserveIxs(adminSigner, marketWithAddress, reserveAddress, newConfig); > // submit each chunk in order > ``` > > ### Borrower: set a stop-loss order > > The SDK provides high-level helpers `createPriceBasedOrder` and `readPriceBasedOrder`, plus `KaminoAction.buildSetObligationOrderIxn` to wrap the on-chain instruction. > > ```typescript theme={"theme":"css-variables"} > import { > KaminoAction, > KaminoMarket, > KaminoObligation, > createPriceBasedOrder, > readPriceBasedOrder, > OrderType, > OrderActionType, > PriceBasedOrderTriggerType, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import Decimal from 'decimal.js'; > > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoMarket = await KaminoMarket.load(rpc, address(''), slotDuration); > const kaminoObligation = await KaminoObligation.load(kaminoMarket, address('')); > > const context = { > kaminoMarket, > kaminoObligation, > stablecoins: ['USDC'], > }; > > // Inspect the current stop-loss > const currentStopLoss = readPriceBasedOrder(context, OrderType.StopLoss); > console.log(currentStopLoss); > > // Set a new stop-loss: when collateral price drops below $125, repay all USDC debt > const newStopLoss = createPriceBasedOrder(context, OrderType.StopLoss, { > trigger: { > type: PriceBasedOrderTriggerType.LongStopLoss, > whenCollateralPriceBelow: new Decimal(125), > }, > action: { > type: OrderActionType.FullRepay, > }, > executionBonusBpsRange: [50, 200], // 0.5% - 2% bonus to executor > }); > > const ix = KaminoAction.buildSetObligationOrderIxn( > borrowerSigner, > kaminoMarket, > kaminoObligation, > newStopLoss, > ); > // Sign and submit > ``` > > A complete working example is at [klend-sdk/examples/klend-examples/example_obligation_order.ts](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/klend-examples/example_obligation_order.ts). > [tab] API > > > [!NOTE] > > > > **Configuring obligation orders is not available via the REST API.** The market-level flags and reserve-level fees are admin operations available through the **SDK** or **Kamino CLI**. User-facing order creation happens via SDK or app integrations. > > To configure obligation orders, use the **SDK** or **Kamino CLI** tabs. > [tab] Kamino CLI > > ## Enable obligation orders via CLI > > ```bash theme={"theme":"css-variables"} > # 1. Download > yarn kamino-manager download-lending-market-config \ > --lending-market > > # 2. Edit ./configs//market-.json — set: > # "obligation_order_creation_enabled": 1 > # "obligation_order_execution_enabled": 1 > # "price_triggered_liquidation_disabled": 0 > > # 3. Inspect & apply > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode multisig \ > --multisig > ``` > > For the per-reserve `protocol_order_execution_fee_pct`, edit the reserve config and apply via `update-reserve-config`. > > User-side order creation is not exposed through the kamino-manager CLI; borrowers create orders via the Kamino webapp or via SDK-built transactions. ## Order conditions An order specifies a `ConditionType` and a threshold: | ConditionType | When it fires | | - | - | | `Never (0)` | Never. Disabled placeholder | | `UserLtvAbove (1)` | Borrower's LTV exceeds the threshold | | `UserLtvBelow (2)` | Borrower's LTV drops below the threshold | | `DebtCollPriceRatioAbove (3)` | Debt asset's price relative to collateral exceeds the threshold | | `DebtCollPriceRatioBelow (4)` | Same ratio drops below the threshold | | `Always (5)` | Always fires (manual-trigger orders) | | `LiquidationLtvCloserThan (6)` | Borrower's LTV is closer to the liquidation threshold than the configured distance | The most useful conditions for self-deleverage are `UserLtvAbove` and `LiquidationLtvCloserThan`. The price-ratio conditions are useful for protecting against specific pair movements. ## Order opportunities (the action) | OpportunityType | What it does | | - | - | | `DeleverageSingleDebtAmount (0)` | Repay a specified amount of a single debt position by liquidating collateral | | `DeleverageAllDebt (1)` | Repay all debt on the obligation (or all debt against a specified collateral) | `DeleverageSingleDebtAmount` is the granular case — pay down a chunk of debt, leave the rest. `DeleverageAllDebt` is the full unwind. ## The execution flow The borrower calls `set-obligation-order` from their wallet, supplying a condition type, threshold, opportunity type, amount, and any reserve references the order needs. The order is stored on the obligation account and is now visible to executors. Execution is permissionless. Anyone can run a monitor that watches the program for orders whose condition is currently met; the standard pattern is an executor bot that scans active orders and submits `fill-obligation-order` against any that are fillable, referencing the obligation, the collateral reserve, the debt reserve, and the amount. When the bot's call lands, the program performs the deleverage in a single instruction: it liquidates the specified amount of collateral, repays the corresponding debt, pays the standard liquidation bonus to the executor, and routes `protocol_order_execution_fee_pct` of the proceeds to the protocol fee account. The order is cleared (or partially filled, if the action was specified as an amount and the bot only filled a portion). ## Why a curator enables this Standard liquidation only fires when a borrower's LTV crosses the per-reserve `liquidationThresholdPct`. That's the safety floor. Obligation orders let a borrower set a *softer* trigger above that floor — a stop-loss that fires before the position becomes liquidatable, on terms the borrower controls. An institutional borrower running a 10× yield loop on SOL/mSOL might set: * Order 1: `UserLtvAbove 70%` → `DeleverageSingleDebtAmount 20% of position` (gradual deleveraging as risk rises) * Order 2: `UserLtvAbove 78%` → `DeleverageAllDebt` (full exit before liquidation threshold at 80%) When SOL price drops, Order 1 fires first, paring the position back. If that's not enough and prices keep falling, Order 2 fires before the protocol's liquidation kicks in — saving the borrower the wider liquidation bonus. ## Common conditions for self-deleverage | Strategy | Condition | Threshold | Action | | - | - | - | - | | Soft stop-loss on an LST loop | `UserLtvAbove` | 5–10pp below liquidation threshold | `DeleverageSingleDebtAmount` covering \~20% | | Hard exit on rapid drop | `LiquidationLtvCloserThan` | 2pp distance | `DeleverageAllDebt` | | Pair-specific protection | `DebtCollPriceRatioAbove` | Asset-specific | `DeleverageSingleDebtAmount` | | Manual cancel-on-call | `Always` | — | `DeleverageSingleDebtAmount` (only fires on executor call) | ## Pausing during an incident The market-level kill switch is `price_triggered_liquidation_disabled`. Setting it to `1` blocks all price-triggered actions, including obligation order fills, while leaving non-price flows (manual repay, manual deposit, etc.) operational. Useful for: oracle outage, suspicious price movement, before a planned migration. Reset to `0` once the incident is resolved. ## Reference * [Market config reference](/curators/markets/market-config-reference) — `obligation_order_*_enabled`, `price_triggered_liquidation_disabled` * [Reserve config reference](/curators/markets/reserve-parameters) — `protocol_order_execution_fee_pct` * [Liquidations](/curators/markets/liquidations) — the protocol-managed equivalent * [Auto-deleverage](/curators/markets/auto-deleverage) — protocol-managed margin-call mechanism * [klend-sdk obligation order example](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/klend-examples/example_obligation_order.ts) # Permissioned Markets Source: https://docs.kamino.com/curators/markets/permissioned-markets Gate specific market actions behind a per-user, per-action allowlist enforced on-chain by the kperm program A permissioned market gates specific on-chain actions such as deposit, borrow, and liquidate behind an explicit per-user allowlist. A user without an allowlist entry (or whose entry doesn't include the action they're attempting) is rejected by the program. The curator picks which actions are gated and which users are allowed to take them; everything else stays open. The on-chain enforcement is handled by a separate program called **kperm**. ## When to use this * **KYC'd-only depositor base** — tie KYC completion to a wallet, then automate whitelisting via the API * **Accredited-investor restrictions** — same pattern, gated by attestation * **Internal market for a specific app's users** — your app's onboarding flow is the gate * **Permissioned borrowers** — counterparty agreements that lock borrow access to named entities ## How it works Permissioning is enforced by a **cosigner pattern**. Every gated action on a permissioned market requires two on-chain signatures: the user's, plus a co-signature from a kperm-controlled PDA called the **Market Permissioner**. klend will only execute the action if both are present. The mechanic has two on-chain pieces. The **market** holds two new fields. `permissioning_authority` is a pubkey that klend treats as a required co-signer on every gated action; the curator sets it to the kperm-derived **Market Permissioner PDA** (seeds: `["market", market_address]`). `permissioned_ops` is a `u64` bitfield naming which actions on this market are gated. Setting these two fields is what turns a market into a permissioned market. The **kperm program** holds the per-user allowlist. For each (market, user) pair authorized to take gated actions, kperm stores a `UserPermission` account at PDA `["permission", market, user]` recording which operations that user can take. When a user takes a gated action, their wallet does not call klend directly. It builds the klend instruction it wants to execute, then wraps it inside `kperm.permissioned_fwd_to_klend(ix_data)` and submits the wrap. kperm reads the user's `UserPermission`, confirms the requested action is in the allowlist, and CPIs into klend with its Market Permissioner PDA acting as the co-signer. klend sees the required co-signer present and executes the wrapped instruction. If the user has no `UserPermission` or the requested action is missing from the bitfield, kperm rejects and the entire transaction reverts. For non-gated actions on the same market (actions whose bit is not set in `permissioned_ops`, plus withdraw, repay, refresh, and read paths), users call klend directly. Only the gated operations require the wrap. ## The operations The kperm bitfield supports four operation slots: | Bit | Op | Notes | | - | - | - | | 0 | `DEPOSIT` | Gates depositing collateral / supplying liquidity | | 1 | `BORROW` | Gates borrowing | | 2 | `LIQUIDATE` | Gates liquidating other users' positions on this market | | 5 | `KEYRING` | External-policy bridge. Use this when a user's actions should be enforced by a separate keyring/policy program (the kperm allowlist still applies as a fallback) | A user's `UserPermission.permissioned_ops` is the bitwise OR of the bits they're allowed to act on (e.g. `DEPOSIT | BORROW` for a whitelisted depositor-borrower). **Withdraw and repay stay open.** The on-chain bitfield doesn't gate exits — once a user has been allowed to deposit or borrow, they can always close their position. Refresh and read paths are also always open. The design is to screen capital at the entry; not at the exit. ## Curator workflow **1. Decide what to permission** Pick the operations to gate. `DEPOSIT` is the most common (KYC'd depositor base). Add `BORROW` for fully gated lending venues. You can change this later. **2. Switch the market into permissioned mode** Set `permissioning_authority` to the Market Permissioner PDA and `permissioned_ops` to the chosen bitfield. From this point, klend requires the kperm cosigner for every gated action. **3. Whitelist users** Use the SDK, CLI, or REST API (see tabs below). All three issue the same `init_user_permission` (first grant) or `update_user_permission` (subsequent grants) instruction on-chain. **4. Test the rejection path** Send a deposit transaction from an un-whitelisted wallet on staging and confirm it reverts. Add that wallet to the allowlist and retry — it should succeed. > [tab] SDK > > ## Configure permissioning via SDK > > The kperm-aware methods live in `@kamino-finance/klend-sdk` alongside the standard `KaminoManager`. > > ### Curator: switch the market into permissioned mode > > ```typescript theme={"theme":"css-variables"} > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > PermissionedOp, > getMarketPermissionerPda, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { PROGRAM_ID as KPERM_PROGRAM_ID } from '@kamino-finance/klend-sdk/dist/@codegen/kperm/programId'; > import { address } from '@solana/kit'; > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketAddress = address(''); > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress = { address: marketAddress, state: marketState }; > > const marketPermissioner = await getMarketPermissionerPda(marketAddress, KPERM_PROGRAM_ID); > const permissionedOpsBitfield = PermissionedOp.fromString('DEPOSIT|BORROW'); > > const newLendingMarket = new LendingMarket({ > ...marketState, > permissioningAuthority: marketPermissioner, > permissionedOps: permissionedOpsBitfield, > }); > > const ixs = kaminoManager.updateLendingMarketIxs(adminSigner, marketWithAddress, newLendingMarket); > // submit each ix in order > ``` > > `PermissionedOp.fromString` accepts pipe-separated names: `'DEPOSIT'`, `'DEPOSIT|BORROW'`, `'DEPOSIT|BORROW|LIQUIDATE'`, etc. > > ### Whitelist a user (initial grant or update) > > ```typescript theme={"theme":"css-variables"} > import { initPermissionIx, updatePermissionIx, getPermissionPda } from '@kamino-finance/klend-sdk'; > import { UserPermission } from '@kamino-finance/klend-sdk/dist/@codegen/kperm/accounts'; > > const userAddress = address(''); > const grantedOps = PermissionedOp.fromString('DEPOSIT|BORROW'); > > const userPermissionPda = await getPermissionPda(marketAddress, userAddress, KPERM_PROGRAM_ID); > const existing = await UserPermission.fetch(rpc, userPermissionPda, KPERM_PROGRAM_ID); > > const ix = existing > ? await updatePermissionIx(globalAdminSigner, marketAddress, userAddress, grantedOps, /* overwrite */ false) > : await initPermissionIx(globalAdminSigner, marketAddress, userAddress, grantedOps); > // Sign and submit with the global admin's signer > ``` > > `updatePermissionIx` takes an `overwrite` flag: `true` replaces the user's allowed ops with `grantedOps`; `false` bitwise-ORs `grantedOps` into the existing set. > > ### Revoke a user > > ```typescript theme={"theme":"css-variables"} > import { removePermissionIx } from '@kamino-finance/klend-sdk'; > > const ix = await removePermissionIx(globalAdminSigner, marketAddress, userAddress, KPERM_PROGRAM_ID); > // Sign and submit > ``` > > The `UserPermission` account stays on-chain with `permissioned_ops = 0`. Re-granting later avoids paying rent again. > > ### User flow: take a gated action > > The standard `KaminoAction` builders detect when the target market is permissioned and automatically wrap the produced klend instructions with `permissioned_fwd_to_klend`. Builders integrating against a permissioned market continue to call `KaminoAction.buildDepositTxns(...)`, `buildBorrowTxns(...)`, etc. — the SDK handles the wrap. > > For instructions built outside of `KaminoAction`, wrap manually: > > ```typescript theme={"theme":"css-variables"} > import { permissionedFwdToKlend } from '@kamino-finance/klend-sdk/dist/@codegen/kperm/instructions'; > import { PROGRAM_ID as KLEND_PROGRAM_ID, getPermissionPda } from '@kamino-finance/klend-sdk'; > > const userPermissionPda = await getPermissionPda(marketAddress, userSigner.address, KPERM_PROGRAM_ID); > > const wrapped = permissionedFwdToKlend( > { ixData: klendIx.data }, > { > user: userSigner, > targetProgram: KLEND_PROGRAM_ID, > userPermission: userPermissionPda, > }, > /* remainingAccounts = */ [...klendIx.accounts], > KPERM_PROGRAM_ID, > ); > // Submit `wrapped` as the user's transaction > ``` > [tab] API > > ## Programmatic whitelisting via REST API > > Kamino exposes a REST API that issues the on-chain `init_user_permission`, `update_user_permission`, and `remove_user_permission` instructions on the curator's behalf. Intended use: automated onboarding — KYC provider attests → backend marks the user verified → backend calls the API → the wallet is allowed on the target market within seconds. > > The API takes the same inputs as the SDK and CLI: > > * Market address > * User wallet address > * Operations to grant (any combination of `DEPOSIT`, `BORROW`, `LIQUIDATE`, `KEYRING`) > > Signing is handled by the kperm global admin which the API operates against on your behalf for whitelisted markets. > > > [!NOTE] > > > > API base URL, authentication, and exact request schemas are not yet publicly documented. Coordinate with the Kamino team to obtain access for your market. > [tab] Kamino CLI > > ## Configure permissioning via CLI > > ### Switch the market into permissioned mode > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-lending-market-permission \ > --market \ > --operations "DEPOSIT|BORROW" \ > --mode execute > ``` > > In one call, the command sets `permissioning_authority` to the Market Permissioner PDA and sets `permissioned_ops` to the bitfield parsed from `--operations`. Operations are pipe-separated and case-insensitive: `DEPOSIT`, `BORROW`, `LIQUIDATE`, `KEYRING`. > > To reduce the gated set later, re-run with the smaller bitfield (e.g. drop `BORROW` by passing `--operations "DEPOSIT"`). > > ### Whitelist a user > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager add-permission \ > --market \ > --user \ > --operations "DEPOSIT|BORROW" \ > --mode execute > ``` > > The CLI auto-detects whether the user's `UserPermission` account already exists. If it does, the operations are merged via bitwise OR. If it doesn't, the account is created with the specified ops. > > ### Revoke a user > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager remove-permission \ > --market \ > --user \ > --operation "DEPOSIT|BORROW|LIQUIDATE" \ > --mode execute > ``` > > Sets the user's `permissioned_ops` to `0`. The user can no longer take any gated action until re-whitelisted. ## On-chain accounts | Account | Program | PDA seeds | Stores | | - | - | - | - | | `LendingMarket` | klend | (market account) | `permissioning_authority` (Market Permissioner PDA), `permissioned_ops` (u64 bitfield) | | `UserPermission` | kperm | `["permission", market, user]` | `market`, `user`, `permissioned_ops`, cached `marketPermissioner`, bumps | | Market Permissioner | kperm | `["market", market]` | Authority PDA the kperm program signs as when CPI'ing into klend (signature-only; the PDA stores no data) | | `GlobalConfig` | kperm | `["global_config"]` | `globalAdmin`, `pendingAdmin` for the kperm program | Program ID for kperm: `KPermUZsf9tu4cSd9LNcMojCbiHfdbJXv9dr3pAUzz1`. ## Operational considerations | Topic | Detail | | - | - | | Performance | Permissioned actions add one CPI hop (kperm → klend). Compute-unit cost rises modestly; users may need to bump priority fees on busy slots | | Multisig | When the curator's market owner is a multisig, `update-lending-market-permission` becomes a multisig proposal subject to the timelock, like every other market config change | | Whitelist authority | The kperm `globalAdmin` is set when the kperm program is initialized. For most curator markets, a Kamino-controlled admin holds it; the curator delegates whitelisting to the REST API. For curators that want full sovereignty, coordinate with the team to use a curator-owned admin | | Composability | Permissioning is enforced at the klend-instruction boundary. Programs that integrate with klend by composing instructions (vaults, liquidators, third-party interfaces) must use `permissioned_fwd_to_klend` to interact with a permissioned market | | Exit semantics | Withdraw and repay are always open. If you need to throttle exits, layer the [withdrawal queue](/curators/markets/withdrawal-queue) and standard reserve caps on top | ## Reference * [Market config reference](/curators/markets/market-config-reference) — `permissioning_authority` and `permissioned_ops` fields * [Market settings](/curators/markets/market-settings) — broader market-level config flow * [Updating reserves](/curators/markets/reserve-management) — reserves work the same way under a permissioned market * [`update-lending-market-permission`, `add-permission`, `remove-permission` CLI](/build/cli/market-operations) — full flag detail # Plan Your Market Source: https://docs.kamino.com/curators/markets/plan-your-market Understand the decisions a curator makes when designing and operating a Kamino lending market A Kamino lending market brings together a curated set of assets that users can supply and borrow. The curator chooses those assets and sets the parameters that govern how the market operates. Each market is isolated, so its exposure remains separate from other Kamino lending markets. ![Kamino curators markets list](https://mintcdn.com/kamino-3d73a151/Kr04J8Tty1aPhdQ2/images/curators/markets/markets-list.webp?fit=max\&auto=format\&n=Kr04J8Tty1aPhdQ2\&q=85\&s=3a827f2f1e7031eacd8de6cbb1a0c1a5) By the end of this guide Curators should understand: * What a Kamino lending market does * What to consider when choosing assets for a market * The relationship between risk settings and evolving market conditions * The ownership and emergency roles within a market * When to expand market liquidity as lending and borrowing activity grows *** ## A Market in One Example Planning a market starts with understanding how all its core components work together. Consider a market with SOL and USDC reserves, which will be used throughout this guide. Each reserve has its own configuration that determines whether users can supply or borrow the asset and whether it can be used as collateral. ![Lending market flow: supply, borrow, price fall, liquidation](https://mintcdn.com/kamino-3d73a151/08Y-TFxV_VC5bdgE/images/curators/markets/market-lending-flow.webp?fit=max\&auto=format\&n=08Y-TFxV_VC5bdgE\&q=85\&s=6930595d8d514a35fa8d6a1748021995) Lenders supply USDC to the market and earn interest when that USDC is borrowed. A borrower can access that liquidity by depositing SOL as **collateral** and borrowing USDC against it. Suppose a borrower deposits 100 SOL worth \$20,000 and borrows \$12,000 USDC. The position has an **LTV of 60%**: \$12,000 of debt against \$20,000 of collateral. If the SOL reserve has a maximum LTV of 70%, the borrower could borrow up to \$14,000. ![100 SOL collateral, \$12,000 USDC borrowed, 60% LTV with remaining capacity](https://mintcdn.com/kamino-3d73a151/08Y-TFxV_VC5bdgE/images/curators/markets/market-ltv-breakdown.webp?fit=max\&auto=format\&n=08Y-TFxV_VC5bdgE\&q=85\&s=0c0c0b9338b55fa1867179b233f1d694) The position remains healthy until it reaches the **liquidation threshold**. At a threshold of 75%, the \$12,000 debt becomes eligible for liquidation when the value of the SOL collateral falls to \$16,000, or \$160 per SOL. A **liquidator** can then repay part of the borrower's debt in exchange for some of their SOL collateral. To make liquidation worthwhile, the liquidator receives slightly more collateral than the value of the debt they repay. This difference is the **liquidation bonus**. With an 8% liquidation bonus, a liquidator who repays \$1,000 of USDC debt receives \$1,080 worth of SOL. The **close factor** determines how much of the borrower's debt can be repaid in a single liquidation. With a 20% close factor, a position with \$12,000 of outstanding debt can have up to **\$2,400 repaid in one liquidation**. The **oracle** provides the prices used to value the borrower's SOL collateral and USDC debt. As those prices change, the position's LTV changes with them, which determines when the position reaches the liquidation threshold. **Caps** limit how large the market can grow. A deposit cap limits how much SOL can be supplied to the reserve, while a borrow cap limits how much USDC can be borrowed from it. If the value of SOL falls too quickly for the position to be liquidated in time, the collateral may no longer be worth enough to repay the debt. The remaining shortfall becomes **bad debt**, reducing the amount USDC lenders can withdraw from the reserve. Knowledge Check A curator should be able to: * Understand how collateral price movements influence borrowing capacity. * Understand how curator settings determine when a position becomes eligible for liquidation. *** ## Who Participates in a Lending Market A market can support three main types of users: lenders, borrowers, and loopers. Each interacts with the market differently and introduces a different kind of demand and risk. **Lending.** Lenders supply assets such as USDC to earn interest. They provide the liquidity borrowers use, and their main risk is that losses in the reserve can reduce the amount they are able to withdraw. **Borrowing.** Borrowers deposit collateral and borrow another asset against it. They create demand for the liquidity supplied by lenders, and they take on liquidation risk if the value of their collateral falls too far. **Looping.** Loopers deposit SOL, borrow USDC against it, use that USDC to buy more SOL, and repeat. This lets them increase their exposure beyond what their starting capital would normally allow. Because each loop involves buying more SOL, sufficient market liquidity is needed for positions to open efficiently. If the collateral also earns staking yield, that yield applies to the larger position as well. Kamino Multiply automates the repeated borrow-and-buy loop in a single transaction. In a SOL/USDC market dominated by loopers, many users may be borrowing USDC to buy more SOL. As more of the supplied USDC is borrowed, utilisation rises, meaning a larger share of the USDC in the reserve is already in use and less remains available. Kamino's risk controls are designed to keep this exposure within manageable bounds. If SOL falls sharply, many looped positions may need to unwind around the same time. Loopers may sell SOL to repay USDC, while liquidators may also sell SOL received from unhealthy positions. This concentrates activity around the same assets and is one reason curators need to consider available liquidity when configuring a looping-heavy market. Knowledge Check A curator should be able to: * Identify what lenders, borrowers, and loopers do. * Understand how each participant affects the market. *** ## What Curators Should Consider Before Launch Before launch, a curator needs to understand how much risk the market can safely support and configure it around those limits. ### Risk Lenders and borrowers take on different risks. In the SOL/USDC example, lenders supply USDC to earn interest and do not depend on SOL increasing in value. The borrower deposits SOL as collateral instead of selling it, so they continue to benefit if SOL rises but also bear the loss if SOL falls. If the collateral loses value, the position moves closer to its health limit, the point where its collateral is no longer sufficient relative to its debt. That does not mean USDC lenders are completely insulated from the risk of SOL's price falling. Their protection depends on the borrower's collateral remaining sufficient to cover the outstanding debt. Kamino uses a buffer between the maximum LTV and the health limit so positions have room to absorb price movement before liquidation is required. If the position reaches that limit, liquidation is designed to reduce the debt while the collateral can still cover it. If a shortfall still remains, it becomes bad debt in the USDC reserve and can reduce the amount lenders are able to withdraw. Worth checking * Who is lending and who is borrowing. * What borrowers are using the borrowed asset for. * Whether many borrowers are exposed to the same underlying trade. * Who would ultimately absorb a loss if collateral no longer covers the debt. > [card] [Risk parameters](/curators/markets/risk-parameters) > > LTV, thresholds, IR curves, and caps for each reserve. > [card] [Market risk](/risk/market-risk) > > Measured risk data across Kamino markets. ### Liquidity and Volatility A position can only be closed safely if there is enough market liquidity to sell the collateral without moving its price too far. **Liquidity** measures how much the price changes when collateral is sold, and curators need to look at that price impact at the sizes a liquidation may actually need to execute. Available liquidity helps determine how large positions the market can safely support. Reserve caps and liquidation parameters should be set so collateral can be sold at expected liquidation sizes without price impact overwhelming the liquidation bonus. **Volatility** measures how quickly the collateral price can move. More volatile assets need more room between the maximum LTV and the health limit so a position has time to be liquidated before the collateral value falls too far. Worth checking * Whether the collateral asset has enough market liquidity to be sold without significant price impact. * How sharply the collateral asset has moved during previous periods of volatility. * Whether that liquidity depends on incentives, and how much would remain if those incentives ended. * Whether the proposed reserve caps are appropriate for the collateral asset's available market liquidity. > [!TIP] > > Use the [KRAF risk dashboard ↗](https://risk.kamino.finance/) to review liquidity and volatility data for the collateral asset when setting reserve parameters. > [card] [Volatility](/risk/market-risk/volatility) > > Measured volatility data. > [card] [Liquidity](/risk/market-risk/liquidity) > > On-chain liquidity analysis. > [card] [KRAF dashboard](https://risk.kamino.finance/) > > Live risk dashboard. ### Token and Oracle Risk Before adding an asset to a market, a curator needs to understand both **the risks of the token itself** and **how its value will be determined onchain**. A token can introduce risks through its minting, transfer, or administrative controls, while the oracle determines the price Kamino uses to value collateral and debt. **The token.** If new tokens can still be created, the curator needs to understand who controls that authority and how securely it is managed. If minting were abused, someone could create a large amount of the token, deposit it as collateral, and borrow another asset against it. The debt asset's borrow cap also limits how much value can be borrowed from the market. Even if the collateral supply increases significantly, borrowing cannot exceed the cap set on the debt reserve. Curators should also review any **freeze, upgrade, or transfer controls** that could affect how the token behaves after the market is live. **The oracle.** The oracle determines the value Kamino uses for collateral and debt, so choosing the right price source is part of the market's risk design. For a liquid asset such as SOL, a market price may be appropriate. An RWA may instead rely on **Net Asset Value (NAV)**, while a **Liquid Staking Token (LST)**, which represents a staked asset plus the rewards it accrues, may use its staking exchange rate. Whichever source is used, the price needs to stay current. If an oracle updates too slowly, Kamino may be working from a value that no longer reflects the market during a fast price move. The market should also have a way to handle a price feed becoming unavailable or reporting an unexpected value. Using more than one independent price source, together with rules for stale or conflicting prices, can make the oracle setup more resilient. Worth checking * Whether the token has a **mint authority** or **freeze authority**, and who controls them. * If new tokens can still be issued, how securely the minting process is managed. * Which **price feeds** are configured for the asset, and what happens if one becomes stale or unavailable. * Whether the chosen oracle setup matches how the asset is actually valued, such as market price, NAV, or a staking exchange rate. > [card] [Asset risk](/risk/asset-risk) > > Token risk, oracle pricing, depeg analysis. > [card] [Configuring oracles](/curators/markets/configuring-oracles) > > Wire each reserve to a Scope price feed. ### Market Authority and Controls Curators should choose who holds the market owner and emergency council roles, and understand how quickly each role can make changes to the market. Changes to market and reserve settings made by the market owner are delayed by a timelock, giving signers time to review them and respond if a key or device has been compromised. The emergency council can act immediately, but only through a limited set of protective controls, so it can contain an incident without having full authority over the market. | Role | What it can do | How quickly it can act | | - | - | - | | **Market owner** | Can change market and reserve settings | Changes go through the owner multisig and timelock | | **Emergency council** | Can make a limited set of protective changes that restrict market activity | Can act immediately without the owner timelock | | **Proposer authority** | Can configure a reserve before its first deposit | Only applies during initial reserve setup | The emergency council cannot restore normal operation after using these controls. Reversing those protective changes requires the market owner and is subject to the owner timelock. Market changes should be protected by strong signing and approval controls. Curators should design the signing process so that no single compromised signer or device can change the market on its own. Sensitive changes can sit behind a multisig and timelock, while independent verification and external alerts help catch anything unexpected. A timelock slows down parameter changes, so reserve caps should be set conservatively to keep the market safe during that delay. If a change is needed, the curator may have to wait for the timelock to expire before new parameters take effect, while the emergency council can only take protective actions such as disabling parts of the market. Worth checking * Whether the multisig has enough independent signers and an appropriate approval threshold. * Whether signers use dedicated devices for approving market changes. * How long the owner multisig timelock is, since that delay affects how conservatively reserve caps should be set. * Whether the emergency council is configured and ready to act if needed. * Whether external alerts are in place and someone is responsible for monitoring them outside normal hours. > [card] [Transfer to multisig](/curators/markets/transfer-to-multisig) > > Move ownership from a hot wallet to Squads. > [card] [Emergency council](/curators/markets/emergency-council) > > Set up the emergency authority. > [card] [Emergency controls](/curators/markets/emergency-controls) > > Pause, freeze, and socialize loss. *** ## Assessing Market Configuration Curators should align the market's configuration with its expected risk and operating conditions. ### Setting Risk Parameters Each reserve in a market has its own configuration, and each parameter governs a different part of how that reserve behaves. | Parameter | Depends on | Sets | | - | - | - | | LTV ratio and liquidation threshold | Collateral volatility and liquidity | How much can be borrowed against the collateral and when a position becomes eligible for liquidation | | Interest rate curve | Target utilisation | The cost of borrowing as reserve utilisation changes | | Deposit and borrow caps | Available collateral liquidity and timelock constraints | How much exposure the reserve can support | | Withdrawal caps | Expected withdrawal activity | How quickly funds can leave the reserve | | Liquidation bonus | Price impact at expected liquidation sizes | The incentive available to liquidators | Reserve caps should be checked against the amount of collateral that may need to be liquidated. The collateral asset should have enough available liquidity for those liquidations to execute without price impact overwhelming the liquidation bonus. Worth checking * Whether the **LTV and liquidation threshold** leave enough room for the collateral asset's observed volatility. Use the proposed reserve parameters together with KRAF volatility data. * Whether the **expected liquidation size** can be sold without excessive price impact. Use KRAF liquidity data for the collateral asset. * Whether the **reserve caps** remain conservative enough during the owner multisig timelock. * Whether the **liquidation bonus** is sufficient relative to the expected price impact at that liquidation size. > [card] [Risk parameters](/curators/markets/risk-parameters) > > Full parameter reference and recommended values. > [card] [Withdrawal caps](/curators/markets/withdrawal-caps) > > Throttle deposits, withdrawals, and debt activity. > [card] [Liquidations](/curators/markets/liquidations) > > Close factor, bonuses, and bad-debt handling. ### Oracle Configuration Each reserve needs an oracle configuration that reflects how its asset should be valued. Kamino Lend uses Scope, Kamino's oracle aggregator, to price reserve assets. Curators choose the Scope price feed that best reflects how each asset should be valued. Curators can also configure safeguards that determine when a reserve should stop accepting an oracle price. These safeguards are disabled by default and need to be configured explicitly. | Setting | What it does | | - | - | | **Heuristic bounds** | Sets a minimum and maximum accepted price | | **TWAP divergence** | Limits how far the current price can deviate from the time-weighted average price | | **Price age** | Sets how long a price can go without updating before it is rejected | | **Block price usage** | Prevents the reserve from using its oracle price until the setting is changed | > Heuristic bounds are manually configured minimum and maximum prices that an oracle price is allowed to fall within. They do not protect against unlimited minting because an increase in token supply may not change the reported oracle price. Reserve caps provide a separate limit on how much exposure the market can take on. Worth checking * Whether a suitable **Scope price feed** exists for the reserve asset. * Whether the **heuristic bounds** allow plausible price movement while still rejecting clearly erroneous values. * Whether the **TWAP divergence limit** can catch an unusual gap between the current price and its recent average, and whether the **price age limit** rejects a feed that has stopped updating. * Whether `block_price_usage` has been tested before launch by the authority responsible for using it. > [card] [Configuring oracles](/curators/markets/configuring-oracles) > > Wire each reserve to a Scope price feed with TWAP guards. > [card] [Scope oracle types](/curators/markets/scope-oracle-types) > > Composition types for fixed-income, multi-source, and LST assets. *** ## Steps to Taking the Market Live Curators bring a market live through a defined sequence of setup steps. **1. Create the market** Create the lending market. This initializes the `LendingMarket` account that will contain the market's reserves and configuration. See [Creating a market](/curators/markets/creating-a-market). ![Create Market modal](https://mintcdn.com/kamino-3d73a151/_kBsgfUkJCUTJS4M/images/curators/markets/create-market-modal.webp?fit=max\&auto=format\&n=_kBsgfUkJCUTJS4M\&q=85\&s=cf7d7a7c69c53911be939cc5c239edaf) **2. Add reserves** Add the reserves the market will support. One reserve per token mint per market. Typically, one reserve is added for the collateral asset and another for the asset users borrow. See [Adding reserves](/curators/markets/adding-reserves). **3. Make the seed deposit** Make the initial deposit into each reserve. A reserve must receive its first deposit before its configuration can be updated. **4. Set risk parameters** Set the reserve risk parameters for each reserve. See [Risk parameters](/curators/markets/risk-parameters). **5. Configure the oracle** Connect each reserve to its Scope price feed. See [Configuring oracles](/curators/markets/configuring-oracles). **6. Transfer ownership to the multisig** Transfer market ownership from the setup wallet to the owner multisig. See [Transfer to multisig](/curators/markets/transfer-to-multisig). **7. Set the emergency council** Assign the emergency council for the market. See [Emergency council](/curators/markets/emergency-council). **8. Turn on alerting** Turn on external alerting for the market. Host it separately from the curator's own systems so a compromise cannot disable the alerts. **9. Open with initial reserve caps** Open the market with lower initial reserve caps. These limits control how much can be deposited into and borrowed from each reserve, and can be raised gradually as the market begins operating. **Liquidator coverage.** Liquidations are permissionless, so a new market is not guaranteed active liquidator coverage. Curators should confirm coverage before the market goes live. Liquidator tooling is open source, so curators can run their own if needed. **Collateral liquidity.** If the market is intended to support looping, there needs to be enough liquidity to buy the collateral asset. Liquidations also require enough liquidity to sell it. Curators should confirm that liquidity is available before the market goes live and again before raising reserve caps. Curators should increase reserve caps gradually after the market goes live. Each increase should follow a waiting period and be based on how the reserves are performing. > [card] [Lifecycle](/curators/markets/lifecycle) > > The full path from create to operate. > [card] [Quickstart](/curators/markets/quickstart) > > Stand up a working market on staging in \~10 minutes. > [card] [Market settings](/curators/markets/market-settings) > > Market-level parameters and flags. *** ## Managing the Live Market Once the market is live, curators can evaluate how each reserve is performing and decide when its configuration needs to change. ### Monitor and Adjust Curators should monitor live reserve conditions to see whether the assumptions behind the configuration still hold. What to watch * **Utilisation.** Watch whether reserve utilisation is approaching the point on the interest rate curve where borrowing rates begin rising sharply. If utilisation stays too high, most of the reserve liquidity is already borrowed, leaving less available for withdrawals. * **Concentration.** Watch how much of the reserve's borrowing is concentrated in its largest positions. If one position represents a large share of the borrow cap, a single liquidation could be much larger than expected and place more pressure on available collateral liquidity. * **Oracle health.** Watch for stale price updates or unusual differences between the current oracle price and its **time-weighted average price (TWAP)**. If borrowing stops unexpectedly, check whether an oracle safeguard has been triggered. * **Liquidity.** Recheck how much of the collateral asset can be bought or sold without significant price impact. If that liquidity is incentive-driven, watch for changes as incentives decline or end. Curators should define when each monitored condition requires action, so changes in reserve performance have a clear response. Reserve cap increases are configuration changes, so they must be approved through the same authority and timelock used for other reserve updates. > [card] [Market data](/curators/markets/market-data) > > Query reserve and market state. > [card] [Reserve management](/curators/markets/reserve-management) > > Edit reserve configurations after launch. ### Incident Response In each case the first move stops the exposure growing. The cause gets dealt with after. **Price feed wrong or stale** \ **Signal:** divergence alert, staleness alert, or a price that does not match other venues. \ **First move:** `block_price_usage` on the affected reserve. Emergency council, no timelock. **Collateral token compromised** \ **Signal:** unexpected change in supply, public disclosure, or a mint from an authority believed revoked. \ **First move:** borrow cap to 0 and LTV to 0. Emergency council. **Position underwater, nobody liquidating** \ **Signal:** a position above its liquidation threshold that just sits there. \ **First move:** measure the gap at real fill prices. If the bonus no longer covers impact, raise it (owner action, waits on timelock). `socialize_loss` comes last. **Signer compromised** \ **Signal:** a proposal nobody created, or an approval from an unexpected signer. \ **First move:** market emergency mode or borrowing disabled. Emergency council. Then rotate the multisig. > [!WARNING] > > Alerting should run outside the curator's own hosting. A compromise that reaches the curator's systems would otherwise switch off the alerts reporting it. The incident contact at Kamino should be agreed before launch. > [card] [Emergency controls](/curators/markets/emergency-controls) > > Full reference for pause, freeze, and loss socialization. > [card] [Emergency council](/curators/markets/emergency-council) > > What the council can and cannot do. *** ## Worked Example This worked example shows how a curator can turn market observations into a market configuration. Using the SOL/USDC market, it shows how those conditions shape reserve settings and how the resulting configuration can be tested before exposure is increased. The figures are illustrative and are not Kamino recommendations. ### Measured Inputs The curator starts with existing information about the market before choosing any reserve parameters. For SOL, the most important starting point is its liquidity and volatility under real trading conditions. | Input | Example | | - | -: | | SOL price | \$200 | | Price impact on a \$2m sale | 0.4% | | Price impact on a \$10m sale | 1.6% | | Price impact on a \$25m sale | 4.5% | | 30-day annualised volatility | 60% | | Largest single-day fall over 12 months | 18% | ### Market Setup Inputs The worked example also assumes the reserve already has a suitable Scope price feed and that the market's authority roles have been configured. | Input | Example | | - | - | | Oracle | Scope SOL/USD entry with TWAP available | | Market owner | 3-of-5 multisig with a 12-hour timelock | | Emergency council | 2-of-4, no timelock | | Mint authority | None; SOL is the native asset | ### Initial Configuration The first question is how much room to leave between borrowing and liquidation. With SOL moving about 3.2% on an average day in this example, a 70% LTV and 77% liquidation threshold leave a seven-point buffer before a position becomes liquidatable. Next, the curator can focus on how borrowing costs should change as the USDC reserve fills. The borrow-rate curve keeps rates relatively low through 80% utilisation, then increases them more aggressively as available liquidity becomes tighter. | Utilisation | Borrow rate | | - | -: | | 0% | 0.5% | | 80% | 6% | | 95% | 25% | | 100% | 150% | New borrowing is blocked at 90% utilisation, after the borrow rate has already begun rising more sharply. This gives the interest-rate curve a chance to slow borrowing before the reserve reaches its hard limit. ### Exposure Limits The curator can then decide how much SOL exposure the reserve should allow. SOL is used only as collateral, so its borrow limit is set to 0. The deposit limit is set to 10,000 SOL, which caps how much SOL can enter the reserve. For the USDC reserve, the curator can set how much USDC can be borrowed across the market. In this example, the borrow limit is set to \$5 million. Because that limit is shared by all borrowers, it does not cap the size of an individual position. The curator therefore needs to test what happens if a large share of that debt becomes concentrated in one position. ### Liquidation Capacity Before choosing the liquidation bonus, it helps to revisit what happens during a liquidation. A liquidator repays part of the borrower's USDC debt and receives SOL collateral in return. The liquidation bonus means the liquidator receives slightly more SOL than the value of the USDC they repaid. If a borrower held \$5 million of USDC debt, a 20% close factor would allow up to \$1 million of that debt to be repaid in one liquidation. With a 5% bonus, the liquidator would receive about \$1.05 million worth of SOL. The liquidator may sell that SOL on an external market to recover the USDC used to repay the debt. Selling a large amount of SOL can move its market price, which is why the curator needs to compare the expected liquidation size with SOL's available trading liquidity. ### Withdrawal Limits Withdrawal caps control how quickly users can remove liquidity from a reserve. They do not limit how much collateral a liquidator can receive or sell during a liquidation. In this example, the SOL withdrawal cap is set to 5,000 SOL over 24 hours, while the USDC withdrawal cap is set to \$2 million over the same period. The USDC debt withdrawal cap controls how quickly new borrowing can increase. In this example, it is set to \$1 million over 24 hours, so even if the reserve is still below its overall \$5 million borrow limit, debt cannot grow faster than that rate. ### Liquidation Bonus The liquidation bonus compensates the liquidator for the cost and risk of closing the position. If a liquidator repays \$1 million of USDC debt with a 5% bonus, they receive about \$1.05 million worth of SOL. If selling that SOL causes less than 0.4% price impact, only a small part of the 5% bonus is lost during the sale. The remaining value helps cover transaction costs and provides the liquidator's incentive to execute the liquidation. The minimum bonus is set to 2%, so a liquidator is still rewarded when a position has only just crossed the liquidation threshold. As the position becomes less healthy, the bonus can increase toward the 5% maximum. ![Dynamic liquidation bonus as LTV increases](https://mintcdn.com/kamino-3d73a151/08Y-TFxV_VC5bdgE/images/curators/markets/liquidation-bonus-curve.webp?fit=max\&auto=format\&n=08Y-TFxV_VC5bdgE\&q=85\&s=f983da6e3fd936dacc6be0b12a01b3f9) ### Stress Check and Revision The curator should then test how the position holds up during a sharp fall in SOL. In the measured period, SOL fell as much as 18% in a single day, so the example uses that move as a stress case. Assume a position has \$100 of SOL collateral and \$77 of USDC debt at the liquidation threshold. If the full \$77 of debt had to be repaid through liquidation, a 5% bonus would require liquidators to receive \$80.85 worth of SOL collateral. That leaves \$19.15 of the original \$100 collateral value. An 18% fall in SOL would almost wipe out that remaining cushion, leaving only about \$1.15 of value before the position no longer has enough collateral to comfortably cover the debt and liquidation bonus. To create more room, the example lowers the liquidation threshold from 77% to 75%. With \$100 of collateral, that means liquidation begins at \$75 of debt instead of \$77, so the position is acted on earlier and more collateral value remains available to absorb further price movement. The LTV is then reduced to 68% to preserve the same seven-point gap between borrowing and liquidation. ### Oracle Configuration Next, the curator can configure how the SOL reserve is priced. The reserve uses a Scope SOL/USD feed, with safeguards that determine when that price should no longer be trusted. | Setting | Example | | - | - | | Price feed | Scope SOL/USD | | `max_age_price_seconds` | 60 | | `max_age_twap_seconds` | 240 | | `max_twap_divergence_bps` | 500 | | Heuristic lower bound | \$5 | | Heuristic upper bound | \$2,000 | The price age limits reject updates that have become stale, while the TWAP divergence limit rejects a current price that has moved too far from its recent average. The heuristic bounds provide an additional check against clearly invalid SOL prices. ### First Cap Increase After the market has operated without incident and SOL liquidity has been remeasured, the curator increases the USDC borrow limit from \$5 million to \$10 million. *** ## Pre-launch Checklist Before opening the market, confirm that the setup is complete and each configuration choice has been verified. ### Market Readiness * [ ] The intended lending and borrowing activity is clear. * [ ] Price impact has been measured at the expected liquidation size. * [ ] The collateral asset's largest recent price moves have been reviewed. * [ ] Token authorities have been checked, including mint and freeze authority where applicable. * [ ] The debt reserve's borrow cap limits the market's exposure if collateral supply increases unexpectedly. * [ ] Liquidator coverage has been confirmed before launch. * [ ] If market liquidity depends on an issuer, the expected liquidity commitment has been confirmed. ### Authority and Controls * [ ] The owner multisig is configured with the intended signer threshold. * [ ] The owner timelock is set to the intended duration. * [ ] The emergency council is configured and able to act without the owner timelock. * [ ] External alerting is active. * [ ] An incident contact at Kamino has been agreed. * [ ] The signing process has been tested before launch. ### Reserve Configuration * [ ] The gap between LTV and the liquidation threshold covers the collateral asset's observed volatility. * [ ] The utilisation block sits above the interest-rate curve kink. * [ ] Deposit and borrow caps are set to the intended launch size. * [ ] The expected liquidation size can be sold without excessive price impact. * [ ] Withdrawal caps are set on both reserves. * [ ] The maximum liquidation bonus is above the expected price impact at the liquidation size. * [ ] The minimum liquidation bonus is below the maximum. * [ ] The liquidation threshold still leaves enough collateral value after the maximum bonus is applied. ### Oracle Configuration * [ ] A suitable Scope price feed exists for each reserve asset. * [ ] Price age limits are configured. * [ ] TWAP divergence limits are configured. * [ ] Heuristic price bounds are configured. * [ ] The oracle setup has been tested before launch. * [ ] `block_price_usage` has been tested by the authority that would use it during an incident. ### Launch Checklist * [ ] The full market setup sequence has been rehearsed on staging. * [ ] The seed deposit has been made before any reserve configuration write. * [ ] Market ownership has been transferred to the multisig. * [ ] Growth criteria have been written down before opening the market. * [ ] Every signer has reviewed the incident response process. # Programmatic Integration Source: https://docs.kamino.com/curators/markets/programmatic-integration Where to go for SDK, API, and direct RPC integration with a Kamino market Curator markets expose the same on-chain primitives as every other Kamino market. Anything you can do with the public Kamino API or SDK against the main markets, you can do against your curator market by passing your market address. This page is a routing index: it points to the existing developer documentation that covers each integration surface in depth. ## Building deposit / borrow / repay / withdraw transactions For an app that lets users deposit, borrow, repay, or withdraw on your market: > [card] [Borrow developer docs](/build/developers/borrow/index) > > Overview of operations, data, rewards, position management > [card] [Borrow tutorials](/build/tutorials/borrow/deposit-and-borrow) > > Step-by-step walkthroughs of common operations > [card] [Borrow API recipes](/build/recipes/borrow/deposit-via-api) > > REST-API-only patterns, no SDK > [card] [Borrow API reference](/build/api-reference/borrow/market-data/markets-list) > > OpenAPI reference for every Borrow endpoint Each of these works against any klend market — pass your market address as the `--market` parameter (CLI), the `marketPubkey` argument (SDK), or the `market` URL parameter (API). ## Reading market and reserve data For dashboards, alerts, and read-only integrations: > [card] [Read market data](/curators/markets/market-data) > > The curator's view: API + SDK + RPC examples for market state > [card] [API reference (market data endpoints)](/build/api-reference/borrow/market-data/markets-list) > > Full OpenAPI reference ## Earn / vault integration on top of your market If a vault sits on top of your market and you want to integrate the vault layer: > [card] [Earn developer docs](/build/developers/earn/index) > > Vault data and operations > [card] [Earn tutorials](/build/tutorials/earn/earn-and-withdraw) > > Vault deposit / withdraw walkthroughs ## Rewards and farms For computing APYs, claiming rewards, building reward dashboards: > [card] [Rewards tutorials](/build/tutorials/borrow/calculate-reserve-reward-apy) > > Calculate reserve reward APY, claim rewards > [card] [Rewards API reference](/build/api-reference/borrow/rewards/rewards-list) > > REST endpoints for active rewards and user claimables > [card] [Farms & rewards (curator side)](/curators/markets/farms-and-rewards) > > How a curator initializes and operates farms ## Curator-specific tooling These surfaces are specific to curator workflows (separate from end-user app integrations): > [card] [kamino-manager CLI](/build/cli/index) > > All curator operations: create market, add reserves, update configs, propose multisig transactions > [card] [CLI command index](/curators/markets/cli-command-index) > > Quick lookup of every market-related command ## Program-level integration For a custom program (Anchor / native) that interacts with your market on-chain: | Resource | Use for | | - | - | | [klend repository](https://github.com/Kamino-Finance/klend) | Program source, IDL, Rust types, error definitions | | [klend-sdk repository](https://github.com/Kamino-Finance/klend-sdk) | TypeScript bindings + helper utilities + the kamino-manager CLI | | [KFarms repository](https://github.com/Kamino-Finance/kfarms) | Farms program source | | [farms-sdk repository](https://github.com/Kamino-Finance/farms-sdk) | TypeScript bindings for farms | | [Program addresses](/build/resources/program-addresses) | All Kamino program IDs (mainnet + staging + devnet) | ## Reference * [Read market data](/curators/markets/market-data) — read examples * [CLI command index](/curators/markets/cli-command-index) — every market-related CLI command * [Reserve config reference](/curators/markets/reserve-parameters) — every editable reserve field * [Market config reference](/curators/markets/market-config-reference) — every editable market field # Quickstart Source: https://docs.kamino.com/curators/markets/quickstart Stand up a working market on staging in ~10 minutes This walkthrough takes you from zero to a working market with one reserve on Kamino's staging environment. Staging runs the klend program on Solana mainnet under a separate program ID, so prices, oracles, and conditions match production while the market itself stays isolated from prod. > [!NOTE] > > **Want a fully isolated sandbox instead?** Replace every `--staging` flag below with `--devnet` to run against Solana devnet. Devnet is good for learning the CLI without any mainnet exposure; staging is the right target if you intend to graduate the same configuration to mainnet. ## Prerequisites | Requirement | Why | | - | - | | Node.js + Yarn | The CLI is a TypeScript app shipped with `klend-sdk` | | Solana CLI (`solana-keygen`) | To create and inspect the admin keypair | | A funded Solana wallet | To pay transaction fees and seed the first deposit | | A Solana RPC endpoint | Public RPC works for staging; private RPC strongly recommended | If you're missing any of these, follow the [CLI installation & setup](/build/cli/installation-setup) page first. ## 1. Clone and configure ```bash theme={"theme":"css-variables"} git clone git@github.com:Kamino-Finance/klend-sdk.git cd klend-sdk yarn ``` Create a `.env` file in the project root: ```bash theme={"theme":"css-variables"} ADMIN=./admin.json RPC=https://api.mainnet-beta.solana.com KLEND_PROGRAM_ID_MAINNET="KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD" KLEND_PROGRAM_ID_STAGING="SLendK7ySfcEzyaFqy93gDnD3RtrpXJcnRwb6zFHJSh" KVAULT_PROGRAM_ID_MAINNET="KvauGMspG5k6rtzrqqn7WNn3oZdyKqLKwK2XWQ8FLjd" KVAULT_PROGRAM_ID_STAGING="stKvQfwRsQiKnLtMNVLHKS3exFJmZFsgfzBPWHECUYK" KVAULT_PROGRAM_ID_DEVNET="devkRngFnfp4gBc5a3LsadgbQKdPo8MSZ4prFiNSVmY" ``` Generate or point to an admin keypair: ```bash theme={"theme":"css-variables"} solana-keygen new -o admin.json solana-keygen pubkey admin.json # send a small amount of SOL to this address ``` ## 2. Create the market ```bash theme={"theme":"css-variables"} yarn kamino-manager create-market --staging --mode execute ``` The CLI returns a market address in its output. Save it; every subsequent command takes it as `--lending-market` or `--market`. ```bash theme={"theme":"css-variables"} export MARKET= ``` > [!TIP] > > Always start a new operation with `--mode inspect` (prints a simulator URL) or `--mode simulate` (runs the simulation and prints the result). Switch to `--mode execute` once the dry run looks correct. ## 3. Add a reserve The repo includes `configs/reserve_config_example.json` as a starting point. For staging, USDC is a sensible first reserve. ```bash theme={"theme":"css-variables"} yarn kamino-manager add-asset-to-market \ --market $MARKET \ --mint EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v \ --mint-program-id TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA \ --reserve-config-path ./configs/reserve_config_example.json \ --staging \ --mode execute ``` > [!WARNING] > > The example reserve config is a starting template. Before mainnet, replace it with a config tuned for the asset, oracle, and risk profile you actually want. See [Risk parameters](/curators/markets/risk-parameters) and [Reserve config reference](/curators/markets/reserve-parameters). Repeat the command with a different `--mint` for each additional reserve. ## 4. Verify the market state Download the full market and reserve config to confirm everything is wired up: ```bash theme={"theme":"css-variables"} yarn kamino-manager download-lending-market-config-and-all-reserves-configs \ --lending-market $MARKET \ --staging ``` The CLI writes the configs to `./configs/{MARKET_ADDRESS}/`. Open them and check: * Market `lending_market_owner` is your admin pubkey * Each reserve has `status: 0` (Active) * Each reserve has a populated `tokenInfo.scopeConfiguration.priceFeed` * `depositLimit` and `borrowLimit` are non-zero where you want activity ## 5. Test a deposit Open the staging webapp scoped to your market: ``` https://app.kamino.finance/?STAGING_PROGRAM&market= ``` Connect a wallet that holds the asset, deposit, and confirm the position appears. If you don't see the market, double-check the staging program flag and that the reserve `status` is `0`. ## What you have now A working market with one reserve, owned by your hot wallet, running against staging. The on-chain accounts are real; the program is real; the oracles are real. The only thing missing for production is multisig ownership. ## Next steps for going to production **1. Tune risk parameters** Replace the example config with values appropriate for the asset and your risk thesis. → [Risk parameters](/curators/markets/risk-parameters) **2. Configure oracles** Pick the right oracle source, set TWAP guards, configure staleness. → [Configure oracles](/curators/markets/configuring-oracles) **3. Enable any optional features** Withdrawal queue, fixed rate reserves, borrow orders, eMode, permissioning — opt in per feature. → [Withdrawal queue](/curators/markets/withdrawal-queue) **4. Set up a Squads multisig** Production markets must be owned by a multisig. → [Transfer to multisig](/curators/markets/transfer-to-multisig) **5. Re-run on mainnet** Drop the `--staging` flag and re-run the create + add-reserve flow. The mainnet program ID `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD` is the default. ## Common errors at this stage | Error | Cause | | - | - | | `RPC rate limit / transaction failed` | Use a private RPC (Helius, Triton, etc.). Public mainnet RPC is rate-limited. | | `InvalidOracleConfig` | The reserve's `tokenInfo` doesn't match a real oracle account. Run `get-oracle-mappings` to find the correct addresses. | | `Reserve init failed: account already exists` | Re-running `add-asset-to-market` with the same mint. Each mint can have only one reserve per market. | | `Insufficient funds for transaction fee` | The admin wallet is empty. Send a small amount of SOL. | For a wider catalog of errors, see [Troubleshooting](/curators/markets/troubleshooting). # Updating Reserves Source: https://docs.kamino.com/curators/markets/reserve-management Edit reserve configurations after launch: parameters, caps, status, oracles After a reserve is live, every parameter on its `ReserveConfig` is editable through the same fetch → mutate → apply pattern as market settings. This page covers the day-to-day workflow. > [tab] SDK > > ## Update a reserve via SDK > > The SDK exposes `kaminoManager.updateReserveIxs(signer, marketWithAddress, reserveAddress, newReserveConfig)` for full reserve config updates. Fetch the current config, mutate, pass the new value in. > > **1. Initialize KaminoManager and fetch the reserve** > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket, Reserve } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > > const adminSigner = await parseKeypairFile('/path/to/admin.json'); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketAddress = address(''); > const reserveAddress = address(''); > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > > const reserve = await Reserve.fetch(rpc, reserveAddress); > if (!reserve) throw new Error('Reserve not found'); > ``` > > **2. Mutate the fields you want to change** > > ```typescript theme={"theme":"css-variables"} > const newConfig = { ...reserve.config }; > > // Examples — mix and match per your update: > newConfig.loanToValuePct = 80; > newConfig.liquidationThresholdPct = 85; > newConfig.borrowFactorPct = 100n; > newConfig.depositLimit = 5_000_000_000_000n; > newConfig.borrowLimit = 4_500_000_000_000n; > newConfig.utilizationLimitBlockBorrowingAbovePct = 90; > newConfig.protocolTakeRatePct = 10; > newConfig.status = 0; // 0 Active, 1 Obsolete, 2 Hidden > ``` > > For oracle changes, see [Configure oracles](/curators/markets/configuring-oracles). For elevation groups, see [Elevation groups](/curators/markets/elevation-groups). > > **3. Apply the update** > > ```typescript theme={"theme":"css-variables"} > const updateIxs = await kaminoManager.updateReserveIxs( > adminSigner, > marketWithAddress, > reserveAddress, > newConfig, > ); > > async function buildAndSendTx(ixs: any[]) { > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayerSigner(adminSigner, tx), > (tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > (tx) => appendTransactionMessageInstructions(ixs, tx) > ) > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > }); > } > > for (const { ixs } of updateIxs) { > await buildAndSendTx(ixs); > } > ``` > > `updateReserveIxs` returns the update split into chunks for transaction size; submit each chunk in order. > > ### Cloning a reserve config > > To duplicate an existing reserve's config onto a new reserve, see [Add reserves → Cloning an existing reserve config via SDK](/curators/markets/adding-reserves#cloning-an-existing-reserve-config-via-sdk). > > ### Multisig mode > > Replace the admin signer with `noopSigner(multisigPubkey)` and submit the resulting transactions as Squads proposals. > [tab] API > > > [!NOTE] > > > > **Reserve configuration updates are not available via the REST API.** The Kamino API supports reading reserve metrics and historical data; reserve configuration is an admin operation available through the **SDK** or **Kamino CLI**. > > To update reserve configurations, use the **SDK** or **Kamino CLI** tabs. > > For reading reserve metrics, see [Read market data](/curators/markets/market-data). > [tab] Kamino CLI > > ## Update a reserve via CLI > > The standard edit flow: > > **1. Download the current config** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-reserve-config \ > --reserve \ > --output ./configs/.json > ``` > > **2. Edit the JSON** > > Change only the fields you intend to change. The CLI computes the diff against on-chain state on `inspect`. > > **3. Inspect** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-reserve-config \ > --reserve \ > --reserve-config-path ./configs/.json \ > --mode inspect > ``` > > Open the printed Solana Explorer URL; verify the diff matches your intent. > > **4. Execute or propose** > > Hot-wallet-owned: re-run with `--mode execute`. > > Multisig-owned: re-run with `--mode multisig --multisig `. Submit the printed base58 transaction as a Squads proposal. > > ### Focused command for the borrow cap > > For just adjusting `borrowLimit` (the most-frequent change): > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-reserve-config-debt-cap \ > --reserve \ > --mode multisig \ > --multisig > ``` > > Faster to review than a full config update; useful when ramping a maturing reserve. ## Common edits ### Adjust LTV / liquidation threshold / borrow factor Edit `loanToValuePct`, `liquidationThresholdPct`, `borrowFactorPct`. Existing positions continue using the new values from the next refresh. > [!WARNING] > > Lowering `liquidationThresholdPct` below the LTV of existing positions causes those positions to become liquidatable on the next refresh. Communicate parameter tightening publicly in advance, or set the change to take effect only after a cooldown. ### Adjust deposit / borrow caps Edit `depositLimit` and/or `borrowLimit`. The CLI's focused `update-reserve-config-debt-cap` command exists for the borrow cap. ### Change the IR curve Edit `borrowRateCurve.points`. The change takes effect from the next interest accrual; current debts continue accruing at the new rate. ### Update oracle config Edit fields under `tokenInfo`. The on-chain validator confirms the new oracle accounts match what was passed in the instruction; mismatches return `InvalidScopePriceAccount`. For a full oracle migration, do it as a single update: clear old fields, set new fields, apply. See [Configure oracles](/curators/markets/configuring-oracles). ### Pause a reserve Set `status: 1` (Obsolete) or `status: 2` (Hidden). | Status | Effect | | - | - | | `0` Active | Normal operation | | `1` Obsolete | Existing positions continue; signals integrators not to surface for new activity | | `2` Hidden | Hidden from default UIs | For a stronger pause that blocks operations program-side, use `block_price_usage: 1` on the reserve's `tokenInfo` (rejects every operation that needs the price) or `emergency_mode: 1` on the reserve. See [Emergency controls](/curators/markets/emergency-controls). ### Enable / disable advanced features Most advanced features have flags at the **market** level — withdrawal queue, borrow orders, obligation orders, fixed-term rollover windows. The reserve-level fixed-term parameters (`debt_term_seconds`, `host_fixed_interest_rate_bps`, `early_repay_remaining_interest_pct`) live on `ReserveConfig` and use the standard reserve update flow. See: * [Withdrawal queue](/curators/markets/withdrawal-queue) (market-level) * [Fixed rate reserves](/curators/markets/fixed-rate-reserves) (reserve-level + market-level) * [Borrow orders](/curators/markets/borrow-orders) (market-level) * [Obligation orders](/curators/markets/obligation-orders) (market-level + reserve-level fee) ## Multisig considerations For multisig-owned markets, every reserve update is a Squads proposal subject to the configured timelock. Plan parameter changes accordingly — a 12-hour timelock means an LTV adjustment proposed at 9:00 AM executes at 9:00 PM. For changes that need to land faster (e.g., closing a reserve in response to an oracle incident), use [Emergency controls](/curators/markets/emergency-controls) — `borrow_disabled` or `block_price_usage` flips can be batched into a single emergency proposal that takes precedence over slower-cadence parameter tuning. ## Common errors | Error | Cause | | - | - | | `InvalidConfig` | A field is out of range (e.g., `loanToValuePct > 100`, or `liquidationThresholdPct < loanToValuePct`). | | `InvalidOracleConfig` / `InvalidScopePriceAccount` | Oracle pubkey in `tokenInfo` doesn't match the account passed to the instruction. | | `MarketImmutable` | Market has `immutable: 1`. No further updates are possible. | | `Unauthorized` | The signer isn't the `lending_market_owner`. Check ownership with `get-market-or-vault-admin-info`. | ## Reference * [Reserve config reference](/curators/markets/reserve-parameters) — every editable field * [Risk parameters](/curators/markets/risk-parameters) — choosing values * [Emergency controls](/curators/markets/emergency-controls) — pause and freeze flows * [`market-operations` CLI reference](/build/cli/market-operations) — full CLI flag detail # Reserve Config Reference Source: https://docs.kamino.com/curators/markets/reserve-parameters Every editable field on a Kamino reserve This is the canonical reference for `ReserveConfig` — the on-chain struct that defines every parameter of a Kamino reserve. Field names below match the JSON used by the kamino-manager CLI (camelCase). The on-chain Rust struct uses snake_case; the SDK handles the conversion. For guidance on choosing values, see [Risk parameters](/curators/markets/risk-parameters), [Configure oracles](/curators/markets/configuring-oracles), and the topic-specific guides linked from each section below. ## Reserve status | Field | Type | Description | | - | - | - | | `status` | u8 enum | `0` Active (normal operation), `1` Obsolete (existing positions continue; signals not for new activity), `2` Hidden (hidden from default UIs) | ## Risk parameters | Field | Type | Description | | - | - | - | | `loanToValuePct` | u8 (0–100) | Maximum borrowing capacity against this asset as collateral, in percent of USD value | | `liquidationThresholdPct` | u8 (0–100) | LTV at which a position becomes liquidatable. Must be ≥ `loanToValuePct` | | `borrowFactorPct` | u64 (≥100) | Risk multiplier on debt-side valuation. `100` = no adjustment; higher values shrink effective borrow capacity | | `disableUsageAsCollOutsideEmode` | u8 (bool) | If `1`, this asset can be used as collateral only inside elevation groups | | `utilizationLimitBlockBorrowingAbovePct` | u8 (0–100) | Block new borrows when utilization is above this percent. `0` disables | ## Capacity limits | Field | Type | Description | | - | - | - | | `depositLimit` | u64 (token base units) | Maximum total deposits accepted. `0` = no limit | | `borrowLimit` | u64 (token base units) | Maximum total borrows. `0` = no borrows allowed | | `borrowLimitOutsideElevationGroup` | u64 | Borrow cap against this asset as collateral when borrower is outside any eMode group. `u64::MAX` = no cap | | `borrowLimitAgainstThisCollateralInElevationGroup` | array of 32 u64 | Per-group borrow cap against this asset as collateral. Index = `group_id - 1` | ## Withdrawal caps Each cap is a `WithdrawalCaps` struct with these fields: | Field | Type | Description | | - | - | - | | `configCapacity` | i64 (token base units) | Maximum net flow per interval. `0` disables the cap | | `currentTotal` | i64 | Net flow within the current interval (program-managed) | | `lastIntervalStartTimestamp` | u64 | Unix timestamp when the current interval started (program-managed) | | `configIntervalLengthSeconds` | u64 | Interval length in seconds. Common: `86400` (1 day) | Two caps per reserve: | Field | Throttles | | - | - | | `depositWithdrawalCap` | Net deposit / withdrawal flow on the collateral side | | `debtWithdrawalCap` | Net borrow / repay flow on the debt side | ## Liquidation parameters | Field | Type | Description | | - | - | - | | `minLiquidationBonusBps` | u16 (0–10000) | Minimum bonus paid to liquidators | | `maxLiquidationBonusBps` | u16 (0–10000) | Maximum bonus paid to liquidators | | `badDebtLiquidationBonusBps` | u16 (0–10000) | Bonus when liquidating bad-debt positions (debt > collateral) | | `protocolLiquidationFeePct` | u8 (0–100) | Protocol's cut of liquidation proceeds | ## Auto-deleverage | Field | Type | Description | | - | - | - | | `autodeleverageEnabled` | u8 (bool) | Per-reserve enablement (market-level flag must also be `1`) | | `deleveragingMarginCallPeriodSecs` | u64 | Per-reserve override for the margin-call grace period. `0` falls back to the market default | | `deleveragingThresholdDecreaseBpsPerDay` | u64 | Effective liquidation threshold drops by this many bps per day after margin call | | `deleveragingBonusIncreaseBpsPerDay` | u64 | Liquidator bonus rises by this many bps per day after margin call | | `minDeleveragingBonusBps` | u16 | Floor on the deleverage-specific bonus | ## Interest rate curve ```jsonc theme={"theme":"css-variables"} "borrowRateCurve": { "points": [ { "utilizationRateBps": 0, "borrowRateBps": 0 }, // up to 11 points ] } ``` | Field | Type | Description | | - | - | - | | `borrowRateCurve.points` | array (exactly 11 entries) | Piecewise linear curve. Each entry: `{ utilizationRateBps, borrowRateBps }`. The curve must be non-decreasing in both fields. | | `utilizationRateBps` | u16 (0–10000) | Utilization at this breakpoint, in basis points | | `borrowRateBps` | u32 | Borrow rate at this utilization, in basis points | The first point should be `(0, 0)` or `(0, 1)`. The last point should be `(10000, max_rate)`. Pad unused slots by repeating the final point. ## Fees | Field | Type | Description | | - | - | - | | `fees.borrowFee` | string (decimal) | Origination fee charged on each borrow. `"0.001"` = 0.1% | | `fees.flashLoanFee` | string (decimal) | Flash loan fee. `"0.001"` = 0.1% | | `protocolTakeRatePct` | u8 (0–100) | Percent of accrued interest routed to protocol fees (depositors receive the remainder) | | `protocolOrderExecutionFeePct` | u8 (0–100) | Percent of obligation order execution proceeds routed to protocol fees | ## Token info / oracle config ```jsonc theme={"theme":"css-variables"} "tokenInfo": { "name": "USDC", "heuristic": { "lower": 0, "upper": 0, "exp": 0 }, "maxAgePriceSeconds": 120, "maxAgeTwapSeconds": 240, "maxTwapDivergenceBps": 4050, "scopeConfiguration": { /* ... */ }, "blockPriceUsage": 0 } ``` | Field | Type | Description | | - | - | - | | `name` | UTF-8 string (≤32 bytes) | Token symbol. Surfaced in tooling | | `heuristic.lower` | u64 | Sanity bound: minimum acceptable price = `lower * 10^exp`. `0` disables | | `heuristic.upper` | u64 | Sanity bound: maximum acceptable price | | `heuristic.exp` | u64 | Decimal exponent for the heuristic bounds | | `maxAgePriceSeconds` | u64 | Reject prices older than this many seconds | | `maxAgeTwapSeconds` | u64 | Reject TWAPs older than this many seconds. Required if TWAP is enabled | | `maxTwapDivergenceBps` | u64 (0–10000) | Reject prices that deviate from TWAP by more than this. `0` disables the TWAP guard | | `blockPriceUsage` | u8 (bool) | If `1`, every operation needing this reserve's price is rejected. Emergency switch | ### Scope configuration ```jsonc theme={"theme":"css-variables"} "scopeConfiguration": { "priceFeed": "", "priceChain": [0, 65535, 65535, 65535], "twapChain": [52, 65535, 65535, 65535] } ``` | Field | Type | Description | | - | - | - | | `priceFeed` | Pubkey | Scope `OraclePrices` account | | `priceChain` | u16 array (length 4) | Indices into the Scope feed forming the price chain. `65535` is the unused-slot sentinel | | `twapChain` | u16 array (length 4) | TWAP indices for the same chain | ## Fixed-Rate Parameters Fixed-rate reserves use the same primitives as floating reserves plus four config fields that pin the rate and impose a term. See [Fixed Rates](/curators/markets/fixed-rates) for the full configuration workflow. | Parameter | Type | Description | | - | - | - | | `hostFixedInterestRateBps` | Basis points (u16) | Optional protocol-side spread layered on top of `borrowRateCurve`. Charged to the borrower and accruing 100% to the protocol. Default `0`. | | `debtTermSeconds` | u64 (seconds) | Per-borrow term. Each borrow matures at `last_borrowed_at_timestamp + debtTermSeconds`. `0` = open-term (the reserve behaves as floating). Cannot be shortened on a reserve with active borrows. | | `debtMaturityTimestamp` | u64 (Unix seconds) | Reserve-wide sunset. After this, no new borrows are accepted and existing borrows become liquidatable (gated by market flag). `0` = no sunset. Must not be set in the past. | | `earlyRepayRemainingInterestPct` | Integer (0–100) | Penalty for repaying inside the first term. Penalty = projected interest for the remaining term × this percentage. Accrues to protocol fees on the debt reserve. | For a fixed-rate reserve, configure `borrowRateCurve` as a flat curve at the target rate (both endpoints set to the same `borrowRateBps`) and leave `hostFixedInterestRateBps` at `0` unless an intentional protocol spread is required. ## Elevation groups | Field | Type | Description | | - | - | - | | `elevationGroups` | u8 array (length 20) | List of elevation group IDs this reserve participates in. `0` slots are unused | See [Elevation groups](/curators/markets/elevation-groups). ## Fixed-term | Field | Type | Description | | - | - | - | | `debtTermSeconds` | u64 | Duration of fixed-term borrows on this reserve. `0` = open-term (default) | | `debtMaturityTimestamp` | u64 | Absolute Unix timestamp when all debt on this reserve matures (cohort mode). `0` = per-borrow rolling term | | `hostFixedInterestRateBps` | u16 | Fixed-rate component (bps) added on top of the IR curve rate | | `earlyRepayRemainingInterestPct` | u8 (0–100) | Percent of remaining interest owed on early repay | See [Fixed rate reserves](/curators/markets/fixed-rate-reserves). ## Emergency | Field | Type | Description | | - | - | - | | `emergencyMode` | u8 (bool) | Per-reserve emergency mode. `1` halts operations on this reserve | | `proposerAuthorityLocked` | u8 (bool) | If `1`, blocks the proposer authority from updating this reserve config | | `blockCtokenUsage` | u8 (bool) | If `1`, blocks using this reserve's cTokens as collateral | See [Emergency controls](/curators/markets/emergency-controls). ## Fields to ignore The following appear in some example JSON files but are not part of the current `ReserveConfig` struct. Treat them as no-ops; the program ignores them on update: | Stale field | Status | | - | - | | `assetTier` | Deprecated. Replaced by elevation groups. | | `multiplierSideBoost` | Removed. | | `multiplierTagBoost` | Removed. | If you encounter these in older configs, you can leave them in place (the on-chain struct ignores unrecognized fields during update) or strip them for clarity. ## Reading the live config ```bash theme={"theme":"css-variables"} yarn kamino-manager download-reserve-config \ --reserve ``` Saves the canonical, on-chain config to a JSON file. Use this as the source of truth before editing. ## Reference * [Risk parameters](/curators/markets/risk-parameters) — choosing LTV, threshold, IR curve, caps * [Configure oracles](/curators/markets/configuring-oracles) — TWAP and staleness setup * [Elevation groups](/curators/markets/elevation-groups) — eMode setup * [Fixed rate reserves](/curators/markets/fixed-rate-reserves) — fixed-rate, fixed-term lending * [Liquidations](/curators/markets/liquidations) — liquidation tunables * [Auto-deleverage](/curators/markets/auto-deleverage) — margin-call grace window (advanced, rarely used) * [Withdrawal caps](/curators/markets/withdrawal-caps) — per-interval rate limits * [Updating reserves](/curators/markets/reserve-management) — the update workflow # Risk Parameters Source: https://docs.kamino.com/curators/markets/risk-parameters Choose LTV, liquidation thresholds, IR curves, caps, and borrow factors for a reserve Risk parameters are how a curator expresses a thesis about an asset. They determine how much can be borrowed against it, when liquidations trigger, what the cost of borrowing is at each utilization level, and how much capital can flow into and out of the reserve. This page is a guide to choosing values. Every field documented here is in [Reserve config reference](/curators/markets/reserve-parameters); refer there for the full schema and defaults. ## The relationship between LTV and liquidation threshold ``` loanToValuePct <= liquidationThresholdPct <= 100 ``` | Field | What it does | | - | - | | `loanToValuePct` | Maximum borrowing capacity against the asset, as a percent of its USD value. A user with \$1,000 of an asset at 75% LTV can borrow \$750 of debt. | | `liquidationThresholdPct` | The point at which the position becomes liquidatable. Must be `>= loanToValuePct`. The gap between the two is the **liquidation buffer** — the cushion a borrower has before being liquidatable. | | `liquidationThresholdPct - loanToValuePct` | The buffer. Wider buffers reduce liquidation frequency at the cost of borrowing capacity. | Common reference points used across major Kamino markets: | Asset class | LTV | LT | Buffer | | - | - | - | - | | Major stablecoins (in stables-only group) | 90–95% | 92–97% | 2–3% | | Major liquid assets (SOL, BTC, ETH) | 70–80% | 75–85% | 5–10% | | LSTs paired with their underlying (eMode) | 88–92% | 90–95% | 2–5% | | Long-tail volatile assets | 30–55% | 50–70% | 10–20% | | Newly listed assets | Start conservative; widen later | | | These are reference ranges. Tune them to each asset based on its volatility profile, on-chain liquidity, oracle reliability, and historical depeg / recovery behavior. ## Borrow factor ```jsonc theme={"theme":"css-variables"} { "borrowFactorPct": 100 } ``` A multiplier on the *debt-side* valuation of an asset. Borrowing 100 units of an asset with `borrowFactorPct: 125` is treated as if you borrowed 125 units for risk purposes — making the position behave more conservatively. | borrowFactorPct | Effect | | - | - | | `100` | No adjustment. Default for stables and major assets. | | `125` | Debt is treated as 25% larger than its market value. Use for assets where post-liquidation slippage is higher than typical. | | `200+` | Aggressive overweight. Use for highly volatile or thinly traded debt assets. | The program enforces `borrowFactorPct >= 100`; values below have no effect. ## The interest rate curve ```jsonc theme={"theme":"css-variables"} { "borrowRateCurve": { "points": [ { "utilizationRateBps": 0, "borrowRateBps": 0 }, { "utilizationRateBps": 7000, "borrowRateBps": 500 }, { "utilizationRateBps": 8500, "borrowRateBps": 1500 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 } ] } } ``` The borrow rate is determined by reserve utilization (`borrowed / deposited`) using a piecewise linear curve. The curve must satisfy: * Exactly 11 points (pad with the final point repeated if you have fewer breakpoints) * `utilizationRateBps` strictly non-decreasing from `0` to `10000` (`0%` to `100%`) * `borrowRateBps` non-decreasing across the curve * Rate between two breakpoints is linearly interpolated ### Designing the curve The economics of an IR curve hinge on the **kink** — the breakpoint where the rate starts climbing steeply. | Region | Purpose | | - | - | | `0% → kink` | Mild slope. Lets borrowers access cheap leverage when liquidity is abundant. | | `kink → 100%` | Steep slope. Penalizes high utilization, pulls borrowers to repay and lenders to deposit. | For most assets, the kink sits at 70–85% utilization. The slope above the kink is what enforces solvency: at 95% utilization, depositors should earn enough that capital flows in; borrowers should pay enough that capital flows out. A common shape: | Utilization | Borrow rate | | - | - | | 0% | 0% | | 70% | 5% (the kink) | | 85% | 15% | | 100% | 80%+ | The exact numbers depend on the asset and demand. Stablecoins with steady deposit demand can run with kinks at 90% and tighter slopes; volatile or thinly-supplied assets need wider slopes to keep utilization in check. ### Padding the array The on-chain struct expects 11 points. If your curve has fewer real breakpoints, repeat the final point to fill: ```jsonc theme={"theme":"css-variables"} { "points": [ { "utilizationRateBps": 0, "borrowRateBps": 0 }, { "utilizationRateBps": 7000, "borrowRateBps": 500 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 }, { "utilizationRateBps": 10000, "borrowRateBps": 8000 } ] } ``` ## Deposit and borrow caps ```jsonc theme={"theme":"css-variables"} { "depositLimit": "1000000000000", "borrowLimit": "900000000000" } ``` Limits are denominated in **token base units** (lamports for SOL, smallest unit for the token's decimals). | Cap | Effect | | - | - | | `depositLimit` | Hard ceiling on total deposits. New deposits beyond this revert. Set higher than `borrowLimit` to leave a withdrawal buffer. | | `borrowLimit` | Hard ceiling on total borrows. New borrows beyond this revert. | A common pattern for new reserves: | Phase | depositLimit | borrowLimit | | - | - | - | | Initial listing | Conservative (e.g., \$1M equivalent) | 80–90% of `depositLimit` | | After 30 days of clean operation | 2–5× initial | Same ratio | | Steady state | Asset-specific; track asset's on-chain liquidity | Same ratio | `borrowLimit < depositLimit` ensures there is always some unborrowed liquidity (subject to live withdrawals). `borrowLimit == depositLimit` allows full utilization but means depositors may need the [withdrawal queue](/curators/markets/withdrawal-queue) to redeem. A focused command exists for adjusting just the borrow cap: ```bash theme={"theme":"css-variables"} yarn kamino-manager update-reserve-config-debt-cap \ --reserve \ --mode multisig \ --multisig ``` ## Utilization-based borrow blocking ```jsonc theme={"theme":"css-variables"} { "utilizationLimitBlockBorrowingAbovePct": 80 } ``` Blocks new borrows once utilization exceeds the configured percentage. `0` disables. Useful as a softer alternative to `borrowLimit` for reserves where you want to throttle leverage at high utilization without capping total deposits. Example: `utilizationLimitBlockBorrowingAbovePct: 90` means borrows revert when utilization is above 90%, while existing borrows and repayments continue unaffected. ## Fees ```jsonc theme={"theme":"css-variables"} { "fees": { "borrowFee": "0", "flashLoanFee": "0" }, "protocolTakeRatePct": 0, "protocolLiquidationFeePct": 0, "protocolOrderExecutionFeePct": 0 } ``` | Fee | Charged on | How it accrues | | - | - | - | | `fees.borrowFee` | Origination of every borrow, as a decimal string (e.g. `"0.001"` = 0.1%) | Added to borrow's debt at origination | | `fees.flashLoanFee` | Each flash loan | Charged in the same instruction as the flash repay | | `protocolTakeRatePct` | Interest accrual on the reserve | Percentage (0–100) of accrued interest routed to protocol fees | | `protocolLiquidationFeePct` | Liquidations | Percentage (0–100) of liquidation proceeds routed to protocol fees | | `protocolOrderExecutionFeePct` | Filled obligation orders | Percentage (0–100) of filled order proceeds routed to protocol fees | Default for curator markets: all zero. Curator-set fees go to the curator-controlled `lending_market_owner` via [`redeem_fees`](/curators/markets/protocol-fees). ## Reserve status ```jsonc theme={"theme":"css-variables"} { "status": 0 } ``` | Value | State | Meaning | | - | - | - | | `0` | Active | Normal operation | | `1` | Obsolete | Deprecated — the program treats this similarly to active for existing positions but signals to integrators not to surface for new activity | | `2` | Hidden | Hidden from default UIs | Most reserves stay at `0`. Use `1` when phasing out a reserve while honoring existing obligations. ## Putting it together: a checklist for a new reserve **1. Pick LTV and liquidation threshold** Use comparable Kamino reserves as a starting reference. For a never-listed asset, start more conservatively than analogues and widen later. **2. Set borrow factor** `100` for major assets and stables. `125`+ for assets with thinner exit liquidity. **3. Design the IR curve** Pick a kink (typically 70–85% utilization). Set base rate at the kink (3–8% for stables, 5–15% for volatile assets). Set max rate at 100% utilization (40–80% APR is common). **4. Choose caps** `depositLimit` proportional to the asset's verified on-chain liquidity. `borrowLimit` 80–90% of `depositLimit`. **5. Set fees** `protocolTakeRatePct` = 0–20% if you want the curator to capture interest revenue. Origination fees default to `0` for most consumer-facing reserves. **6. Configure the oracle** Scope is the default. Set TWAP and staleness guards. → [Configure oracles](/curators/markets/configuring-oracles) **7. Decide on advanced features** eMode? Auto-deleverage? Withdrawal queue? Fixed-term? Each is opt-in. → [Lifecycle](/curators/markets/lifecycle#optional-features-and-when-to-enable-them) ## Reference * [Reserve config reference](/curators/markets/reserve-parameters) — every field documented * [Liquidations](/curators/markets/liquidations) — what happens when LT is breached * [Elevation groups](/curators/markets/elevation-groups) — relaxed parameters for correlated assets # Scope Oracle Types Source: https://docs.kamino.com/curators/markets/scope-oracle-types Specialized Scope oracle entry types for fixed-income, multi-source, pegged, and LST assets Beyond a plain price feed, Scope supports specialized oracle entry types that each compute a price in a specific way for a class of asset. You select one as the source of a reserve's Scope chain when wiring the oracle, covered in [Configure oracles](/curators/markets/configuring-oracles). > [!NOTE] > > These types are configured on the Scope side and referenced by their index in a reserve's `priceChain`. Coordinate with the Kamino team to add a Scope entry for your asset. | Type | What it computes | Use for | | - | - | - | | `DiscountToMaturity` | Fair value of a discounted instrument that redeems at par on a known date | Zero-coupon bonds, T-bills, PT-tokens, vesting tranches | | `MostRecentOf` | Freshest price across up to 4 sources, with staleness and divergence guards | Multi-provider resilience | | `CappedFloored` | A source price clamped to a ceiling, a floor, or both | Pegged and regulated stablecoins | | `CappedMostRecentOf` | `MostRecentOf` with an upper bound applied | Multi-source pegged assets | | `SplStake` | An SPL Stake Pool's redemption rate | LST reference pricing | ## DiscountToMaturity Models a fixed-income instrument that trades at a discount and redeems at par on a known date. You configure an annual discount rate (in basis points) and a maturity timestamp. The oracle computes the current fair value by applying that discount linearly over the remaining time, so the price starts below 1.0 and climbs smoothly to exactly 1.0 at maturity, regardless of market noise. **When to use it.** Any token that represents a claim on a fixed future redemption: zero-coupon bonds, treasury bills, PT-tokens, vesting tranches, or structured credit instruments where the terminal value is known but the current fair value depends on time elapsed. ## MostRecentOf Aggregates up to 4 price sources and returns the price from whichever was updated most recently, subject to two safety guards. **Staleness.** All sources must have been updated within a configurable time window. If any single source goes stale, the oracle fails rather than silently serving an old price. This is intentional, because the divergence check below only makes sense when all sources are live. **Divergence.** The spread between the highest and lowest price across all sources must stay within a configurable tolerance. If the sources disagree beyond that threshold, the oracle fails rather than picking one arbitrarily. **When to use it.** When you want resilience across multiple data providers (for example Chainlink plus Pyth Pro) without trusting any single one. The "most recent wins" rule keeps latency low in normal conditions, while the divergence check acts as a circuit breaker the moment the feeds disagree, protecting against a compromised or malfunctioning provider silently manipulating the result. ## CappedFloored Wraps any source oracle and bounds its price. The cap and floor are themselves oracle entries, so each can be dynamic (for example derived from a protocol invariant) or a hardcoded constant. ### 1. Capped Prevents the source price from exceeding a configured ceiling. **When to use it.** Stablecoins and pegged assets where the price should never be accepted above peg, even if a market feed briefly reports it there. Also useful for any token with a hard protocol-level redemption ceiling: using a live oracle for the cap means the ceiling tracks protocol state automatically rather than requiring manual updates. ### 2. Floored The mirror of Capped: prevents the source price from falling below a configured floor. **When to use it.** Regulated stablecoins that should not take temporary depegs into account. > [!NOTE] > > Cap and floor can be combined on the same source entry, giving a bounded range. The price is accepted only if it falls between the floor and the ceiling, and is clamped to whichever bound it crosses. ## CappedMostRecentOf Combines `MostRecentOf` and `Capped` in a single oracle: it selects the freshest price from multiple sources (with the same divergence and staleness checks), then applies an upper bound. **When to use it.** Whenever you want the resilience of multiple providers but also need a hard ceiling. For example, using several market feeds for a pegged asset while ensuring the result can never exceed peg, even during a brief depeg in a single feed. ## SplStake Reads an SPL Stake Pool account directly and returns the pool's current redemption rate: how many SOL you would receive per staked pool token if you unstaked today. Because the stake rate is only updated once per epoch (roughly every 2 to 3 days), this oracle is intentionally designated as a reference price, not a primary valuation source. It does not reflect real-time market dynamics, does not account for unstaking fees, and ignores that secondary-market prices are typically lower than the theoretical stake rate. **When to use it.** LSTs, where the stake rate provides a slow-moving, manipulation-resistant floor that the market price is compared against. ## Feature: Reference Price Check A per-oracle safety mechanism that validates incoming price updates against a separately designated reference price. When configured, every time an oracle entry is refreshed the new price is compared to its reference. If the two diverge by more than a configurable tolerance (default 5%), the update is either blocked or the transaction reverts, depending on how the caller has configured the strictness. **Why this matters.** A reference price is typically a constant that can be updated regularly (for RWAs) or a slow-moving, hard-to-manipulate value such as a long TWAP or a NAV, paired with a faster market feed. The check creates a circuit breaker: the market feed is accepted in normal conditions, but the moment it moves too far from the reference, indicating a potential oracle attack, flash loan manipulation, or feed failure, the update is rejected until the discrepancy resolves. ## Reference * [Configure oracles](/curators/markets/configuring-oracles): wire a reserve to a Scope feed * [Oracle architecture overview](/security/oracles): Scope, price protection, and manipulation resistance # Transfer Ownership to a Multisig Source: https://docs.kamino.com/curators/markets/transfer-to-multisig Move market ownership from a hot wallet to a Squads multisig Every production market should be owned by a multisig. The recommended setup is [Squads v4](https://squads.so) with a hardware-wallet signer set and a timelock. Transfer is a deliberate two-step on-chain process designed to prevent typos from locking you out. > [!NOTE] > > All Kamino-deployed markets use Squads v4 with a 12-hour timelock on SOL/BTC Market and shorter timelocks on satellite markets. Curator markets should match this posture before opening to external users. ## How the transfer works The `LendingMarket` account has two owner-related fields: | Field | Role | | - | - | | `lending_market_owner` | The active owner. Authorized to update the market and reserves. | | `lending_market_owner_cached` | A staging slot. The current owner sets it; only that cached pubkey can finalize the swap. | The transfer runs in two steps. First, the current owner sets `lending_market_owner_cached` to the multisig pubkey. The active owner doesn't change yet; only the staging slot moves. Second, a signer at the new owner address (the multisig itself) calls `update-lending-market-owner`, which copies the cached value into the live `lending_market_owner` and finalizes the transfer. The split exists so a typo in the cached pubkey is recoverable: the current owner can re-set the cached field as many times as needed before promotion. Only the second step is irreversible from your side. > [tab] SDK > > ## Transfer ownership via SDK > > The SDK exposes `updatePendingLendingMarketAdminIx` for step 1 and `updateLendingMarketOwnerIxs` for step 2. > > **1. Initialize KaminoManager and fetch the market** > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > generateKeyPairSigner, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > noopSigner, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > > const initialAdmin = await parseKeypairFile('/path/to/current-owner.json'); > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > > const marketAddress = address(''); > const newOwnerAddress = address(''); > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > ``` > > **2. Step 1 — cache the new owner** > > ```typescript theme={"theme":"css-variables"} > const ix1 = kaminoManager.updatePendingLendingMarketAdminIx( > initialAdmin, > marketWithAddress, > newOwnerAddress, > ); > > async function buildAndSendTx(signer: any, ixs: any[]) { > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayerSigner(signer, tx), > (tx) => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > (tx) => appendTransactionMessageInstructions(ixs, tx) > ) > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > }); > } > > await buildAndSendTx(initialAdmin, [ix1]); > console.log('Pending admin set to', newOwnerAddress); > ``` > > **3. Step 2 — promote the cached owner** > > This step must be signed by the new owner (the multisig). For a multisig, build the transaction with `noopSigner(newOwnerAddress)` and submit it as a Squads proposal. > > ```typescript theme={"theme":"css-variables"} > // Re-fetch the market state — its lending_market_owner_cached is now the new owner > const updatedMarketState = await LendingMarket.fetch(rpc, marketAddress); > if (!updatedMarketState) throw new Error('Market not found'); > marketWithAddress.state = updatedMarketState; > > const newOwnerSigner = noopSigner(newOwnerAddress); > const ix2 = kaminoManager.updateLendingMarketOwnerIxs(marketWithAddress, newOwnerSigner); > > // For a hot-wallet test (e.g., on staging), if the new owner is a real keypair, > // load it as a signer and submit directly: > // const newOwnerKp = await parseKeypairFile('/path/to/new-owner.json'); > // await buildAndSendTx(newOwnerKp, [ix2]); > > // For a Squads multisig, encode the transaction as base58 and submit it as a proposal. > ``` > > The full working example lives at [klend-sdk/examples/klend-examples/example_change_market_admin.ts](https://github.com/Kamino-Finance/klend-sdk/blob/master/examples/klend-examples/example_change_market_admin.ts). > [tab] API > > > [!NOTE] > > > > **Ownership transfer is not available via the REST API.** The Kamino API supports reading admin metadata; ownership transfer is an admin operation available through the **SDK** or **Kamino CLI**. > > To transfer ownership, use the **SDK** or **Kamino CLI** tabs. > > To inspect current ownership, query the on-chain `LendingMarket` account directly or use: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager get-market-or-vault-admin-info --address > ``` > [tab] Kamino CLI > > ## Transfer ownership via CLI > > ### Step 1 — cache the new owner > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager download-lending-market-config \ > --lending-market > ``` > > Edit the downloaded config at `./configs//market-.json`, set: > > ```jsonc theme={"theme":"css-variables"} > { > "lending_market_owner_cached": "" > } > ``` > > Inspect, then apply: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode inspect > > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode execute > ``` > > ### Step 2 — promote the cached owner > > This step must be signed by the multisig (the address you cached in Step 1). From the multisig, propose a transaction that calls `update-lending-market-owner`: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-lending-market-owner \ > --lending-market \ > --mode multisig \ > --multisig > ``` > > The CLI prints a base58 transaction. Submit it as a Squads proposal, collect signatures, execute. After execution, `lending_market_owner` equals your multisig. > > > [!WARNING] > > > > After Step 2 completes, the original hot wallet has no authority over the market. Verify the multisig signer set, the threshold, and the timelock before promoting. The program does not enforce a recovery path if you lose access to the multisig. > > ### All subsequent operations use multisig mode > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-reserve-config \ > --reserve \ > --reserve-config-path ./configs/config.json \ > --mode multisig \ > --multisig > ``` > > The CLI returns the base58 transaction. Submit, sign, wait out the timelock, execute. ## Setting up the Squads multisig A short walkthrough; full documentation lives at [Squads docs](https://docs.squads.so). **1. Create the Squad** On [squads.so](https://squads.so), create a new Squad. Choose your signer set (hardware wallets recommended for production) and a signature threshold (e.g., 3-of-5). **2. Configure a timelock** In Squad settings, enable a transaction timelock. Kamino's reference is 12h for SOL/BTC Market, 4h for satellite markets. Pick the value that fits your operational tempo and incident-response posture. **3. Fund the Squad** Send a small amount of SOL to the Squad's vault address to cover transaction fees on proposals. **4. Note the Squad pubkey** Use the Squad's vault address as the multisig pubkey passed to the SDK / CLI. ## Verifying transactions before signing A common pattern among security-conscious curators is to recompute the transaction locally and compare its hash to the proposal in Squads. Before signing a proposal: 1. Re-run the same SDK code (or CLI command with `--mode multisig`) 2. Compare the printed base58 transaction to what's surfaced in the Squads UI 3. Sign only if the bytes match exactly This guards against compromised proposals. ## Rotating the multisig later To move ownership to a new multisig after the first transfer is complete, repeat the two-step flow: 1. The current multisig submits a proposal that updates `lending_market_owner_cached` to the new multisig. 2. The new multisig submits a proposal that calls `update-lending-market-owner`. The same protections apply: you can re-set the cached field as many times as you want before the second step finalizes. ## Reference * [Market settings](/curators/markets/market-settings) — the broader market-level config flow * [Market config reference](/curators/markets/market-config-reference) — `lending_market_owner` and `lending_market_owner_cached` fields * [`market-operations` CLI reference](/build/cli/market-operations) — full CLI flag detail * [Squads docs](https://docs.squads.so) # Withdrawal Caps Source: https://docs.kamino.com/curators/markets/withdrawal-caps Throttle deposits, withdrawals, and debt activity on a per-reserve, per-interval basis Each reserve can configure two independent caps that throttle activity over a sliding interval. Caps are useful for newly-listed assets, regulated tokens, and any reserve where you want to limit how much can flow in or out per day without imposing a hard `depositLimit`/`borrowLimit` ceiling. ## The two caps Each reserve has two `WithdrawalCaps` structs: ```jsonc theme={"theme":"css-variables"} { "depositWithdrawalCap": { "configCapacity": "1000000000000", "configIntervalLengthSeconds": "86400" }, "debtWithdrawalCap": { "configCapacity": "500000000000", "configIntervalLengthSeconds": "86400" } } ``` | Cap | Throttles | | - | - | | `depositWithdrawalCap` | Net deposit / withdrawal flow on the reserve's collateral side | | `debtWithdrawalCap` | Net borrow / repay flow on the debt side | Both are denominated in **token base units** of the reserve's mint. ## Field semantics | Field | What it stores | | - | - | | `configCapacity` | Maximum net flow allowed within the interval. The cap counts both directions: deposits add to the running total, withdrawals subtract. The same applies for borrow / repay on the debt cap. | | `configIntervalLengthSeconds` | Length of the rolling interval, in seconds. `86400` = 24 hours. | | `currentTotal` | The current net flow within the active interval. Maintained on-chain; you don't set it manually. | | `lastIntervalStartTimestamp` | Unix timestamp when the active interval started. Maintained on-chain. | When the interval elapses (i.e., `now > lastIntervalStartTimestamp + configIntervalLengthSeconds`), `currentTotal` resets to zero on the next operation. ## Setting `configCapacity` to disable `configCapacity = 0` disables the cap (the program treats `0` as no limit). To enable a cap, set a positive value. To temporarily lock down a reserve, set `configCapacity` to a small positive value during a config update — the next operation that would push net flow above the cap will revert. Avoid `0`, which disables the cap entirely. ## Worked example A new reserve for a long-tail asset listed with `depositLimit = 10M tokens`. The curator wants to limit per-day inflows to 1M tokens during the first month to keep TVL growth proportionate to the asset's available on-chain liquidity. ```jsonc theme={"theme":"css-variables"} { "depositLimit": "10000000000000", // hard ceiling: 10M tokens "depositWithdrawalCap": { "configCapacity": "1000000000000", // per-day: 1M tokens "configIntervalLengthSeconds": "86400" } } ``` Day 1: the reserve fills up to 1M tokens, then further deposits revert until the interval resets. Day 2: the cap resets, another 1M tokens are accepted. After 30 days: increase `configCapacity` to scale with comfort. ## Common configurations | Reserve type | depositWithdrawalCap | debtWithdrawalCap | | - | - | - | | Newly-listed asset | Cap to \~10% of `depositLimit` per day | Cap to \~10% of `borrowLimit` per day | | Established stable | Disabled (`0`) | Disabled (`0`) | | Tokenized off-chain asset | Cap aligned with off-chain redemption capacity | Often disabled if not borrowable | | Regulated token (Token-2022) | Cap aligned with regulator-imposed flow constraints | Same | | Reserve with a vault on top | Disabled or very generous; vault-side rate limits handle UX | Same | ## Updating caps Edit the reserve config, run `update-reserve-config`: ```bash theme={"theme":"css-variables"} yarn kamino-manager update-reserve-config \ --reserve \ --reserve-config-path ./configs/updated.json \ --mode multisig \ --multisig ``` Updates take effect immediately. The `currentTotal` and `lastIntervalStartTimestamp` are not reset by a config update — the interval continues running with the new capacity. ## Caps vs. utilization-based blocking Two related fields throttle different things: | Mechanism | What it does | | - | - | | `depositWithdrawalCap` / `debtWithdrawalCap` | Limit *total* net flow per interval, regardless of utilization | | `utilizationLimitBlockBorrowingAbovePct` | Block new borrows when utilization is *currently* above the threshold, regardless of historical flow | Use caps when you want predictable per-day flow limits (e.g., asset-issuer agreements). Use the utilization limit when you care about preventing leverage at high utilization levels. The two work together: caps throttle volume, the utilization limit shapes the curve. ## Reading current cap state `download-reserve-config` returns `currentTotal` and `lastIntervalStartTimestamp` along with the configured fields. Use it to inspect how much of the current interval's capacity has been consumed. ```bash theme={"theme":"css-variables"} yarn kamino-manager download-reserve-config \ --reserve ``` ## Reference * [Reserve config reference](/curators/markets/reserve-parameters) — `depositWithdrawalCap` and `debtWithdrawalCap` fields * [Risk parameters](/curators/markets/risk-parameters) — `depositLimit`, `borrowLimit`, `utilizationLimitBlockBorrowingAbovePct` # Withdrawal Queue Source: https://docs.kamino.com/curators/markets/withdrawal-queue FIFO redemption mechanism for reserves at high utilization The withdrawal queue is a market-level mechanism that lets depositors hold a place in line for liquidity when a reserve is fully utilized. Instead of a withdrawal reverting because the available pool is empty, the depositor enqueues a `WithdrawTicket` and is paid out FIFO as borrowers repay, deposits arrive, or liquidations free liquidity. The queue is opt-in per market, controlled by three boolean flags on the `LendingMarket` account. ## When to enable the queue | Curator situation | Enable the queue | | - | - | | Reserves run at high utilization (>90% sustained) | Yes | | A vault sits on top, holding institutional capital subject to redemption requests | Yes | | Reserves typically run at moderate utilization with deep buffers | Optional | | Long-tail asset where exits are rare but should be predictable | Yes | | Reserves where you want every withdrawal to be instant or revert | Leave disabled | ## Three flags, three operations | Flag | What it gates | | - | - | | `withdraw_ticket_issuance_enabled` | `enqueue-to-withdraw`: a depositor can submit collateral and receive a ticket | | `withdraw_ticket_redemption_enabled` | `withdraw-queued-liquidity`: a ticket holder can claim their share when capacity is available | | `withdraw_ticket_cancellation_enabled` | `cancel-withdraw-ticket`: a ticket holder can exit the queue | Curators flip these together when launching the queue. The most useful intermediate state is `issuance + redemption` enabled, `cancellation` disabled — depositors can join the line and be paid, but cannot back out, which simplifies accounting for vaults sitting on top. ## The minimum queued value threshold `min_withdraw_queued_liquidity_value` sets the minimum USD value (scaled fraction) a single ticket may represent. Below the threshold, `enqueue-to-withdraw` reverts with `WithdrawTicketValueTooSmall`. | Value | Effect | | - | - | | `0` | No floor. Any-size tickets allowed (risk: dust spam) | | Reasonable floor (e.g., \$1 equivalent) | Filters dust, keeps the queue economically meaningful | | Aggressive floor (e.g., \$1000 equivalent) | Restricts the queue to sizable depositors only | > [tab] SDK > > ## Configure the queue via SDK > > Enabling the queue is a market-level config update. Use `kaminoManager.updateLendingMarketIxs` and toggle the relevant fields. > > ```typescript theme={"theme":"css-variables"} > import { > KaminoManager, > DEFAULT_RECENT_SLOT_DURATION_MS, > PROGRAM_ID, > MarketWithAddress, > } from '@kamino-finance/klend-sdk'; > import { LendingMarket } from '@kamino-finance/klend-sdk/dist/@codegen/klend/accounts'; > import { address } from '@solana/kit'; > > // ... rpc setup, adminSigner ... > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS, PROGRAM_ID); > const marketAddress = address(''); > > const marketState = await LendingMarket.fetch(rpc, marketAddress); > if (!marketState) throw new Error('Market not found'); > const marketWithAddress: MarketWithAddress = { address: marketAddress, state: marketState }; > > const newLendingMarket = { ...marketState }; > newLendingMarket.withdrawTicketIssuanceEnabled = 1; > newLendingMarket.withdrawTicketRedemptionEnabled = 1; > newLendingMarket.withdrawTicketCancellationEnabled = 1; > newLendingMarket.minWithdrawQueuedLiquidityValue = 100_000n; // adjust per asset > > const updateIxs = kaminoManager.updateLendingMarketIxs(adminSigner, marketWithAddress, newLendingMarket); > // submit each ix in order > ``` > > ### User-side queue operations > > The user-facing queue instructions (`enqueueToWithdraw`, `withdrawQueuedLiquidity`, `cancelWithdrawTicket`, `recoverInvalidTicketCollateral`) are part of the on-chain klend program. The current public klend-sdk does not yet expose dedicated TypeScript helpers for these. > > Until the helpers ship, end-user apps integrate the queue via: > > * A direct kvault deposit/redeem flow when a vault sits on top of the market (the vault submits the ticket on the user's behalf via its own kvault tooling) > * The Kamino webapp surface for queue-enabled markets that are listed in `resources.json` > * Building the ixes manually from the program IDL > > For curator-side enablement, the SDK flow above is the only thing you need. > [tab] API > > > [!NOTE] > > > > **Configuring the queue is not available via the REST API.** The flags live on `LendingMarket` and are flipped through the **SDK** or **Kamino CLI**. The REST API exposes read access to ticket and queue state for monitoring. > > To enable or configure the queue, use the **SDK** or **Kamino CLI** tabs. > > To monitor queue state, query the on-chain reserve and any open `WithdrawTicket` accounts directly, or use the [API reference](/build/api-reference/introduction) for reserve metrics. > [tab] Kamino CLI > > ## Configure the queue via CLI > > The queue flags live on the market config. Apply via the standard `update-lending-market-from-config` flow. > > ```bash theme={"theme":"css-variables"} > # 1. Download > yarn kamino-manager download-lending-market-config \ > --lending-market > > # 2. Edit ./configs//market-.json — set: > # "withdraw_ticket_issuance_enabled": 1 > # "withdraw_ticket_redemption_enabled": 1 > # "withdraw_ticket_cancellation_enabled": 1 > # "min_withdraw_queued_liquidity_value": "" > > # 3. Inspect > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode inspect > > # 4. Apply via multisig > yarn kamino-manager update-lending-market-from-config \ > --lending-market \ > --lending-market-config-path ./configs//market-.json \ > --mode multisig \ > --multisig > ``` ## Anatomy of a ticket When a depositor calls `enqueue-to-withdraw`, the program: 1. Burns their collateral cTokens from their wallet 2. Increments the reserve's `WithdrawQueue.queued_collateral_amount` 3. Creates a `WithdrawTicket` account with: * `sequence_number` (monotonically increasing per reserve) * `owner` (the depositor's wallet) * `reserve` (the reserve being withdrawn from) * `queued_collateral_amount` (the cTokens held in queue) * `created_at_timestamp` * `progress_callback_type` and `progress_callback_custom_accounts` (optional callback hook) The ticket is a Solana account. The depositor (or whoever submitted on their behalf) holds the right to redeem when their sequence number is up. ### Sequence numbers and FIFO order The reserve tracks two counters: ```rust theme={"theme":"css-variables"} struct WithdrawQueue { queued_collateral_amount: u64, next_issued_ticket_sequence_number: u64, next_withdrawable_ticket_sequence_number: u64, } ``` | Counter | What it tracks | | - | - | | `next_issued_ticket_sequence_number` | The number the **next** new ticket will receive. Increments on `enqueue-to-withdraw` | | `next_withdrawable_ticket_sequence_number` | The smallest number that has not yet been redeemed. Increments on `withdraw-queued-liquidity` after a ticket is fully closed | A ticket with sequence number `N` is redeemable when `next_withdrawable_ticket_sequence_number == N`, provided the reserve has enough liquidity to satisfy it. ## The redemption flow The reserve gains liquidity over time through borrower repayments, new deposits, liquidations, and (for markets with a vault sitting on top) the vault's `invest` operation routing capital in. Whenever liquidity is available, the holder of the next-eligible ticket can call `withdraw-queued-liquidity`. The program checks the ticket's `sequence_number` against the reserve's `next_withdrawable_ticket_sequence_number`; if they match, it pays out as much of the queued collateral as the available liquidity covers. Partial fills are allowed: a ticket that asks for \$100k against a reserve with \$30k free liquidity is paid \$30k now and waits for the rest. When a ticket is fully drained, the program closes its account and increments `next_withdrawable_ticket_sequence_number` so the next ticket in line becomes eligible. Holders watch the queue and submit the redemption transaction when liquidity allows; in practice, off-chain bots monitor and submit on behalf of users, which is how the standard Kamino UX surfaces the queue to depositors. ## Cancellation When `withdraw_ticket_cancellation_enabled = 1`, a ticket holder can call `cancel-withdraw-ticket` to back out of the queue: * The remaining `queued_collateral_amount` is converted back to cTokens and returned to the holder * The ticket is marked `invalid = 1` and closed * `next_withdrawable_ticket_sequence_number` does not advance — the cancelled slot is skipped on the next redemption Cancellation is a depositor-friendly feature. Disable it for institutional vaults where queue position is sold or transferred contractually under the off-chain agreement. ### Recovering invalid tickets If a ticket gets stuck in an invalid state (the program detects this on certain edge cases), the curator or emergency authority can call `recover-invalid-ticket-collateral` to drain its queued collateral and restore queue progression. ## Vault integration: progress callback A `WithdrawTicket` can carry an optional progress callback. When the ticket completes redemption, the program invokes the callback to notify a corresponding program — most commonly a Kamino vault. ```rust theme={"theme":"css-variables"} enum ProgressCallbackType { None = 0, KlendQueueAccountingHandlerOnKvault = 1, } ``` If a kvault submits the `enqueue-to-withdraw` on behalf of one of its depositors, the ticket can carry `KlendQueueAccountingHandlerOnKvault` so that on redemption, the kvault is automatically notified to credit the depositor's vault share. This is the standard pattern for institutional vaults sitting on top of a queue-enabled market. ## Common errors | Error | Cause | | - | - | | `WithdrawTicketValueTooSmall` | The ticket's value is below `min_withdraw_queued_liquidity_value`. Either reduce the threshold or have the depositor combine smaller withdrawals | | `WithdrawTicketIssuanceDisabled` | `withdraw_ticket_issuance_enabled = 0`. Enable the flag | | `WithdrawTicketRedemptionDisabled` | `withdraw_ticket_redemption_enabled = 0`. Enable the flag | | `WithdrawTicketCancellationDisabled` | `withdraw_ticket_cancellation_enabled = 0`. Enable the flag, or accept that cancellation is intentionally disabled | | Redemption returns less than expected | Reserve liquidity is partially available — the program pays out what it can; the ticket carries the remainder | ## Reference * [Market config reference](/curators/markets/market-config-reference) — queue-related fields * [Troubleshooting](/curators/markets/troubleshooting) — `WithdrawTicketValueTooSmall` and related dust edge cases * [Permissioned markets](/curators/markets/permissioned-markets) — gated venues where queue mechanics often pair with allowlist enforcement # Glossary Source: https://docs.kamino.com/curators/reference/glossary One-line definitions for every term used in the curator vault docs Click any term to jump to the canonical treatment. | Term | Definition | | - | - | | **Allocation Admin** | Limited admin role that can update weights, caps, types, and priorities on existing allocations only. See [Roles & ownership](/curators/vaults/concepts/roles-and-ownership#the-three-admin-roles). | | **Allocation Cap** | Hard ceiling on tokens deployed into a single reserve. See [Allocations](/curators/vaults/concepts/allocations#the-allocation-cap). | | **Allocation Weight** | Relative integer determining proportional share for Standard allocations. Ignored for Conditional. See [Allocations](/curators/vaults/concepts/allocations#the-weight-system). | | **AUM Fee** | Annual percentage fee on total vault assets, paid to the vault admin. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#manager-fees). | | **Autocompound Farm** | Farm that distributes rewards in the deposit token, automatically compounding into vault positions. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#farm-rewards). | | **Borrow Order** | A standing on-chain intent to borrow specific terms. One of two demand paths into a fixed-rate reserve. See [Fixed Rates → Concepts](/curators/vaults/fixed-rates/concepts#how-borrowers-take-fixed-rate-liquidity). | | **Conditional Allocation** | Allocation type that deploys capital only when borrow demand arrives. Recommended for fixed-rate reserves. See [Allocations](/curators/vaults/concepts/allocations#standard-vs-conditional). | | **Crank** | Permissionless off-chain bot that triggers on-chain state updates such as rebalancing. | | **Crank Fund Fee** | Per-deposit fee covering the cost of the invest crank. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#the-crank-fund-fee). | | **Curator** | Vault creator and manager — the admin (or multisig) controlling vault operations. | | **Deposit Token** | The token a vault accepts. Immutable per vault. | | **Direct Borrow** | An instant atomic borrow against available reserve liquidity. The other demand path alongside Borrow Orders. See [Fixed Rates → Concepts](/curators/vaults/fixed-rates/concepts#how-borrowers-take-fixed-rate-liquidity). | | **Fixed-Rate Reserve** | Lending reserve with a constant borrow rate and a fixed term (e.g. `USDC 5.5% 3M`). See [Fixed Rates](/curators/vaults/fixed-rates). | | **Floating-Rate Reserve** | Lending reserve with a utilization-based variable rate. | | **Insurance Pool** | Curator-locked capital that absorbs losses before depositors. Implemented as `FirstLossCapitalFarm`. See [Risk primitives](/curators/vaults/concepts/risk-primitives#the-insurance-pool). | | **kToken (Receipt Token)** | The vault's share token, issued to depositors. Format: `kv[DEPOSIT_SYMBOL]-[SUFFIX]`. | | **Lamports** | Smallest unit of a token (e.g. 1 SOL = 1,000,000,000 lamports). | | **Performance Fee** | Fee on vault profits, paid to the vault admin. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#manager-fees). | | **Priority** | Numerical value controlling which Standard allocations are eligible as source reserves for Conditional fills. Higher = more protected. See [Allocations](/curators/vaults/concepts/allocations#priority). | | **Reserve** | A specific lending pool within a market. Vaults allocate capital to reserves. | | **Squads** | Solana multisig used for production vault management. See [Roles & ownership](/curators/vaults/concepts/roles-and-ownership#the-squads-multisig-model). | | **Standard Allocation** | Allocation type that deploys capital immediately and continuously per weight. See [Allocations](/curators/vaults/concepts/allocations#standard-vs-conditional). | | **Sync Allocations** | Permissionless action to rebalance the vault toward target allocations. See [Allocations](/curators/vaults/concepts/allocations#sync-and-rebalance). | | **Unallocated Funds** | Idle vault capital kept liquid for instant withdrawals. See [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals#the-unallocated-buffer). | | **Vault Admin** | Full-control admin role for the vault. Production vaults transfer this to a Squads multisig. See [Roles & ownership](/curators/vaults/concepts/roles-and-ownership#the-three-admin-roles). | | **Vault Farm** | The farm where depositors stake their kTokens to receive reward distributions. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#farm-rewards). | | **Whitelisted Reserves** | Smart-contract-level constraint preventing allocation to reserves outside Kamino's verified set. See [Risk primitives](/curators/vaults/concepts/risk-primitives#whitelisted-reserves). | | **Withdrawal Penalty** | Security mechanism — fee on withdrawals returned to the vault to defeat yield-sniping. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#the-withdrawal-penalty). | | **Withdrawal Queue** | Per-reserve FIFO queue for exits when reserve liquidity is committed. See [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals#the-withdrawal-queue). | | **Withdrawal Ticket** | An entry in the withdrawal queue. Has a sequence number, a queued amount, and a destination token account. | # Vault parameters Source: https://docs.kamino.com/curators/reference/parameters Complete parameter reference for vault config, allocations, and farms Canonical reference for every parameter on a Kamino vault. For the model behind each, follow the link in the description. ## Vault-level parameters | Parameter | Type | Set at | Editable | Description | | - | - | - | - | - | | `Name` | String | Creation | Yes | Vault display name. Max 40 chars. | | `VaultAdminAuthority` | Address | Creation | Yes (2-step transfer) | Vault admin. Production vaults transfer to a Squads multisig. See [Roles & ownership](/curators/vaults/concepts/roles-and-ownership). | | `LookupTable` | Address | Creation | Yes (managed) | Address lookup table managed by the protocol. | | `Farm` | Address | Post-creation | No (immutable once set) | Vault Farm — distributes rewards to kToken holders. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#farm-rewards). | | `FirstLossCapitalFarm` | Address | Post-creation | Yes | Insurance Pool farm. See [Risk primitives](/curators/vaults/concepts/risk-primitives). | | `VaultAutocompoundFarm` | Address | Post-creation | Yes | Autocompound farm. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#farm-rewards). | | `PerformanceFeeBps` | Basis points | Creation | Yes | Fee on vault profits. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#manager-fees). | | `ManagementFeeBps` | Basis points | Creation | Yes | Annual fee on AUM. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#manager-fees). | | `MinDepositAmount` | Lamports | Creation | Yes | Minimum deposit per transaction. | | `MinWithdrawAmount` | Lamports | Creation | Yes | Minimum withdrawal per transaction. | | `MinInvestAmount` | Lamports | Creation | Yes | Minimum size for an investment instruction. | | `MinInvestDelaySlots` | Slots | Creation | Yes | Delay between two investments in a specific reserve. | | `WithdrawalPenaltyBps` | Basis points | Creation | Yes | Percentage withdrawal penalty (returned to vault). See [Yield & fees](/curators/vaults/concepts/yield-and-fees#the-withdrawal-penalty). | | `WithdrawalPenaltyLamports` | Lamports | Creation | Yes | Absolute withdrawal penalty (returned to vault). The system charges the MAX of the two. | | `CrankFundFeePerReserve` | Lamports | Post-creation | Yes | Per-reserve fee covering invest crank costs. | | `PendingVaultAdmin` | Address | During transfer | System-managed | Pending admin during a two-step transfer. | | `AllocationAdmin` | Address | Post-creation | Yes | Admin that can update weights, caps, types, and priorities only. See [Roles & ownership](/curators/vaults/concepts/roles-and-ownership#when-to-use-allocation-admin). | | `UnallocatedWeight` | Integer | Post-creation | Yes | Relative weight for the unallocated buffer. See [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals#the-unallocated-buffer). | | `UnallocatedTokensCap` | Lamports | Post-creation | Yes | Hard cap on the unallocated buffer. | | `AllowAllocationsInWhitelistedReservesOnly` | Boolean | Post-creation | One-way (`true` only) | Restrict new allocations to verified reserves. Irreversible. See [Risk primitives](/curators/vaults/concepts/risk-primitives#whitelisted-reserves). | | `AllowInvestInWhitelistedReservesOnly` | Boolean | Post-creation | One-way (`true` only) | Restrict investment to verified reserves. Irreversible. See [Risk primitives](/curators/vaults/concepts/risk-primitives#whitelisted-reserves). | ## Per-allocation parameters | Parameter | Type | Editable | Description | | - | - | - | - | | `target_allocation_weight` | Integer | Yes | Relative weight for Standard allocations. Ignored for Conditional. See [Allocations](/curators/vaults/concepts/allocations#the-weight-system). | | `allocation_cap` | Lamports | Yes | Maximum tokens deployed into this reserve. Binding limit for Conditional. See [Allocations](/curators/vaults/concepts/allocations#the-allocation-cap). | | `reserve_type` | `Standard` \| `Conditional` | Yes | Allocation behavior. See [Allocations](/curators/vaults/concepts/allocations#standard-vs-conditional). | | `priority` | Integer | Yes | Source-reserve eligibility for Conditional fills. Higher = more protected. See [Allocations](/curators/vaults/concepts/allocations#priority). | ## Farm parameters | Parameter | Type | Description | | - | - | - | | `Farm` | Address | Vault Farm address (immutable after creation). | | Farm cooldown period | Duration | Delay before stake-based rewards are claimable. Prevents deposit-claim-withdraw cycling. | | `FirstLossCapitalFarm` | Address | Insurance Pool farm. Mandatory 30-day cooldown for normal withdrawals. See [Risk primitives](/curators/vaults/concepts/risk-primitives#the-insurance-pool). | | `VaultAutocompoundFarm` | Address | Autocompound farm. Distributes rewards in the deposit token. | ## Immutable parameters These cannot be changed after vault creation: * **Deposit Token** (`tokenMint`) — the token the vault accepts. * **Receipt Token Ticker prefix** — `kv[symbol]-`. The suffix is editable. * **Farm address** — once set via farm creation. ## System-managed parameters Set by the system, not directly by curators: | Parameter | Description | | - | - | | `PendingVaultAdmin` | Set during admin transfer (step 1/2); cleared on claim or cancel. | | Farm authority | Transferred to the protocol after farm creation. | ## Related references > [card] [Glossary](/curators/reference/glossary) > > One-line definitions for every term. > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > Operational walkthrough — UI / SDK / CLI. # Allocations Source: https://docs.kamino.com/curators/vaults/concepts/allocations How vault capital is distributed across reserves — Standard vs. Conditional, weights, caps, priority, and the rebalancing model The allocation strategy is the single most important configuration on a vault. It tells the vault how much capital to deploy into each reserve and under what conditions. This page covers the model. For step-by-step setup, see [Configure allocations](/curators/vaults/guides/configure-allocations). ## What an allocation is An allocation is a configuration entry on the vault that names one reserve and specifies how the vault should treat it. Each allocation has four parameters: | Parameter | Type | Role | | - | - | - | | `target_allocation_weight` | Integer | Relative share of vault capital, used by Standard allocations | | `allocation_cap` | Token amount | Hard ceiling on tokens deployed into this reserve | | `reserve_type` | `Standard` \| `Conditional` | Allocation behavior — covered below | | `priority` | Integer | Controls source-reserve eligibility for Conditional fills | A vault holds multiple allocations. Together they define the target distribution. ## Standard vs. Conditional The allocation type governs *when* the vault deploys capital into the reserve. ### Standard Capital is deployed into the reserve immediately and continuously, sized by weight (subject to cap). This is the default behavior — it matches how lending vaults have always worked. Use Standard for floating-rate reserves where you want capital actively earning the moment it lands. ### Conditional Capital is **not** deployed at configuration time. The allocation is a *signal* — a declaration that the vault is willing to deploy up to the cap into this reserve when there's borrow demand for it. The capital stays in the vault's other Standard allocations earning yield until a borrower needs it. When demand arrives, the vault atomically pulls from a Standard allocation, deposits into the target reserve, and the borrow executes — all in one transaction. Use Conditional for fixed-rate reserves where you want to offer capacity without committing capital that might sit idle. The full FR treatment is in [Fixed Rates → Allocations](/curators/vaults/fixed-rates/allocations). ### Comparison | Aspect | Standard | Conditional | | - | - | - | | Behavior | Capital deployed per weight, immediately | Capital signalled, deployed atomically when demand arrives | | Weight handling | Weight determines share | Weight ignored; only cap matters | | Liquidity in the reserve | Visible immediately | Invisible until a fill triggers | | Opportunity cost | Earns whatever the reserve yields (zero if no borrower) | Zero — capital earns floating yield until matched | | Best for | Floating-rate reserves | Fixed-rate reserves | | Default priority | Normal | Higher priority (on-demand fill) | You can mix both on the same reserve — a Standard base layer of visible liquidity with Conditional capacity behind it. ## The weight system Standard allocations use **relative integer weights**, not percentages. A reserve's share of vault capital is its weight divided by the total weight of all Standard allocations plus the unallocated weight. ``` reserve allocation % = (reserve_weight / total_weight) × 100 total_weight = sum(standard_allocation_weights) + unallocated_weight ``` **Example:** | Reserve | Weight | Share | | - | - | - | | SOL/BTC Market USDC | 500 | 50% | | JLP Market USDC | 300 | 30% | | Altcoin Market USDC | 200 | 20% | | **Total** | **1,000** | **100%** | Weights are integer-only; they are meaningful only relative to each other. Weights of `100/300/600` and `1/3/6` give identical distributions. Conditional allocations have weights but **the weight is ignored**. The cap is the binding limit. ## The allocation cap The cap is a hard ceiling on the amount of tokens the vault will deploy into a single reserve, independent of weight. If the weight implies more than the cap, allocation stops at the cap and excess flows to other allocations per their weights. **Example:** * Reserve weight: 500 (50% of total weight 1,000) * Vault size: 1M USDC * Cap: 200K USDC * **Result:** 200K allocated. The remaining 300K (the weight-implied excess) redistributes across the other allocations. Use caps for risk control — bound exposure to any single reserve or market. For Conditional allocations, the cap is the **only** binding limit (since weight is ignored). To set or change weight and cap on any allocation, see [Configure allocations](/curators/vaults/guides/configure-allocations). ## Priority Priority controls which Standard allocations are eligible as source reserves when a Conditional fill executes. **The rule:** capital flows into a Conditional allocation only from Standard allocations whose priority is **less than or equal to** the Conditional reserve's priority. Higher priority number = more protected. All allocations default to priority `0`. To carve out a Standard allocation that should never be drawn down by Conditional fills, give it a priority above the Conditional allocation's priority. **Example:** | Allocation | Type | Priority | Eligible as source for the Conditional fill? | | - | - | - | - | | SOL/BTC Market USDC | Standard | 0 | Yes (0 ≤ Conditional's 0) | | JLP Market USDC | Standard | 0 | Yes | | Altcoin Market USDC | Standard | 2 | No (2 > Conditional's 0) | | SOL/BTC Market USDC 5% 3M | Conditional | 0 | — (this is the destination) | The Altcoin allocation is protected. The Main and JLP allocations are eligible sources. Set priority on any allocation via [Configure allocations](/curators/vaults/guides/configure-allocations). > [!WARNING] > > **Why priority exists.** Conditional reserves can in principle be manipulated — an attacker can open and close a withdrawal ticket in the same transaction to trigger source-reserve draw-down without any real borrower demand. Priority is the mitigation. Set priority above the Conditional reserve's priority on any source you want protected from this vector. ## Unallocated funds (the liquidity buffer) Not every dollar in the vault should be deployed into reserves. The vault holds an **unallocated buffer** — capital that sits idle, available to service withdrawals without triggering reserve rebalancing. | Parameter | Type | Description | | - | - | - | | `UnallocatedWeight` | Integer | Relative weight for unallocated funds; participates in total weight | | `UnallocatedTokensCap` | Token amount | Hard cap on the unallocated amount | **Example:** * Total vault: 10M USDC * `UnallocatedWeight`: 80 (8% of total weight 1,000) * `UnallocatedTokensCap`: 2M USDC * **Result:** Target 800K unallocated. If vault grows and 8% would exceed 2M, capped at 2M. The buffer trades yield for instant liquidity. A higher buffer means depositors can withdraw without queuing; a lower buffer means more capital is earning. Adjust the buffer at [Configure allocations](/curators/vaults/guides/configure-allocations); see [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals) for how the buffer interacts with the withdrawal queue. ## Sync and rebalance Allocations are **targets**, not absolute state. The actual allocation drifts from target as deposits land, withdrawals leave, interest accrues, and Conditional fills move capital. A **sync** brings the vault back into alignment. * **Permissionless.** Anyone can call sync; it's not a privileged operation. * **Automatic.** A bot runs sync every \~15 minutes across all vaults. * **Manual.** You can trigger sync immediately when needed (e.g. just after changing allocations) — see [Configure allocations → Sync after changes](/curators/vaults/guides/configure-allocations#sync-after-changes). * **Best-effort.** Sync may not reach the exact target distribution if the source reserve has insufficient available liquidity to deallocate from. * **Capped invest.** `invest_with_max_amount` is an `invest` variant: weights and allocation caps still determine whether funds move into or out of the reserve, but the caller can cap the amount moved toward that target. This allows partial fund movement in the target direction when the full rebalance amount is not currently available. Sync is also what executes Conditional fills when borrow demand arrives — though those fills also happen atomically inside the borrowing transaction, not just on the sync cadence. ## What an allocation can't do A few constraints worth knowing: * The deposit token is set at vault creation and is immutable. You can only allocate to reserves that match this token. * Removing an allocation doesn't necessarily move the capital out immediately — if the underlying reserve is illiquid, the deallocation queues through the withdrawal queue. * You can't allocate to a reserve that isn't whitelisted if [Whitelisted Reserves](/curators/vaults/concepts/risk-primitives) is enabled. ## What's next > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > Add, edit, and remove reserve allocations via UI, SDK, or CLI. > [card] [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals) > > The buffer, instant withdrawals, and the queue. > [card] [Fixed Rates → Allocations](/curators/vaults/fixed-rates/allocations) > > The FR-specific application of Conditional allocation. > [card] [Parameters](/curators/reference/parameters) > > Full parameter reference. # How vaults work Source: https://docs.kamino.com/curators/vaults/concepts/how-vaults-work The vault primitive: share tokens, allocation, the depositor flow, and the curator's role A Kamino Vault is a programmable lending position. As a curator, you deploy a vault for a single deposit token, configure how that capital should be distributed across Kamino lending reserves, and issue share tokens to depositors who deposit into your vault. The vault is the layer between the depositor (who wants yield) and the underlying reserves (where yield is generated). This page is the conceptual foundation. Read it before any of the operational guides. ## The model A vault sits between depositors and Kamino lending reserves. A depositor deposits the vault's accepted token (e.g. USDC) and receives the vault's kToken (e.g. `kvUSDC-X`) in exchange. The vault holds the deposited capital and routes it across a curator-defined mix of Kamino lending reserves — SOL/BTC Market USDC, JLP Market USDC, fixed-rate reserves, and so on — where borrowers pay interest. Yield flows back from the reserves into the vault and accrues to the kToken's exchange rate, so the same kToken redeems for more of the deposit token over time. Three layers, three responsibilities: * **The depositor** holds the vault's kToken (`kvUSDC-X` in this example). The kToken's exchange rate against the deposit token rises as the vault accrues yield. Depositors do not pick reserves; they trust the curator's allocation. * **The vault** routes capital across reserves according to the curator's target allocation, charges the configured fees, and runs an automatic rebalancing loop. * **The reserves** are the underlying lending pools where the actual borrowing and repayment happen. The vault holds cTokens of each reserve it's allocated to. ## Share tokens (kTokens) When a depositor deposits into your vault, they receive a share token (kToken) sized at the current exchange rate. As the vault accrues yield, the kToken's exchange rate against the deposit token rises — so the same kToken redeems for more deposit tokens later than it would at deposit time. There is no rebasing; the share count is stable. ``` shares minted = deposit_amount / current_exchange_rate ``` The kToken's symbol follows the convention `kv[DEPOSIT_SYMBOL]-[SUFFIX]` (e.g. `kvUSDC-mev`). The prefix and the deposit token are immutable at vault creation; the suffix is set by you. ## Allocation Every vault has an **allocation strategy** — the configuration that tells the vault how to deploy capital across reserves. An allocation has, per reserve: * A **type** — Standard (always allocated) or Conditional (allocated only when borrow demand arrives) * A **weight** — relative integer that determines proportional distribution for Standard allocations * A **cap** — hard ceiling on tokens deployed into this reserve * A **priority** — controls source-reserve eligibility for Conditional fills The full mechanics live in [Concepts → Allocations](/curators/vaults/concepts/allocations); for the workflow, [Configure allocations](/curators/vaults/guides/configure-allocations). ## Rebalancing and the crank Allocations are *targets*, not absolute state. As deposits, withdrawals, interest accrual, and Conditional fills shift the actual allocation away from the target, a permissionless **crank** brings the vault back into alignment. A bot runs this every \~15 minutes; anyone (including you) can trigger it manually. You don't manage individual deposits or withdrawals into reserves. You set targets; the crank executes. ## Fees and revenue You earn revenue from the vault through two manager fees configured at vault setup (both editable): * **Performance fee** — a percentage of vault profits * **AUM fee** — an annual percentage on total vault assets Both accrue continuously in the deposit token and are collected when you call the appropriate instruction. See [Concepts → Yield & fees](/curators/vaults/concepts/yield-and-fees) for the full model; fees are set during [vault creation](/curators/vaults/guides/create-a-vault). ## Liquidity and withdrawals Depositors can withdraw at any time. The vault attempts an instant withdrawal first (from the unallocated buffer plus any reserve liquidity it can pull from); if that's insufficient — which happens when capital is committed to fixed-rate reserves or when reserves are heavily utilized — the remaining amount queues through the **withdrawal queue**, a per-reserve FIFO that fills as borrowers repay or new deposits arrive. The withdrawal queue is a primitive worth understanding deeply — it's the exit path for any capital that isn't instantly available. See [Concepts → Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals); to size the unallocated buffer that absorbs normal withdrawals, see [Configure allocations](/curators/vaults/guides/configure-allocations). ## Roles and ownership A vault has three admin roles: * **Vault Admin** — full control over settings, allocations, fees. Production vaults transfer this to a Squads multisig. * **Allocation Admin** — limited role that can update weights, caps, types, and priorities on existing allocations only. Useful for delegating day-to-day rebalancing. * **Farm Authority** — controls the vault's farm. After farm creation, this transfers to the protocol; you do not manage it. Production vaults run under a multisig. Once you transfer admin, every operation flows through Squads as a proposal. See [Concepts → Roles & ownership](/curators/vaults/concepts/roles-and-ownership) for the model and [Transfer admin to multisig](/curators/vaults/guides/transfer-admin) for the migration steps. ## Risk primitives Two on-chain mechanisms communicate trust to depositors: * **The Insurance Pool** — your own capital, locked in the vault, that absorbs losses before any depositor takes a hit. Kamino matches up to \$250K. This is the strongest signal you can offer. Configure via [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool). * **Whitelisted Reserves** — a smart-contract-level constraint that prevents the vault from allocating to reserves outside a protocol-verified set. Required for your vault to appear on Kamino's UI. Configure via [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves). See [Concepts → Risk primitives](/curators/vaults/concepts/risk-primitives) for the model. ## What you actually do A typical curator workflow: 1. **Create the vault** — set deposit token, fees, operational parameters. ([Guide](/curators/vaults/guides/create-a-vault)) 2. **Configure initial allocations** — pick reserves, set weights and caps. ([Guide](/curators/vaults/guides/configure-allocations)) 3. **Set up risk primitives** — Insurance Pool, Whitelisted Reserves. ([Guides](/curators/vaults/guides/set-up-insurance-pool)) 4. **Configure farms** — for reward distribution and autocompounding. ([Guide](/curators/vaults/guides/configure-farms)) 5. **Transfer admin to multisig** — for production. ([Guide](/curators/vaults/guides/transfer-admin)) 6. **Operate** — adjust allocations, monitor APY, collect fees, react to market conditions. If your strategy includes fixed-rate reserves, see [Fixed Rates](/curators/vaults/fixed-rates) for the full FR-specific treatment. ## What's next > [card] [Allocations](/curators/vaults/concepts/allocations) > > The allocation primitive in depth. > [card] [Create a vault](/curators/vaults/guides/create-a-vault) > > Skip to the workflow. # Liquidity & withdrawals Source: https://docs.kamino.com/curators/vaults/concepts/liquidity-and-withdrawals The unallocated buffer, instant withdrawals, and the withdrawal queue — how depositor exits actually work A vault depositor can request a withdrawal at any time. Whether that withdrawal completes immediately or has to wait depends on where the vault's capital is and how it can be unwound. This page is the model — the buffer that absorbs normal withdrawals, the rules that govern instant exits, and the **withdrawal queue** primitive that handles everything else. ## The three liquidity layers When a depositor redeems shares, the vault tries to satisfy the request from three sources, in order: 1. **Unallocated buffer** — capital sitting idle in the vault, immediately available. 2. **Standard allocations** — capital deployed into reserves that have free liquidity (i.e. not all borrowed). The vault can pull what's available. 3. **The withdrawal queue** — for any portion that can't be served instantly. This is the exit path for capital locked in fixed-rate reserves or fully-utilized reserves. If layers 1 + 2 cover the redemption in full, the depositor exits in a single transaction. If they don't, the vault redeems the available portion immediately and queues the rest. ## The unallocated buffer The buffer is the simplest layer: capital that's intentionally not deployed. The vault holds it as the deposit token, available for any withdrawal request. The size is governed by two parameters: | Parameter | Effect | | - | - | | `UnallocatedWeight` | Relative weight for unallocated funds; participates in the total weight calculation alongside reserve allocations | | `UnallocatedTokensCap` | Hard cap on the buffer regardless of weight | A typical vault holds 5–10% of total assets in the buffer. Higher buffer means more depositors exit instantly, but more capital sits unproductive. Lower buffer means more capital earning yield, but more redemptions queue. You set `UnallocatedWeight` and `UnallocatedTokensCap` as part of allocations — see [Concepts → Allocations](/curators/vaults/concepts/allocations#unallocated-funds-the-liquidity-buffer) for the model and [Configure allocations](/curators/vaults/guides/configure-allocations) for the workflow. ## Instant withdrawals When the vault can satisfy the redemption from buffer + reserve liquidity, the user gets the deposit token in one transaction. The vault: 1. Burns the redeeming shares from the user. 2. Pulls from the unallocated buffer first. 3. If still short, redeems cTokens from Standard allocations against reserves with free liquidity. 4. Charges the configured withdrawal penalty (returns to vault). 5. Sends the deposit tokens to the user. A few constraints govern whether step 3 succeeds: * **Reserve utilization.** The vault can only pull from a reserve to the extent the reserve has uncommitted capital. A 100% utilized reserve has nothing to redeem. * **Withdrawal penalty floor.** If the available portion is below the configured `WithdrawalPenaltyLamports`, the withdraw leg reverts. The fix in this case is to skip the instant leg entirely and enqueue the full amount (the SDK exposes `skipWithdrawLeg` for this). The penalty itself is set at vault creation — see [Create a vault](/curators/vaults/guides/create-a-vault) and [Yield & fees → The withdrawal penalty](/curators/vaults/concepts/yield-and-fees#the-withdrawal-penalty). * **Conditional allocations don't help here.** Capital "in" a Conditional allocation is actually still in the underlying floating reserve — so it counts toward instant capacity. But once a Conditional allocation has been *filled* (committed to a fixed-rate reserve), that capital is locked for the loan term. ## The withdrawal queue When part or all of a redemption can't be served instantly, the remainder enters the **withdrawal queue**. The queue is a per-reserve FIFO that fills automatically as capital re-enters the reserve. This is a fundamental Kamino primitive. It's used for vault depositor redemptions (the [Private Credit V2 redemption flow](/products/institutional-yield) is built on it) and for curator-side exits from fixed-rate reserve allocations. Both consume the same machinery. ### How it works Each reserve maintains its own FIFO queue. When a withdrawal can't be served instantly: 1. The vault calls `enqueue_to_withdraw` on the relevant reserve, submitting a **withdrawal ticket** with a sequence number. 2. The ticket waits at its position in the queue. 3. As liquidity returns to the reserve (from any source — see below), the head ticket fills first. If the available liquidity covers the head ticket fully, the queue advances. If it's a partial fill, the head ticket stays at position 0 with the remainder. 4. When the user's ticket fully fills, the deposit tokens are delivered to their destination token account. The queue is **strict FIFO**. The head ticket is determined by the reserve's `next_withdrawable_ticket_sequence_number`, enforced by the on-chain PDA seed. You cannot skip ahead. ### What feeds the queue Three on-chain events return liquidity to a reserve: | Source | Trigger | | - | - | | **Borrower repayments** | Any repay — early (with penalty if applicable), at maturity, or via a rollover that lands in a different reserve | | **New deposits** | Standard-allocation deposits from another vault, retail supply if the reserve allows it, or rebalance settlements | | **Liquidations** | Both regular collateral-health liquidations and protocol-enforced liquidations (term-breach, maturity-breach for fixed-rate reserves) | When any of these lands, a permissionless **WQP bot** (Withdraw Queue Progress) calls `withdraw_queued_liquidity` against the head ticket. Anyone can run their own bot; in practice Kamino's runs reliably. ### What the queue takes precedence over The design rule is: **lender exit takes precedence over borrower stay-in or new entry.** Concretely: * A queued ticket **blocks rollover** for every borrower in that reserve. Borrowers at maturity must repay; they cannot extend. * Tickets are filled before any new borrow-order fill takes liquidity. * Tickets are filled before any regular borrow draws available capital. * Tickets are filled before fee accrual claims would settle. This is why a queued ticket mid-term is a *forcing function*: it doesn't return capital immediately, but it guarantees capital returns at the next maturity wave. ### Lifecycle of a ticket ``` [ submit ] enqueue_to_withdraw ↓ [ queued ] waiting for liquidity, sequence_number assigned ↓ [ partial fill ] (optional) withdraw_queued_liquidity, head only ↓ [ fully filled ] OR [ cancelled ] withdraw_queued_liquidity (final) | cancel_withdraw_ticket ``` Operational rules: * **No notice period.** Tickets take effect immediately. Queue when you decide to. * **Cancellation is free.** Tickets can be cancelled any time before they fully fill. Speculative queue submissions cost nothing if you change your mind. * **Recovery for invalid tickets.** If a ticket's destination token account becomes invalid mid-queue (frozen, delegated, wrong mint), the protocol marks the ticket invalid and the head advances past it. The owner calls `recover_invalid_ticket_collateral` to retrieve their cTokens. ## Two integration paths Vaults expose the queue through two distinct flows. Both are available in the SDK. ### Vault depositor redemption (`withdrawRedeemAndEnqueueIxs`) The orchestrator helper for end users redeeming vault shares. Sends up to three sequential transactions: 1. **Withdraw** — pull whatever instant liquidity exists (buffer + redeemable reserve liquidity) and send to the user. 2. **Redeem-in-kind** — exchange the user's remaining shares for cTokens of the underlying reserves, proportional to vault exposure. 3. **Enqueue** — submit those cTokens as withdrawal tickets against each reserve. The user gets a partial fill now and a queued position for the rest. As tickets fill, the deposit token lands in their destination account. This is the path Private Credit V2 uses — its vaults are typically near 100% utilized, so almost every redemption goes through the queue. ### Curator-side disinvestment A curator wanting to **reduce or remove** a Standard allocation to a high-utilization reserve (especially a fixed-rate reserve) faces the same constraint: the capital is locked. The vault submits a withdrawal ticket against the reserve. As liquidity returns, the ticket fills and the cTokens land back in the vault, where the rebalancer redeploys them per current target weights. To trigger a disinvestment from a high-utilization reserve, lower the allocation's weight or cap via [Configure allocations](/curators/vaults/guides/configure-allocations). For the FR-specific view of the same flow, see [Fixed Rates → Lifecycle → Exiting via the withdrawal queue](/curators/vaults/fixed-rates/lifecycle#exiting-via-the-withdrawal-queue). ## Strategic implications The queue isn't just an exit mechanism — once you understand its dynamics, it's a position-management lever: * **Queue depth as a demand signal.** A reserve with deep queued tickets is one where any returning liquidity is already spoken for. Adding new allocation there means going to the back of the line. * **Queue early as a forcing function.** If you know you want out by a given date, queue ahead. The ticket sits cheaply (cancellable for free) and locks in priority for the next repayment cycle. * **Cancel and resubmit are free.** Manage your queue position responsively. * **Available liquidity ≠ borrowable liquidity.** A reserve's nominal `available_liquidity` is gross; what's actually available for a *new* borrow is `available_liquidity − queued_amount`. Both numbers matter. ## Required market flags The queue is gated by three market-level flags. A market needs all three set for the full lifecycle: | Flag | Required for | | - | - | | `withdraw_ticket_issuance_enabled` | Submitting tickets via `enqueue_to_withdraw` | | `withdraw_ticket_redemption_enabled` | Filling tickets via `withdraw_queued_liquidity` | | `withdraw_ticket_cancellation_enabled` | Cancelling tickets | Plus `min_withdraw_queued_liquidity_value` (default `2`), the anti-dust floor for new tickets and partial-fill remainders. These are set by market managers — see [Markets → Fixed Rates → Market Settings](/curators/markets/fixed-rates/market-settings). ## Edge cases worth knowing * **Dust progress stalls.** If a head ticket's remainder falls below `min_withdraw_queued_liquidity_value`, the WQP bot won't fill it. The ticket stays head-of-queue until enough new liquidity arrives to clear the threshold in one shot. * **Same-tx open-and-close prevention.** A ticket opened and closed in the same transaction is detected and rejected. This protects the [allocation priority system](/curators/vaults/concepts/allocations#priority) from being exploited. * **Vault-owned tickets need callback support.** When a vault submits a ticket against a reserve, the on-chain `progress_callback_type` is set so vault accounting stays in sync as the ticket fills. Older kvault versions don't support this; ensure your vault is on a recent release. * **The vault `invest` operation does not auto-queue.** If you decrease a Standard allocation's weight on a fully-utilised reserve, the rebalancer won't automatically submit a withdrawal ticket — you trigger it explicitly. ## What's next > [card] [Allocations](/curators/vaults/concepts/allocations) > > The allocation primitive, including the unallocated buffer. > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > Operational walkthrough — adjust the unallocated buffer, increase/decrease allocations to trigger queued exits. > [card] [Fixed Rates → Lifecycle](/curators/vaults/fixed-rates/lifecycle) > > The FR-specific operational treatment of exits, including the rollover-blocking rule and queue-as-strategy. # Permissioned vaults Source: https://docs.kamino.com/curators/vaults/concepts/permissioned-vaults Gate vault deposits behind a per-user, per-action allowlist enforced on-chain by the kperm program A permissioned vault gates on-chain deposit actions behind an explicit per-user allowlist. A wallet without an allowlist entry is rejected by the program at deposit time. The curator picks which actions are gated and which users are allowed to take them; everything else stays open. The on-chain enforcement is handled by a separate program called **kperm**, the same primitive that powers [permissioned markets](/curators/markets/permissioned-markets). For the operational walkthrough — switching a vault into permissioned mode and managing the allowlist — see [Enable permissioning](/curators/vaults/guides/enable-permissioning). > [!NOTE] > > kperm is live for Kamino lending markets today. Vault-side support ships with the next kvault release; the SDK, CLI, and on-chain mechanics described here mirror the existing markets implementation. ## When to use this * **KYC'd-only depositor base** — tie KYC completion to a wallet, then automate whitelisting via the API * **Accredited-investor restrictions** — same pattern, gated by attestation * **App-internal vault for a specific app's users** — your app's onboarding flow is the gate * **Counterparty-gated lending vaults** — vault deposits restricted to named institutional entities under bilateral agreements ## How it works Permissioning is enforced by a **cosigner pattern**. Every gated action on a permissioned vault requires two on-chain signatures: the user's, plus a co-signature from a kperm-controlled PDA called the **Vault Permissioner**. kvault will only execute the action if both are present. The mechanic has two on-chain pieces. The **vault** holds two new fields. `permissioning_authority` is a pubkey that kvault treats as a required co-signer on every gated action; the curator sets it to the kperm-derived **Vault Permissioner PDA** (seeds: `["vault", vault_address]`). `permissioned_ops` is a `u64` bitfield naming which actions on this vault are gated. Setting these two fields is what turns a vault into a permissioned vault. The **kperm program** holds the per-user allowlist. For each (vault, user) pair authorized to take gated actions, kperm stores a `UserPermission` account at PDA `["permission", vault, user]` recording which operations that user can take. When a user takes a gated action, their wallet does not call kvault directly. It builds the kvault instruction it wants to execute, then wraps it inside `kperm.permissioned_fwd_to_kvault(ix_data)` and submits the wrap. kperm reads the user's `UserPermission`, confirms the requested action is in the allowlist, and CPIs into kvault with its Vault Permissioner PDA acting as the co-signer. kvault sees the required co-signer present and executes the wrapped instruction. If the user has no `UserPermission` or the requested action is missing from the bitfield, kperm rejects and the entire transaction reverts. For ungated actions on the same vault — actions whose bit is clear in `permissioned_ops`, plus withdraw, refresh, and read paths — users call kvault directly. Only the gated operations require the wrap. ## The operations The kperm bitfield exposes two operation slots that apply to vaults: | Bit | Op | Notes | | - | - | - | | 0 | `DEPOSIT` | Gates depositing into the vault | | 5 | `KEYRING` | External-policy bridge. Use this when a user's actions should be enforced by a separate keyring/policy program (the kperm allowlist still applies as a fallback) | A user's `UserPermission.permissioned_ops` is the bitwise OR of the bits they're allowed to act on. The remaining slots in the kperm bitfield (`BORROW`, `LIQUIDATE`) are market-level operations and have no kvault-side enforcement target. They share the same `u64` encoding for forward-compatibility with markets. **Withdrawals stay open.** The bitfield governs entry only — once a user has been allowed to deposit, they can always redeem their shares subject to the vault's standard liquidity model. The design screens capital at entry only. ## How it composes with other vault primitives Permissioned vaults compose with the rest of the vault primitive surface: * **[Whitelisted Reserves](/curators/vaults/concepts/risk-primitives#whitelisted-reserves)** — protocol-level constraint on which reserves the vault can deploy capital into. Permissioning gates *who* can deposit; Whitelisted Reserves gates *where* capital flows. Running a permissioned vault that also enforces Whitelisted Reserves is the strongest configuration for institutional capital. * **[Insurance Pool](/curators/vaults/concepts/risk-primitives#the-insurance-pool)** — the loss backstop is unaffected by permissioning. Whitelisted depositors get the same loss-waterfall protection as depositors in any other vault. * **[Standard / Conditional allocations](/curators/vaults/concepts/allocations)** — allocation strategy is independent of who's allowed to deposit. A permissioned vault can run any combination of floating-rate and fixed-rate allocations. * **[Multisig admin](/curators/vaults/concepts/roles-and-ownership)** — switching the vault into permissioned mode and updating `permissioned_ops` are admin actions. Under a Squads multisig, both flow through the standard proposal model. ## Comparison to markets The vault and market flavors of kperm share the same primitive — kperm cosigner pattern, same `UserPermission` account layout, same `KEYRING` external-policy bridge — and differ only in the target program and the operation surface. A market gates `DEPOSIT | BORROW | LIQUIDATE`; a vault gates `DEPOSIT`. Curators running both products manage them through the same SDK module and the same global admin. ## What's next > [card] [Enable permissioning](/curators/vaults/guides/enable-permissioning) > > The operational walkthrough — switch the vault into permissioned mode, whitelist users, and integrate the API. > [card] [Permissioned markets](/curators/markets/permissioned-markets) > > The same primitive applied to lending markets. # Risk primitives Source: https://docs.kamino.com/curators/vaults/concepts/risk-primitives The Insurance Pool and Whitelisted Reserves — the two on-chain protections you offer depositors A Kamino vault has two protocol-level mechanisms for communicating trust to depositors. Together they answer two distinct questions: * **What if something goes wrong?** → the **Insurance Pool**, your locked capital that absorbs losses before depositors take a hit. * **Where can capital go?** → **Whitelisted Reserves**, a smart-contract-level constraint that prevents the vault from allocating to unverified reserves. Both are configurable but become irreversible once enabled. Together they represent the highest trust configuration for a vault. Both are required for your vault to appear on Kamino's UI. ## The Insurance Pool The Insurance Pool is your own capital, locked into the vault, that acts as a **loss backstop**. If the vault incurs bad debt and losses are socialized, your locked capital is used to compensate affected depositors before depositors bear any loss themselves. The Insurance Pool is the strongest trust signal you can offer depositors. It puts your capital first in the loss waterfall, with public on-chain visibility of the amount. ### Mechanics * **You deposit** into a dedicated farm on your vault. Your capital earns yield in line with the vault's APY — your backstop is productive while it's locked. ([Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool)) * **Kamino matches** your deposit up to **\$250K**. If you deposit \$200K, Kamino contributes an additional \$200K, bringing your vault's Insurance Pool to \$400K. Deposits above \$250K are not matched. * **Withdrawals have a mandatory 30-day cooldown.** Initiating a withdrawal is a public on-chain signal — depositors and anyone monitoring the vault see that you're exiting. ([Withdrawal mechanisms](/curators/vaults/guides/set-up-insurance-pool#withdrawal-mechanisms)) * **Emergency withdrawal** bypasses the 30-day cooldown but requires a 2-of-2 multisig (your wallet + Kamino's security council). Designed exclusively for releasing funds to compensate depositors after a loss event. ([Withdrawal mechanisms](/curators/vaults/guides/set-up-insurance-pool#withdrawal-mechanisms)) > [!NOTE] > > The Insurance Pool is implemented on-chain as the vault's `FirstLossCapitalFarm`. You'll see the engineering name in some contexts (parameter tables, SDK method names). The depositor-facing name is **Insurance Pool**; that's the term used throughout this section. ### The loss waterfall When a vault incurs bad debt, the Insurance Pool absorbs the loss first, up to its full balance. If the pool covers the full bad-debt amount, depositors are made whole. If the loss exceeds the pool's balance, depositors absorb the residual. A vault with a healthy Insurance Pool is one where the curator's own capital is at risk first. Depositor confidence flows from this, not from any external guarantee. ### Loss compensation is manual There is no automated on-chain loss detection. When a vault incurs bad debt, Kamino socialises the loss on-chain (via `socialize_loss` on klend), then a manual process — coordinated between you and Kamino — releases Insurance Pool funds and distributes them to a snapshot of affected depositors. The full step-by-step is in [Set up the Insurance Pool → Loss compensation flow](/curators/vaults/guides/set-up-insurance-pool#the-loss-compensation-flow). > [!WARNING] > > The Insurance Pool's emergency withdrawal exists to compensate depositors. Using it to extract your capital and avoid making depositors whole defeats the mechanism's purpose and constitutes a breach of the curator commitment. ## Whitelisted Reserves Whitelisted Reserves is a **smart-contract-level** restriction that ensures your vault's capital can only flow into reserves that Kamino has explicitly verified. Even a compromised admin key cannot direct vault funds into unvetted markets. This is **protocol-level security**, not operational security. The constraint is enforced by the smart contract itself, independent of your key management or multisig configuration. ### The two flags There are two independent on-chain restrictions. Both must be enabled for your vault to appear on Kamino's UI. | Flag | What it restricts | | - | - | | `AllowAllocationsInWhitelistedReservesOnly` | **Allocation control.** You cannot create or increase allocations to any reserve outside the whitelist. Existing allocations can still be edited or removed. | | `AllowInvestInWhitelistedReservesOnly` | **Investment control.** Depositor funds cannot flow into any unvetted reserve. Stricter than allocation control — prevents any *investment* into unverified reserves, not just *allocation creation*. | Enabling both is the recommended configuration. `AllowAllocationsInWhitelistedReservesOnly` alone allows investment into previously-added non-whitelisted reserves, leaving a path the second flag closes. See [Enable Whitelisted Reserves → The two flags](/curators/vaults/guides/enable-whitelisted-reserves#the-two-flags) for the activation walkthrough. ### Irreversibility > [!WARNING] > > Both flags are **one-way**. Once set to `true`, they cannot be reverted — enforced at the smart contract level. This is intentional: it prevents a compromised key or malicious actor from reversing the protection. Be deliberate. Withdrawals are always permitted regardless of whitelist status. You can de-allocate from any reserve at any time, and depositors can enter or exit the vault at any time subject to available liquidity. ### Whitelist management Kamino maintains the whitelist at the protocol level. Curators can activate the enforcement flags on their vault and manage allocations within the resulting set, but have no control over which reserves are on the whitelist. For the configuration walkthrough, see [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves). ## How they compose The two primitives protect different things: * **Whitelisted Reserves** protects against where capital goes — the *what-could-happen* surface. * **Insurance Pool** protects against what happens if something goes wrong — the *what-actually-happened* surface. Together they represent the highest trust configuration for a vault. Run both for any vault accepting institutional capital. ## What's next > [card] [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) > > Walkthrough for configuring the loss backstop. > [card] [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) > > Walkthrough for enabling the smart-contract-level restriction. # Roles & ownership Source: https://docs.kamino.com/curators/vaults/concepts/roles-and-ownership Vault admin types, the multisig model, and the Squads-based execution flow A production vault runs under a Squads multisig — every state-changing operation flows through proposals and approvals. This page explains the admin roles, the transfer model, and how operations actually execute once the multisig holds admin. ## The three admin roles | Role | Scope | Transfer model | | - | - | - | | **Vault Admin** | Full control over settings, allocations, fees, and all parameters | Two-step (initiate → claim) | | **Allocation Admin** | Update allocation **weights, caps, types, and priorities** on existing reserves only. Cannot add or remove reserves; cannot change vault settings. | Single-step (Vault Admin sets directly) | | **Farm Authority** | Controls the vault's farm. Transferred to the protocol after farm creation; not curator-managed thereafter. | Automatic | ### When to use Allocation Admin Allocation Admin is the role you delegate to a non-multisig wallet (or a different multisig) to handle day-to-day rebalancing without granting full vault control. Common patterns: * An automated rebalancing service holds Allocation Admin while the Vault Admin remains a high-security multisig. * A secondary operator manages weights between scheduled rebalances; the primary multisig retains structural control. * Risk management software adjusts caps in response to market signals. The Allocation Admin cannot add new reserves to the allocation or change fee structure — those still require the Vault Admin. To set or rotate the Allocation Admin, see [Transfer admin to multisig → Allocation Admin transfer](/curators/vaults/guides/transfer-admin#allocation-admin-transfer-optional). ## The two-step Vault Admin transfer Vault Admin transfer uses a two-step pattern to prevent accidental ownership changes. ``` [ current admin ] initiate transfer [ pending admin set ] claim [ new admin holds vault ] ● ─────────────────────────────► ● ──────► ● │ │ current admin can cancel here ▼ [ unchanged ] ``` 1. **Initiate.** The current admin submits a transfer to the new admin address. The vault state's `PendingVaultAdmin` is set to the new admin. The new admin does not yet hold control. 2. **Claim.** The new admin (typically a Squads multisig) submits an accept-ownership transaction. Control transfers atomically. Until step 2 lands, the current admin can cancel the pending transfer. After step 2, the previous admin has no privileges. The Allocation Admin transfer is **single-step** — the Vault Admin sets the new Allocation Admin directly. There is no claim. This is intentional: you may want to revoke or rotate Allocation Admin quickly without coordination from the new admin. For step-by-step transfer instructions, see [Transfer admin to multisig](/curators/vaults/guides/transfer-admin). ## The Squads multisig model Production vaults transfer Vault Admin to a [Squads](https://squads.so) multisig before accepting deposits. Two reasons: * **Operational security.** No single key can move vault funds. * **Required for UI listing.** Kamino's UI lists only multisig-controlled vaults that also have [Whitelisted Reserves](/curators/vaults/concepts/risk-primitives#whitelisted-reserves) enabled — see [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves). Once the multisig holds Vault Admin, every state-changing operation becomes a Squads proposal that requires the configured threshold of signatures. To migrate, see [Transfer admin to multisig](/curators/vaults/guides/transfer-admin). ## How operations execute under multisig Two flows are supported. Both produce the same on-chain outcome. For the workflow walkthrough, see [Transfer admin to multisig → Operating after transfer](/curators/vaults/guides/transfer-admin#operating-after-transfer). ### SquadsX flow (recommended) When you sign in to [kamino.com/curators/vaults](https://kamino.com/curators/vaults) with SquadsX, the Send action automatically: 1. Generates the transaction. 2. Creates a Squads proposal. 3. Surfaces it to the multisig members for approval. You don't copy or paste anything — the proposal lands in the Squads dashboard ready for review and execution. ### Encoded transaction flow If you're not using SquadsX: 1. Configure the change on `kamino.com/curators/vaults`. 2. Click Simulate to verify the transaction succeeds and review the resulting state. 3. Copy the Base58-encoded transaction string from the simulation output. 4. Open [Squads](https://squads.so) and import the encoded transaction. 5. Gather approvals. 6. Execute. The same flow applies to programmatic operations via SDK or CLI. SDK methods produce instructions that are wrapped into transactions; CLI commands accept `--mode multisig --multisig ` to emit a Base58-encoded payload for Squads. ## Authority transfer for emergency operations The Insurance Pool's emergency withdrawal uses a **2-of-2 multisig** that's separate from your vault Squads: * One signature from your curator-controlled wallet. * One signature from Kamino's security council. This applies only to emergency withdrawals from the Insurance Pool — see [Risk primitives → Insurance Pool](/curators/vaults/concepts/risk-primitives#the-insurance-pool) and [Set up the Insurance Pool → Withdrawal mechanisms](/curators/vaults/guides/set-up-insurance-pool#withdrawal-mechanisms). Normal vault operations use only your Squads multisig. ## What a curator actually manages In practice, the role split for a typical institutional vault: | Operation | Authority | Workflow | | - | - | - | | Adjust allocation weights/caps (existing reserves) | Vault Admin or Allocation Admin | [Configure allocations](/curators/vaults/guides/configure-allocations) | | Add a new reserve to the allocation | Vault Admin only | [Configure allocations](/curators/vaults/guides/configure-allocations) | | Change fees | Vault Admin | [Create a vault](/curators/vaults/guides/create-a-vault) (also editable post-creation) | | Enable Whitelisted Reserves | Vault Admin (one-way) | [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) | | Set up Insurance Pool | Vault Admin | [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) | | Configure farms | Vault Admin | [Configure farms](/curators/vaults/guides/configure-farms) | | Transfer Vault Admin | Two-step (current → claim by new) | [Transfer admin to multisig](/curators/vaults/guides/transfer-admin) | | Emergency Insurance Pool withdrawal | 2-of-2 (curator + Kamino security) | [Set up the Insurance Pool → Withdrawal mechanisms](/curators/vaults/guides/set-up-insurance-pool#withdrawal-mechanisms) | | Cranking (sync, rebalance) | Permissionless | [Configure allocations → Sync after changes](/curators/vaults/guides/configure-allocations#sync-after-changes) | Cranking is permissionless — the network's bots run sync every \~15 minutes; you can also trigger it manually. You don't *manage* the crank; it runs. ## What's next > [card] [Transfer admin to multisig](/curators/vaults/guides/transfer-admin) > > The step-by-step migration to a Squads-controlled vault. > [card] [Risk primitives](/curators/vaults/concepts/risk-primitives) > > Insurance Pool's 2-of-2 emergency withdrawal model. # Yield & fees Source: https://docs.kamino.com/curators/vaults/concepts/yield-and-fees How vault yield is generated, the manager fee model, the withdrawal penalty, and farm reward distribution A vault's economics have three sides: **yield** that depositors earn, **fees** that the curator charges, and **rewards** distributed via farms. This page covers all three as a model. Fees are configured at vault creation — see [Create a vault](/curators/vaults/guides/create-a-vault) — and farms are set up via [Configure farms](/curators/vaults/guides/configure-farms). ## How yield is generated Vault yield comes entirely from interest paid by borrowers in the underlying reserves. There is no other yield source — if borrowers in your reserves aren't paying interest, depositors aren't earning. Lender yield in any Kamino reserve follows the same formula: ``` supply APY ≈ borrow_rate × utilization × (1 − protocol_take_rate) ``` A vault's **blended APY** is the weighted average across all its allocations: ``` vault APY = Σ (reserve_APY_i × allocation_share_i) ``` The blended APY moves in real time as utilization shifts, allocations rebalance, and any Conditional fills or fixed-rate matches happen. The displayed APY is a trailing average and is not a forward-looking guarantee. For the FR-specific economics (why Conditional allocation tends to higher utilization and how term premium contributes), see [Fixed Rates → Concepts](/curators/vaults/fixed-rates/concepts#economic-rationale). ## Auto-compounding via share price Vault depositors don't receive interest payments. Instead, accrued interest grows the vault's total assets while the share count stays fixed — so the **share price** (kToken exchange rate) appreciates. A depositor who held one kToken at deposit redeems for more deposit tokens at withdrawal. ``` share_price = total_vault_assets / shares_outstanding shares_minted = deposit_amount / share_price ``` There is no rebasing. The depositor's share count is stable. ## Manager fees You earn revenue through two fees configured at [vault creation](/curators/vaults/guides/create-a-vault), both editable post-creation, both denominated in basis points (1 bp = 0.01%). | Fee | Parameter | Basis | Default | | - | - | - | - | | **Performance fee** | `PerformanceFeeBps` | Vault profits | 0 | | **AUM (management) fee** | `ManagementFeeBps` | Total vault assets, annualized | 0 | Both fees accrue continuously in the deposit token. They are **not auto-collected** — you call a withdraw-pending-fees instruction when you want to claim. You can also give-up-pending-fees to return accrued fees to depositors (useful when fees grow disproportionately to vault size). For the workflow, see [Collect fees](/curators/vaults/guides/collect-fees). ### When to use which * **Performance fee** rewards generated yield. It scales with how well the vault performs and aligns curator incentive with depositor outcome. * **AUM fee** charges for active management regardless of yield. It scales with capital under management. Most vaults run both. A typical institutional configuration: `PerformanceFeeBps: 1500` (15%), `ManagementFeeBps: 200` (2%). Both rates are editable post-creation — see [Collect fees → Update performance fee](/curators/vaults/guides/collect-fees#update-performance-fee). ## The withdrawal penalty The withdrawal penalty is **a security mechanism, not manager revenue**. Penalties are returned to the vault, benefiting remaining depositors. It exists to prevent yield-sniping — the exploit where a user deposits just before an autocompound event, captures the yield, and immediately withdraws. | Parameter | Type | Description | | - | - | - | | `WithdrawalPenaltyBps` | Basis points | Percentage withdrawal fee | | `WithdrawalPenaltyLamports` | Lamports | Absolute withdrawal fee | The system charges the **MAX** of the two for each withdrawal. The BPS-based fee scales with size; the lamports-based fee prevents dust exploits. Recommended starting values: `WithdrawalPenaltyBps: 1` (0.01%), `WithdrawalPenaltyLamports: 1`. These are deliberately small — the penalty exists to defeat the exploit, not to deter normal withdrawal behaviour. Set both at [vault creation](/curators/vaults/guides/create-a-vault). ## The crank fund fee A small per-deposit fee charged on each deposit to cover the computational cost of investing the deposited capital into reserves. Not curator revenue — funds the protocol's invest crank operations. | Parameter | Type | Recommended | | - | - | - | | `CrankFundFeePerReserve` | Lamports | 1–2 per reserve in the vault's allocation | Higher values on a vault with many small deposits (and many reserves) increase per-deposit cost. Most vaults leave this at the recommended floor. Set at [vault creation](/curators/vaults/guides/create-a-vault). ## Fee summary | Fee | Recipient | Basis | Purpose | | - | - | - | - | | Performance Fee | Vault admin | Profits | Manager compensation for yield | | AUM Fee | Vault admin | Annual % of assets | Manager compensation for management | | Withdrawal Penalty (BPS) | Vault (depositors) | Withdrawal amount | Defeat yield-sniping | | Withdrawal Penalty (Lamports) | Vault (depositors) | Absolute | Defeat dust exploits | | Crank Fund Fee | Protocol | Per reserve, per deposit | Cover invest crank costs | ## Farm rewards Beyond interest yield, you can distribute additional rewards to depositors via **farms**. Every vault supports three farm types: | Farm | Role | | - | - | | **Vault Farm** | Distributes any reward token to depositors (kToken holders). One per vault. | | **Insurance Pool farm** | Holds your skin-in-the-game capital that absorbs losses before depositors. Backs vault risk; see [Risk primitives](/curators/vaults/concepts/risk-primitives). | | **Autocompound Farm** | Distributes rewards in the vault's deposit token, automatically compounding into vault positions. SDK support coming. | ### Vault Farm mechanics The Vault Farm is a separate on-chain account attached to the vault. Once created, farm authority transfers to the protocol — you stop directly managing it. To distribute rewards, you fund the farm with the reward token; depositors claim proportional to their kToken holdings over the reward period. The farm has a **cooldown period** — a delay before staked depositors can claim rewards. This prevents the exploit where a user deposits, claims rewards immediately, and withdraws. The cooldown ensures meaningful exposure before the claim entitlement. To attach the Vault Farm and configure the cooldown, see [Configure farms](/curators/vaults/guides/configure-farms). ### Autocompound The Autocompound Farm is a special-case farm where rewards are denominated in the vault's deposit token and automatically reinvested into vault positions. A USDC vault with an autocompound farm distributes USDC rewards that compound directly — no manual claim, no token management for the user. This is currently configurable via the UI; SDK support is coming. See [Configure farms → Autocompound](/curators/vaults/guides/configure-farms#autocompound-farm). ### Insurance Pool farm The Insurance Pool is implemented as a dedicated farm that holds the curator's locked capital. It interacts with the vault as a depositor but with stronger commitments (mandatory 30-day cooldown, public on-chain visibility, emergency-withdrawal multisig). Treat it as a risk primitive, not a yield mechanism — see [Risk primitives](/curators/vaults/concepts/risk-primitives) for the model and [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) for the workflow. ## What you display to depositors Vaults surface several metrics on Kamino's UI: * **Headline APY** — the blended interest APY across allocations. * **KMNO emissions** (when active) — added to the headline APY. * **Farm rewards** — typically displayed separately from the headline yield, since they're paid in non-deposit tokens. Be aware: a 9% headline APY made up of 6% organic interest + 3% KMNO emissions is materially different from 9% paid entirely in deposit-token interest. The first carries token price risk in its yield; the second doesn't. ## What's next > [card] [Collect fees](/curators/vaults/guides/collect-fees) > > Withdraw pending fees, give up fees, and update fee rates. > [card] [Configure farms](/curators/vaults/guides/configure-farms) > > Set up the Vault Farm, Insurance Pool farm, and Autocompound farm. > [card] [Risk primitives](/curators/vaults/concepts/risk-primitives) > > The Insurance Pool and Whitelisted Reserves. > [card] [Parameters](/curators/reference/parameters) > > Full parameter reference. # Allocations Source: https://docs.kamino.com/curators/vaults/fixed-rates/allocations Standard vs. Conditional allocation applied to fixed-rate reserves — the FR-specific application of the allocation primitive The two allocation types — Standard and Conditional — are the same primitive used everywhere in a vault. This page covers their **application to fixed-rate reserves**: which to choose, how Conditional fills behave, the priority pattern in the FR context, and the FR-specific bits of the setup workflow. For the underlying primitive (weight system, caps, the priority rule, sync mechanics), read [Concepts → Allocations](/curators/vaults/concepts/allocations) first. ## Both types work for FR reserves It's worth being explicit: **both allocation types are valid for fixed-rate reserves.** The choice is about capital efficiency vs. visibility, not technical compatibility. | Approach | Behavior | When to use | | - | - | - | | **Standard** | Capital is committed into the FR reserve immediately | You want visible committed liquidity, you're seeding a new FR reserve, or you're confident demand will arrive quickly | | **Conditional** | Capital stays in floating-rate reserves earning variable yield; deployed atomically when borrow demand arrives | The capital-efficient default for most FR exposure | | **Both on the same reserve** | Standard base layer + Conditional capacity behind it | You want a visible commitment plus latent capacity | ## Why Conditional is the default for FR Two problems with putting vault capital directly into a fixed-rate reserve: 1. **Opportunity cost.** Capital sitting in a fixed-rate reserve with no active borrow earns nothing. A direct 20% allocation to `USDC 5.5% 3M` with no borrowers is 20% of the vault earning zero until a borrower arrives. 2. **Liquidity fragmentation.** Splitting capital across many fixed-rate reserves directly makes each pool shallow. Large borrowers can't find depth at any single rate × duration cell. Conditional allocation solves both. The same pool of floating capital is signalled across multiple FR reserves — whichever fills first wins, and only that portion moves. While waiting, every dollar earns floating yield. ## How Conditional fills respond to demand A Conditional allocation is the vault-side mechanism that converts floating capital into FR reserve liquidity at the moment demand requires it. 1. You set a Conditional allocation on a fixed-rate reserve with an **allocation cap** (e.g. 10M on `USDC 5% 3M`). 2. No capital moves at configuration time. The 10M stays in your Standard floating allocations. 3. **Demand arrives** — either a direct borrow against the FR reserve or a borrow order matching its terms. 4. The vault crank atomically withdraws capital from an eligible floating source, deposits it into the FR reserve, and the borrow executes — all in one transaction. 5. Regular rebalancing (\~15 min auto, or manual via `invest-all-reserves`) redistributes remaining floating capital back to target weights. The trigger is *demand for fixed-rate liquidity*, not a specific borrow type. A direct borrow that finds the reserve underfunded triggers a Conditional fill the same way a borrow order does. See [Concepts → How borrowers take fixed-rate liquidity](/curators/vaults/fixed-rates/concepts#how-borrowers-take-fixed-rate-liquidity) for both demand paths. > [!NOTE] > > **The same pool of capital can signal across multiple fixed-rate reserves at once.** You can set Conditional allocations on `USDC 5.0% 3M`, `USDC 5.5% 3M`, and `USDC 6.0% 6M` all drawing from the same underlying floating capital. Whichever fills first wins; remaining signals stay active against whatever floating capital remains. ## Fill race between vaults Multiple vaults can place Conditional allocations on the same fixed-rate reserve. When demand arrives and more than one vault is eligible to satisfy it, **there is no size or time priority between vaults** — whichever vault's fill transaction lands first wins. In practice this is a race between crank bots. Operational levers: bot latency, priority fees, RPC quality, instruction construction efficiency. Same logic applies between Standard allocations on the same reserve and Conditional capacity behind them: a borrower sees the visible Standard liquidity first, and only triggers a Conditional fill when the visible liquidity is insufficient. ## Priority in the FR context Priority is the [allocation primitive](/curators/vaults/concepts/allocations#priority) that controls which Standard allocations are eligible as source reserves for Conditional fills. In the FR context, you use it to protect specific floating allocations from being drawn down opportunistically by FR fills. **The rule (from Concepts):** funds flow into a Conditional allocation only from Standard allocations whose priority is **less than or equal to** the Conditional reserve's priority. Higher number = more protected. **FR-specific worked example:** | Allocation | Type | Priority | Eligible source for the Conditional fill? | | - | - | - | - | | SOL/BTC Market USDC (float) | Standard | 0 | Yes (0 ≤ Conditional's 0) | | JLP Market USDC (float) | Standard | 0 | Yes | | Altcoin Market USDC (float) | Standard | 2 | No (2 > Conditional's 0) | | SOL/BTC Market USDC 5% 3M | Conditional | 0 | — (destination) | Use cases for raising priority on a Standard allocation in an FR-active vault: * A floating allocation in a market where you've committed to a minimum capital level (e.g. for ecosystem reasons or regulatory disclosure). * A deep strategic position you don't want opportunistically drawn down. * An allocation in a market where the collateral profile is materially riskier than the rest of your vault. > [!WARNING] > > Priority also mitigates a specific manipulation vector: an attacker can in principle open and close a [withdrawal ticket](/curators/vaults/concepts/liquidity-and-withdrawals#the-withdrawal-queue) in the same transaction on a Conditional reserve to trigger source-reserve draw-down without real borrower demand. Setting priority above the Conditional reserve's priority on any source you want protected closes this. ## Setup For the focused step-by-step walkthrough — UI, SDK, and CLI — see [Configure fixed-rate allocations](/curators/vaults/guides/configure-fixed-rate-allocations). It covers the FR-specific parameter choices (Conditional toggle, cap-as-binding-limit, priority for source protection) and includes runnable SDK and CLI examples. The general allocation workflow that handles floating reserves and the unallocated buffer is at [Configure allocations](/curators/vaults/guides/configure-allocations). ## A few FR-specific gotchas * **Conditional liquidity is a config, not an order.** You can't "cancel" a signal — lower the cap or remove the allocation. * **Default priority = 0 for everything.** Conditional allocations don't protect Standard sources by default; opt in explicitly. * **Weight is silently ignored on Conditional.** Setting a weight has no effect; only the cap matters. * **Reserve config changes have a \~4-hour lock.** If a market manager changes the reserve's rate or term, the change isn't live for \~4 hours. Relevant when you're watching a reserve's config shift. ## What's next > [card] [Configure fixed-rate allocations](/curators/vaults/guides/configure-fixed-rate-allocations) > > The focused step-by-step walkthrough for adding an FR allocation. > [card] [Lifecycle](/curators/vaults/fixed-rates/lifecycle) > > What happens after a fill — through term, rollover, repayment, exits via the queue. > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > The general allocation workflow (floating reserves and the unallocated buffer). > [card] [Allocations (primitive)](/curators/vaults/concepts/allocations) > > Weights, caps, sync, the priority rule. # Concepts Source: https://docs.kamino.com/curators/vaults/fixed-rates/concepts The rate grid, term premium, and how borrowers consume fixed-rate liquidity This page explains the structural and economic concepts that shape how a curator should think about fixed-rate reserves. If you're new to fixed rates, read this before [Allocations](/curators/vaults/fixed-rates/allocations). ## The rate grid A single market now serves each debt token through multiple reserves: * One **floating-rate reserve** — rate fluctuates with utilization (existing behaviour) * Zero or more **fixed-rate reserves** — each with a constant borrow rate and a fixed term, e.g. `USDC 5.0% 1M`, `USDC 5.5% 3M`, `USDC 6.0% 6M` These reserves sit on a **rate grid** organised by rate × duration. Example for USDC in a single market: | Rate | 1 month | 3 months | 6 months | 12 months | | - | - | - | - | - | | 5.0% | USDC 5.0% 1M | USDC 5.0% 3M | — | — | | 5.5% | — | USDC 5.5% 3M | USDC 5.5% 6M | — | | 6.0% | — | USDC 6.0% 3M | USDC 6.0% 6M | USDC 6.0% 12M | | 7.0% | — | — | USDC 7.0% 6M | USDC 7.0% 12M | Not every cell is populated. The market manager decides which rate × duration cells exist (see [Markets → Fixed Rates](/curators/markets/fixed-rates)). Each fixed-rate reserve is **fully isolated**. It has its own liquidity pool, its own borrowers, its own lenders, and its own utilization. A position in `USDC 5.5% 3M` has no interaction with `USDC 6.0% 6M`. A large repayment or withdrawal in one reserve does not affect liquidity in adjacent ones. The allocations UI shows reserve type, rate, term, supply APY, TVL, and utilization for each reserve. Use those as your primary allocation signals. ## Term premium and the emerging yield curve The rate grid creates a visible, on-chain term structure: what the market currently prices for 1-month, 3-month, 6-month, and 12-month USDC lending. This is the yield curve for that debt token. The **term premium** is the additional yield lenders require to commit capital for a longer duration. If 3-month USDC clears at 5.0% and 6-month clears at 5.5%, the term premium for the additional 3 months is 50 bps — compensation for reduced liquidity and increased uncertainty over the longer horizon. For curators, the practical implication: the longer cells of the grid tend to clear at higher rates. If your depositor profile tolerates duration, the marginal yield is there. Reading the grid across maturities (1M → 3M → 6M → 12M) shows where the market currently prices duration. To act on a signal — add or expand an FR allocation — see [Allocations](/curators/vaults/fixed-rates/allocations) and [Configure allocations](/curators/vaults/guides/configure-allocations). ## How borrowers take fixed-rate liquidity Two independent paths bring borrow demand into a fixed-rate reserve. Your allocation responds the same way to either. ### Direct borrow A borrower with sufficient collateral sees available liquidity in the fixed-rate reserve and borrows it in a single atomic transaction. This is the same flow as borrowing from any reserve — there is no "order" sitting on-chain, no standing intent. The borrower acts now: collateral posted, debt taken, transaction lands in one slot. For a curator, this means: * A Standard allocation is immediately usable by direct borrows from the moment it lands. * A Conditional allocation can also satisfy a direct borrow — the vault's atomic-fill path triggers as part of the borrow transaction, moving capital from a floating source into the FR reserve and serving the borrow in one shot. ### Borrow order A borrower posts a standing intent: "I want to borrow X tokens at a max rate of Y for at least Z duration, fillable until T." The order doesn't borrow anything yet — it sits on-chain until matching reserve liquidity is available, at which point a fill bot (or anyone, since the fill instruction is permissionless) executes the borrow on the borrower's behalf. Borrow order parameters: | Field | Meaning | | - | - | | `debtLiquidityMint` | Token the borrower wants | | `requestedDebtAmount` | Originally requested size | | `remainingDebtAmount` | Still unfilled | | `maxBorrowRateBps` | Ceiling rate the borrower accepts | | `minDebtTermSeconds` | Minimum acceptable term (`0` = open-term only) | | `fillableUntilTimestamp` | Expiry | | `filledDebtDestination` | Borrower-owned token account where filled funds land | Orders fill atomically against any matching reserve. Fill ordering between competing reserves is **random** — first transaction to execute wins; no priority by submission time, order size, or any other factor. Partial fills are allowed: if the matching reserve has only some of the requested liquidity, the available portion fills immediately and the order remains open for the remainder. Each filled portion accrues interest from the slot it fills. For a curator, the borrow-order book is a source of **demand signal**. An order that's been sitting unfilled for hours at `5.5% / 6M` is the market telling you there's appetite at that cell. Adding capacity there (Conditional or Standard) lets your vault capture the fill — see [Allocations](/curators/vaults/fixed-rates/allocations) for the FR-specific allocation guidance, and [Configure allocations](/curators/vaults/guides/configure-allocations) for the workflow. ## Why FR yields can be higher The general yield formula `Supply APY ≈ Borrow Rate × Utilization × (1 − Protocol Take Rate)` is covered in [Concepts → Yield & fees](/curators/vaults/concepts/yield-and-fees#how-yield-is-generated). The FR-specific observation: **Fixed-rate reserves can run at high utilization when matched with active borrow demand.** At 100% utilization, the `× utilization` factor disappears and lenders earn the borrow rate net of the protocol take for the full term: * A floating reserve at 70% utilization paying a 6% borrow rate passes roughly 4.2% to lenders before protocol take. * A fixed reserve at 100% utilization paying 5.5% passes 5.5% × (1 − take rate) for the locked duration. The economics depend on demand actually showing up. An empty fixed-rate reserve is idle capital regardless of the headline rate — which is the central reason curators typically use Conditional rather than Standard allocation for fixed-rate exposure: capital earns floating yield while waiting for demand instead of sitting idle in the FR reserve. The term premium compounds this — longer-duration reserves clear at higher rates than shorter ones, and capturing it is one of the structural alpha sources FR enables. ## What's next > [card] [Allocations](/curators/vaults/fixed-rates/allocations) > > Standard vs. Conditional in the FR context, fill mechanics, priority, setup. > [card] [Lifecycle](/curators/vaults/fixed-rates/lifecycle) > > What your capital experiences from fill through exits. # Fixed Rates Source: https://docs.kamino.com/curators/vaults/fixed-rates/index Allocating vault capital into fixed-rate reserves — the FR-specific guide for curators Fixed-rate reserves are a distinct reserve type within Kamino lending markets. Each reserve has a constant borrow rate and a fixed term (e.g. `USDC 5.5% 3M`) and exists alongside the floating-rate reserve for the same debt token. Curators have **two ways to allocate** into a fixed-rate reserve: * **Direct (Standard) allocation** — capital is committed into the reserve immediately. Visible liquidity, available for direct borrows from the moment it lands. * **Conditional allocation** — capital stays in floating-rate reserves earning variable yield, and is atomically moved into the fixed-rate reserve only when borrow demand arrives. Both are valid. Conditional is the capital-efficient default for most fixed-rate exposure; direct allocation is the right call when you want capital visibly committed and immediately available, or when you're seeding a reserve where bootstrapping liquidity matters more than yield optimisation. Borrow demand reaches the reserve through two paths: a **direct borrow** (an instant atomic transaction against available reserve liquidity, just like any normal borrow) or a **borrow order** (a standing on-chain intent that fills when matching liquidity arrives). Both consume the same reserve liquidity — your allocation responds to either path. ## Read in this order > [card] [Concepts](/curators/vaults/fixed-rates/concepts) > > The rate grid, term premium, and how borrowers consume fixed-rate liquidity. > [card] [Allocations](/curators/vaults/fixed-rates/allocations) > > Standard vs. Conditional in the FR context, fill mechanics, and priority. > [card] [Configure fixed-rate allocations](/curators/vaults/guides/configure-fixed-rate-allocations) > > Step-by-step UI / SDK / CLI walkthrough for adding an FR allocation. > [card] [Lifecycle](/curators/vaults/fixed-rates/lifecycle) > > What your capital experiences from fill through term, rollover, repayment, post-maturity liquidation, and exits via the withdrawal queue. > [card] [Strategy](/curators/vaults/fixed-rates/strategy) > > Postures, sizing, monitoring, and a worked \$100M vault example. # Lifecycle Source: https://docs.kamino.com/curators/vaults/fixed-rates/lifecycle What your vault's capital experiences from fill through term, rollover, repayment, post-maturity liquidation, and exits via the withdrawal queue This page traces what happens to your vault's capital from the moment a fill occurs through the loan's full term and every exit path — repayment, rollover, post-maturity liquidation, and your own queued exits. Everything below is from the **lender's perspective**. ## Before the fill — the signalled state If you've placed a **Conditional allocation**, your capital exists as configuration on the vault. No capital has moved. Your floating allocations continue to earn variable yield. Any number of borrow demand events could match your signal — only one will, whichever lands first. If you've placed a **Standard allocation**, your capital sits in the fixed-rate reserve immediately. It earns nothing until a borrower takes it (the rate × utilization formula gives zero at zero utilization), but it's visibly available for direct borrows. ## The fill When a borrower takes liquidity from a fixed-rate reserve where your allocation is sourced: * **Standard allocation path.** The borrower borrows directly against your committed liquidity. The reserve's `borrowed_amount` increases, your share of the reserve's outstanding debt grows. No tokens move at the vault level — your kTokens already represented your share of the reserve. * **Conditional allocation path.** The crank performs three steps in a single atomic transaction: withdraws capital from an eligible source reserve (priority-respecting), deposits it into the fixed-rate reserve, executes the borrow. If any step fails, the whole transaction reverts — the vault is never left in an inconsistent state. After a Conditional fill, automatic rebalancing (\~15 minutes) redistributes remaining floating capital to maintain target weights. The vault now holds a fixed-rate position equal to the filled amount; the floating allocations sit at slightly reduced levels until the next rebalance settles things. ## The active term Once filled, your capital is committed to the fixed-rate reserve for the loan's term. Fixed-rate reserves run at high utilization when matched with active borrow demand — at 100% utilization, lenders earn the borrow rate net of the protocol take rate for the locked duration. The term is set per borrow at fill time, anchored to the borrower's `last_borrowed_at_timestamp`. If the reserve's `debt_term_seconds` is 90 days, that borrower's individual maturity is 90 days from the slot of their fill — not from when the reserve was created or from when other borrowers took liquidity. This means a single fixed-rate reserve typically holds several borrows at different stages of their terms, all maturing at different points. From your vault's perspective you hold fractional exposure to all of them, weighted by how much you sourced each fill. Kamino's allocations UI shows current vs. target allocation separately. Your current allocation is your actual position, which may diverge from target while fixed-rate positions are locked. ## Maturity outcomes Each borrow inside the reserve has its own maturity. As each one approaches the end of its term, one of several things happens. ### Rollover (pre-expiration) Rollover runs inside a **pre-expiration window** configured at the market level — typically a few hours or a day before the loan's term end. A keeper bot ("Rollaz" internally) sweeps positions in their rollover windows and attempts to roll them. | Outcome | Trigger | Vault impact | | - | - | - | | **Same-reserve rollover** | Liquidity available; no withdrawal tickets queued; market rollover window is open | Term clock resets. **No tokens move.** Your position stays locked in the same reserve for another full term at the same rate. | | **Different fixed reserve** | Keeper finds a matching reserve at a different rate or duration; window is open | Loan migrates atomically. Tokens transfer between reserve vaults. Your capital stays with the original reserve unless your allocation also covers the new one. | | **Open-term fallback** | `open_term_rollover_window_duration_seconds` configured; borrower opted in (`open_term_allowed = true`); no fixed-rate match available | Position migrates to the floating-rate reserve (same mint). Your capital stays with the original FR reserve. | > [!NOTE] > > **Rollover requires a pre-expiration window.** If `fixed_term_rollover_window_duration_seconds` is `0` on the market, rollover is disabled entirely and every borrower must repay at maturity. Rollover cannot be attempted after expiration — past the term end there's no rollover path, only liquidation. > [!WARNING] > > **Rollover is not supported inside elevation groups.** Borrowers using elevation modes (eMode) on the market cannot have their fixed-term positions rolled over. Factor this into your sizing if your fixed-rate allocations sit in elevation-enabled markets — those positions will require manual repayment at maturity. ### Repayment (any time) A borrower can repay at any point before maturity, with two cases: * **Repay during the first term, before accruing the minimum required interest.** An early-repay penalty applies — the projected interest for the remainder of the term, scaled by the reserve's `early_repay_remaining_interest_pct`. The penalty accrues entirely to **protocol fees on the debt reserve**, not to lenders. Your vault's lender yield is unaffected by the penalty mechanism itself. * **Repay after the minimum interest threshold, or after rollover.** No penalty. Borrower pays principal + accrued interest. Either way, repayment returns capital to the reserve. If your vault has a withdrawal ticket queued in that reserve, the repayment feeds the queue (FIFO). Otherwise it sits in the reserve as available liquidity for the next borrow or the next rebalance. ### Default — protocol-enforced liquidation If a borrower takes no action and the term elapses, the position becomes liquidatable **regardless of collateral health**. Kamino treats an expired fixed-term loan as a protocol-level breach, not a price-driven one. Liquidation enters a **linear ramp** configured per market via `term_based_full_liquidation_duration_secs`: * The liquidatable fraction grows from 0% (at term end) to 100% (at `term-end + duration`). * Liquidators claim a **deleveraging bonus** that starts at the reserve's `min_deleveraging_bonus_bps` and increases `deleveraging_bonus_increase_bps_per_day` per day, capped at `max_liquidation_bonus_bps`. * Protocol-enforced liquidation **bypasses the reserve's deposit withdrawal caps** and explicitly consumes from the withdrawal-queue pool — so from your vault's perspective, term-breach liquidation proceeds feed queued tickets. The same mechanism applies if the reserve itself hits its `debt_maturity_timestamp` (a reserve-wide sunset configured by the market manager) — but with no ramp; all borrows on that reserve become fully liquidatable immediately when the maturity elapses (assuming the market has `mature_reserve_debt_liquidation_enabled = true`). ## Exiting via the withdrawal queue For ordinary floating-rate allocations, exits are usually instant: you decrease the weight, the rebalancer redeems cTokens against available reserve liquidity, capital lands back in the vault. For fixed-rate allocations, the queue is **the** exit. A Standard allocation to a high-utilization fixed-rate reserve can't be redeemed instantly because capital is committed to active borrows for the term. To exit, the vault submits a **withdrawal ticket** and waits for repayments, new deposits, or liquidations to feed liquidity to the head of the queue. The queue is a vault-wide primitive — see [Concepts → Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals) for FIFO mechanics, ticket lifecycle, SDK surface, REST endpoints, and the WQP bot. The FR-specific behavior follows. ### The rollover-blocking rule The single most important FR-specific behaviour: **a queued ticket on a reserve blocks every borrower in that reserve from rolling over.** Borrowers at maturity must repay; they cannot extend their term. This is the design rule expressed in concrete terms — lender exit takes precedence over borrower stay-in. The protocol enforces it on every rollover attempt. Operationally, this turns the queue into a **forcing function**: * A ticket submitted mid-term doesn't return capital immediately. * But it guarantees capital returns at the *next maturity wave*, because affected borrowers are forced to repay. * The reserve's queue state therefore drives the timing of borrower repayments, not just lender redemptions. If you know you want out of a fixed-rate position by a specific date, queue ahead. The ticket sits cheaply (cancellable for free) and locks in your priority for the next cohort of repayments. ### Two flows for FR exits **Vault-side disinvestment.** When you decrease or remove a Standard allocation to a high-utilization FR reserve, the rebalancer can't redeem capital instantly. The vault submits a withdrawal ticket against the reserve. As liquidity returns, the ticket fills and cTokens land back in the vault, where the rebalancer redeploys them per current target weights. Important constraint: **the vault `invest` operation does not auto-queue.** If you change a weight on an FR reserve, the rebalancer attempts a normal disinvestment and stops if there's no available liquidity. To actually exit, you trigger the queue path explicitly. **Depositor redemption with FR exposure.** When a depositor redeems vault shares from a vault with active FR allocations, the SDK orchestrator (`withdrawRedeemAndEnqueueIxs`) handles a multi-leg flow: pull whatever instant liquidity exists → redeem-in-kind for the remainder → enqueue tickets against each underlying FR reserve. This is the path Private Credit V2 uses end-to-end. ### Queue depth as a strategic signal Queue depth tells you about *competing exit demand* on a reserve. Three patterns: * **Deep queue, low utilization.** Tickets are queued but the reserve has available liquidity — the WQP bot is processing in real time. Healthy. Your ticket would fill quickly. * **Deep queue, high utilization.** Tickets are queued and the reserve is fully utilized. New borrowers can't enter (lenders exiting take priority); existing borrowers can't roll. The reserve is in an unwinding phase. Adding a new allocation here means going to the back of the line. * **No queue, high utilization.** Reserve is at full work and lenders are sticking around. New borrow demand competes with existing borrowers for repayment cycles. Conditional capacity here can fill at attractive rates. Read queue depth alongside utilization and unfilled borrow-order demand to understand where each reserve actually sits in its cycle. ### FR-relevant SDK methods The full SDK surface is in [Concepts → Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals). The methods you'll reach for in an FR-active vault: * **`withdrawRedeemAndEnqueueIxs`** — orchestrator for depositor redemptions; sends withdraw + redeem-in-kind + enqueue legs in sequence. Supports `skipWithdrawLeg` for the dust case where the instant leg would revert. * **`KaminoReserve.getAllWithdrawTickets()`** — returns all tickets for a reserve across owners. Use to compute queue depth and ordinality for "queued before you" UX. * **`getReserveAllocationAvailableLiquidityToWithdraw`** — per-reserve available liquidity capped by reserve availability. Decides whether a redemption needs the queue path. * **`getMaxInstantWithdrawableAmount`** — total instant-redemption capacity across the vault's allocations. ## How interest accrues For a fixed-rate reserve at 100% utilization, lender yield is `borrow_rate × (1 − protocol_take_rate)` for the locked term. Interest compounds per slot using the reserve's cumulative borrow rate index. From the vault's POV, your kToken exchange rate appreciates over time as accumulated interest grows the reserve's total assets — same accounting as floating reserves, no special handling. ## What's next > [card] [Strategy](/curators/vaults/fixed-rates/strategy) > > Postures, sizing, monitoring, and a worked example. > [card] [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals) > > The full queue primitive (FIFO mechanics, SDK surface, REST endpoints). # Strategy Source: https://docs.kamino.com/curators/vaults/fixed-rates/strategy Allocation postures, sizing framework, monitoring cadence, and a worked vault example This page is for curators who've internalised the mechanics ([Concepts](/curators/vaults/fixed-rates/concepts), [Allocations](/curators/vaults/fixed-rates/allocations), [Lifecycle](/curators/vaults/fixed-rates/lifecycle)) and want a framework for deploying capital. ## Reading demand on the rate grid Demand for fixed-rate liquidity shows up in two places, and you should watch both. **Reserve activity** is the realised half: how much capital is being borrowed against each fixed-rate reserve, what the utilization is, and how quickly capital is turning over. Active reserves with healthy utilization tell you where the market is clearing. Watch for reserves that fill quickly after each fill — that's a signal capacity is undersupplied. **Unfilled borrow orders** are the latent half: borrowers expressing standing intent at specific rate × duration cells without matching reserve liquidity to fill them yet. A persistent 40M of unfilled order demand at `5.5% / 6M` is a clear signal — adding capacity (Conditional or Standard) lets your vault be the source that fills them. Use both together: reserve activity shows what's working today, the order book shows what the market wants tomorrow. For the data sources behind both signals, see [Data & API](/curators/data/vault-data) and [Allocation data](/curators/data/allocation-data). ## Allocation postures ### Conservative posture * 80–90% in Standard floating allocations across diversified markets * 1–2 Conditional allocations on well-understood fixed-rate reserves * Tight caps — 5–10% of vault per fixed-rate reserve * Review weekly; adjust caps as demand shifts Best for: stable depositor base, low tolerance for exit friction, vaults optimising for consistency over yield. ### Yield-optimising posture * Conditional placements across multiple rate × duration cells * Larger caps — 20–30% of vault in aggregate across fixed-rate reserves * Active daily monitoring of the borrow-order book and reserve activity * Strategic priority use to protect key floating sources * Bot infrastructure to win fill races against competing vaults Best for: sophisticated allocators, active depositor base that understands duration exposure, vaults where yield leadership is the mandate. ## Sizing framework — the maturity mismatch budget Your depositors can demand liquidity at any time. Your fixed-rate positions can be locked for weeks to months. Work out your budget: 1. **Buffer.** Unallocated + deep floating capital sufficient to service normal withdrawal flow. 2. **Fixed-rate ceiling.** Maximum fraction of vault that can be in fixed-rate exposure at any time. 3. **Queue runway.** Worst-case exit time through the [withdrawal queue](/curators/vaults/fixed-rates/lifecycle#exiting-via-the-withdrawal-queue) given each reserve's repayment patterns. A common starting split: 5–10% unallocated buffer, 70–85% Standard floating, 10–25% Conditional across fixed-rate reserves. Adjust based on observed depositor flow. ## Selection heuristics * **Target the tails of the grid.** Longer-duration reserves command higher term premium. If your depositor profile tolerates the duration, the marginal yield is there. * **Follow unfilled demand.** Large, persistently unfilled borrow orders at a specific rate × duration are a direct signal to add capacity. * **Mind reserve concentration.** Multiple Conditional allocations at different cells all drawing from the same floating capital is capital-efficient — you're not fragmenting depth. * **Protect strategic sources.** Any floating allocation you want preserved as a minimum should be priority-elevated. * **Mix Standard and Conditional thoughtfully.** Use Standard to bootstrap visible liquidity in reserves where you want to anchor; use Conditional for the rest of your fixed-rate exposure to keep capital efficient. * **Use the withdrawal queue as a forcing function.** A queued ticket blocks rollovers in the reserve, so capital is guaranteed to return at the next maturity wave. See [Lifecycle → Exiting via the withdrawal queue](/curators/vaults/fixed-rates/lifecycle#exiting-via-the-withdrawal-queue). ## Monitoring cadence | Cadence | What to watch | | - | - | | Per crank cycle (\~15 min) | Allocation state matches target | | Daily | Unfilled demand on the order book; utilization on FR reserves you're positioned in; active fills | | Weekly | Maturity dates on held positions; queue depth; competing vault activity | | Per fill | Was the fill expected? Did the right source reserve drain? Any unexpected re-entry? | ## Worked example — diversified USDC vault A \$100M USDC vault running a mixed floating + fixed-rate strategy, blending Standard and Conditional allocations: | Allocation | Type | Weight | Cap | Priority | | - | - | - | - | - | | SOL/BTC Market USDC (float) | Standard | 500 | No cap | 0 | | JLP Market USDC (float) | Standard | 300 | \$30M | 0 | | Altcoin Market USDC (float) | Standard | 200 | \$15M | 2 | | SOL/BTC Market USDC 5% 3M | Standard | 100 | \$5M | 0 | | SOL/BTC Market USDC 5% 3M | Conditional | — | \$15M | 0 | | SOL/BTC Market USDC 5.5% 3M | Conditional | — | \$15M | 0 | | SOL/BTC Market USDC 6% 6M | Conditional | — | \$10M | 0 | **What this vault does:** * Standard floating weights distribute the bulk of capital 5/3/2 across Main, JLP, and Altcoin markets — respecting the caps on JLP and Altcoin. * The `5% 3M` reserve has both a \$5M Standard allocation (visible, immediately available for direct borrows) and a \$15M Conditional allocation (latent capacity that activates on bigger demand). Total potential exposure: \$20M. * The `5.5% 3M` and `6% 6M` reserves are pure Conditional — visible capacity only when demand actually arrives. * The three Conditional allocations together signal up to \$40M of fixed-rate capacity, all drawing from the same underlying floating capital. Whichever fills first wins. * Altcoin Market floating allocation (priority 2) is **protected** from Conditional fills. * SOL/BTC Market and JLP Market floating allocations (priority 0) are eligible sources for Conditional fills. **A \$15M direct borrow lands on SOL/BTC Market `5% 3M`:** 1. Borrower's transaction sees \$5M of visible Standard liquidity in the reserve, plus \$15M of Conditional capacity behind it. Total available: \$20M. 2. The borrow takes the \$5M Standard liquidity first, then triggers a Conditional fill for the remaining \$10M, atomically pulled from SOL/BTC Market floating. 3. After the rebalance settles (\~15 min), the vault's actual allocations adjust toward target weights given the now-locked \$15M position. **If the borrower repays at maturity:** The \$15M returns to the `5% 3M` reserve. If there's a queued withdrawal ticket against that reserve, it fills first. Otherwise the regular rebalance pulls capital back into the Standard weights. # Collect fees Source: https://docs.kamino.com/curators/vaults/guides/collect-fees Withdraw pending performance and AUM fees, give fees back to depositors, and update fee rates Performance and AUM fees accrue continuously in the vault's deposit token, but they are **not auto-collected** — you have to claim them. This guide covers the four operations: withdraw, give up, update performance rate, update AUM rate. For the model behind each fee, see [Yield & fees](/curators/vaults/concepts/yield-and-fees#manager-fees). ## Withdraw pending fees Move accrued fees from the vault to the admin wallet. Both performance and AUM fees are claimed in a single call. > [tab] UI > > 1. Open your vault on `kamino.com/curators/vaults`. > 2. Open the **Settings** tab and find the **Pending Fees** section. The current accrued amount is displayed in the deposit token. > 3. Click **Withdraw Fees**. > 4. Sign with your admin wallet, or generate a Squads proposal if the vault is multisig-controlled. > > The fees land in the admin wallet's associated token account for the deposit token. > [tab] SDK > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > > const adminSigner = await parseKeypairFile('/path/to/your/keypair.json'); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const manager = new KaminoManager(rpc, slotDuration); > > const vault = new KaminoVault(rpc, address('')); > const instructions = await manager.withdrawPendingFeesIxs(vault); > > // Build and send the transaction with the standard @solana/kit pipe > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > tx => setTransactionMessageFeePayerSigner(adminSigner, tx), > tx => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > tx => appendTransactionMessageInstructions(instructions, tx), > ), > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > skipPreflight: true, > }); > ``` > [tab] CLI > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager withdraw-pending-fees \ > --vault \ > --mode execute > ``` > > For multisig-controlled vaults, append `--mode multisig --multisig ` to emit a Base58-encoded payload for [Squads](https://squads.so). ## Give up pending fees Return accrued fees to depositors. Useful when accrued fees have grown disproportionately to vault size, when you want to retroactively adjust your effective fee rate, or as a goodwill gesture after a difficult period. > [tab] UI > > The Settings tab includes a **Give Up Fees** action alongside **Withdraw Fees**. You specify the amount to return; it goes back to the vault and benefits remaining depositors via increased share price. > [tab] SDK > > ```typescript theme={"theme":"css-variables"} > import { Decimal } from 'decimal.js'; > > const giveUpIx = await manager.giveUpPendingFeesIx( > vault, > new Decimal(1000000), // amount in the deposit token to give up > adminSigner, > ); > > // Build and send: [giveUpIx] > ``` > [tab] CLI > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager give-up-pending-fees \ > --vault \ > --max-amount-to-give-up \ > --mode execute > ``` > > `--max-amount-to-give-up` is in tokens (not lamports). Pass the full pending-fee amount to give back everything; pass a smaller value to give back only part. ## Update performance fee Change the percentage of vault profits taken as the performance fee. Editable any time post-creation. > [tab] UI > > Settings → Fees → edit the **Performance Fee** value (in basis points, 1 bp = 0.01%). Submit. > [tab] SDK > > ```typescript theme={"theme":"css-variables"} > const { updateVaultConfigIx } = await manager.updateVaultPerfFeeIxs( > vault, > 500, // new fee in basis points (here, 5%) > adminSigner, > ); > // Build and send: [updateVaultConfigIx] > ``` > [tab] CLI > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-perf-fee \ > --vault \ > --fee-bps \ > --mode execute > ``` > > Example: `--fee-bps 1500` sets a 15% performance fee. ## Update AUM (management) fee Change the annualized percentage charged on total vault assets. Editable any time post-creation. > [tab] UI > > Settings → Fees → edit the **AUM Fee** value (in basis points). Submit. > [tab] SDK > > ```typescript theme={"theme":"css-variables"} > const { updateVaultConfigIx } = await manager.updateVaultMgmtFeeIxs( > vault, > 200, // new fee in basis points (here, 2%) > adminSigner, > ); > // Build and send: [updateVaultConfigIx] > ``` > [tab] CLI > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-mgmt-fee \ > --vault \ > --fee-bps \ > --mode execute > ``` ## Operational notes * **Both fees claim together.** `withdraw-pending-fees` collects accrued performance and AUM fees in a single transaction. There's no separate withdraw for each. * **Fee changes apply forward.** Updating a fee rate doesn't retroactively change accrued fees — it changes the rate at which new fees accrue. * **Multisig flow.** Production vaults run under [Squads](/curators/vaults/concepts/roles-and-ownership#the-squads-multisig-model). Every fee operation produces a proposal that members approve and execute. SquadsX automates the proposal step from `kamino.com/curators/vaults`; the CLI's `--mode multisig` emits a Base58 payload to import into Squads manually. * **Withdrawal penalties are not curator revenue.** They're a security mechanism returned to the vault — see [Yield & fees → The withdrawal penalty](/curators/vaults/concepts/yield-and-fees#the-withdrawal-penalty). You can't withdraw or change them through this guide. ## What's next > [card] [Yield & fees](/curators/vaults/concepts/yield-and-fees) > > The full fee model, including withdrawal penalties and farm rewards. > [card] [Roles & ownership](/curators/vaults/concepts/roles-and-ownership) > > Multisig flow that governs every fee operation in production. # Configure allocations Source: https://docs.kamino.com/curators/vaults/guides/configure-allocations Add, edit, and remove reserve allocations on a vault — UI, SDK, and CLI This guide is the operational walkthrough for managing vault allocations. For the conceptual model — Standard vs. Conditional, weights, caps, priority — read [Concepts → Allocations](/curators/vaults/concepts/allocations) first. This page assumes you've already chosen the parameters you want. For fixed-rate-specific allocation patterns and a focused step-by-step, see [Configure fixed-rate allocations](/curators/vaults/guides/configure-fixed-rate-allocations). > [tab] UI > > ## Configure via kamino.com/curators/vaults > > ### Add a reserve > > **1. Open the Allocations tab** > > Navigate to your vault on `kamino.com/curators/vaults` and open the **Allocations** tab. > > **2. Click Add Reserve** > > Opens the allocation configuration form. > > **3. Select market and reserve** > > The reserve picker shows market name and TVL, reserve type (floating or fixed-rate), supply APY, reserve TVL, and utilization. A market may contain multiple reserves for the same token (e.g. USDC floating, USDC 5% 3M, USDC 6% 6M). > > **4. Set parameters** > > | Parameter | Notes | > | - | - | > | Allocation Weight | Relative integer; ignored for Conditional allocations | > | Allocation Cap | Hard ceiling in tokens; binding limit for Conditional | > | Conditional Allocation toggle | Off = Standard (immediate deployment); On = Conditional (deploy on demand) | > | Allocation Priority | Default `0`; raise to protect this Standard allocation from being a source for Conditional fills | > > **5. Submit** > > Sign with your admin wallet, or generate a Squads proposal if the vault is multisig-controlled. > > ### Edit an existing allocation > > Open the allocation entry on the Allocations tab. Adjust weight, cap, type toggle, or priority. Submit. > > ### Batch edit weights > > To change weights across multiple reserves in a single transaction, use the batch-edit view. The UI shows real-time percentage recalculation and projected vault APY impact, including unallocated funds. > > ### Remove an allocation > > Either set the weight (Standard) or cap (Conditional) to `0`, or remove the entry entirely. The removed reserve's share is redistributed to the remaining allocations per their weights. > [tab] SDK > > ## Configure via TypeScript SDK > > ### Add or update an allocation > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > Reserve, > ReserveAllocationConfig, > ReserveType, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import { Decimal } from 'decimal.js'; > > const adminSigner = await parseKeypairFile('/path/to/your/keypair.json'); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoManager = new KaminoManager(rpc, slotDuration); > > const vault = new KaminoVault(rpc, address('')); > const reserveAddress = address(''); > > const reserveState = await Reserve.fetch(rpc, reserveAddress); > const reserveWithAddress = { address: reserveAddress, state: reserveState! }; > > // Standard allocation > const standardConfig = new ReserveAllocationConfig( > reserveWithAddress, > 100000, // weight > new Decimal('18446744073709551615'), // u64 max = no cap > new ReserveType.Standard(), > 0, // priority > ); > > // OR — Conditional allocation (typically for fixed-rate reserves) > const conditionalConfig = new ReserveAllocationConfig( > reserveWithAddress, > 0, // weight ignored for Conditional > new Decimal('10000000'), // 10M token cap > new ReserveType.Conditional(), > 0, // priority > ); > > const { updateReserveAllocationIx } = > await kaminoManager.updateVaultReserveAllocationIxs(vault, standardConfig, adminSigner); > > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > tx => setTransactionMessageFeePayerSigner(adminSigner, tx), > tx => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > tx => appendTransactionMessageInstructions([updateReserveAllocationIx], tx), > ), > ); > > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > skipPreflight: true, > }); > ``` > > The same `updateVaultReserveAllocationIxs` method handles both **adding a new reserve** and **updating an existing one** — the SDK detects whether the allocation already exists. > > ### Read current allocations > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoVault } from '@kamino-finance/klend-sdk'; > > const vault = new KaminoVault( > createSolanaRpc('https://api.mainnet-beta.solana.com'), > address(''), > ); > > const allocations = await vault.getVaultAllocations(); > for (const [reserveAddress, overview] of allocations) { > console.log( > `${reserveAddress}: ` + > `weight ${overview.targetWeight}, ` + > `cap ${overview.tokenAllocationCap}, ` + > `current ${overview.ctokenAllocation}`, > ); > } > ``` > > ### Remove an allocation > > ```typescript theme={"theme":"css-variables"} > const removeIx = await kaminoManager.removeReserveFromAllocationIx( > vault, > address(''), > adminSigner, > ); > // Build and send using the same pattern as above > ``` > > If the underlying reserve has insufficient liquidity to deallocate fully, the deallocation queues through the [withdrawal queue](/curators/vaults/concepts/liquidity-and-withdrawals). > > ### Read vault overview with incentives > > ```typescript theme={"theme":"css-variables"} > import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk'; > import { Decimal } from 'decimal.js'; > > const overview = await kaminoManager.getVaultOverview( > vault, > new Decimal(1.0), // deposit token price (adjust for non-stablecoin vaults) > ); > > console.log('APYs:', overview.actualSupplyAPY); > console.log('Reserve farm incentives:', overview.reservesFarmsIncentives); > ``` > [tab] CLI > > ## Configure via Kamino CLI > > > [!NOTE] > > > > Complete the [CLI installation guide](/build/cli/installation-setup) first. Commands require a `.env` file with `ADMIN` and `RPC` configured. > > ### Add or update an allocation > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-reserve-allocation \ > --vault \ > --reserve \ > --allocation-weight \ > --allocation-cap \ > --allocation-type \ > --priority \ > --mode simulate > ``` > > | Flag | Notes | > | - | - | > | `--allocation-weight` | Relative integer. Ignored for Conditional. | > | `--allocation-cap` | Decimal token amount (not lamports). Use `18446744073709.551615` for no cap. | > | `--allocation-type` | `Standard` or `Conditional`. | > | `--priority` | Integer. Default `0`. | > | `--mode` | `simulate` first to verify, then `execute` to send, or `multisig` to emit a Base58 payload for Squads. | > > > [!WARNING] > > > > Always run `--mode simulate` first to verify the resulting state. > > **Example — adding a Conditional allocation to a fixed-rate reserve:** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-reserve-allocation \ > --vault 67dqmR76uAbjX6e81A1ganKv3ou31WUMEdeWJkwVfeXy \ > --reserve 9GJ9GBRwCp4pHmWrQ43L5xpc9Vykg7jnfwcFGN8FoHYu \ > --allocation-weight 0 \ > --allocation-cap 10000000 \ > --allocation-type Conditional \ > --priority 0 \ > --mode simulate > ``` > > ### Remove an allocation > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager remove-vault-allocation \ > --vault \ > --reserve \ > --mode simulate > ``` > > ### Multisig mode > > For multisig-controlled vaults, append `--mode multisig --multisig `. The CLI emits a Base58-encoded transaction string that you import into [Squads](https://squads.so) for proposal and approval. > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-reserve-allocation \ > --vault \ > --reserve \ > --allocation-weight \ > --allocation-cap \ > --allocation-type Standard \ > --mode multisig \ > --multisig > ``` > > > [!NOTE] > > > > Batch editing of multiple allocation weights in a single transaction is not available via CLI. Use the SDK or UI for batch operations. ## Sync after changes Allocations are *targets*. After updating an allocation, the vault doesn't immediately rebalance — a permissionless sync brings actual allocation toward target. The sync bot runs every \~15 minutes; you can also trigger it manually via the UI's "Sync Allocations" action or the SDK's `investAllReservesIxs` / `investSingleReserveIxs` methods. The underlying vault operation is `invest`. It compares the reserve's current allocation with its weight/cap target and then either: * deposits vault liquidity into the reserve if the reserve is under target, or * withdraws available liquidity from the reserve back into the vault if the reserve is over target. ### Partial moves with `invest_with_max_amount` `invest_with_max_amount` is a capped variant of `invest`: weights and allocation caps still determine whether funds move into or out of the reserve, but the caller can cap the amount of liquidity moved toward that target. Use it when the full target move is larger than the liquidity currently available, or when you want to move funds in controlled chunks. This instruction is available on-chain and in `@kamino-finance/klend-sdk` `9.1.0+` as `investSingleReserveWithMaxAmountIxs`. The SDK argument is `maxAmountLamports`: the maximum vault-token lamports to move in or out of the selected reserve. **Example — partial rebalance when one reserve cannot fully deallocate:** * Vault has two allocations, 50% each, with 1M total tokens: 500K in reserve 1 and 500K in reserve 2. * The manager changes weights to reserve 1: 90%, reserve 2: 10%. * The target move is to withdraw 400K from reserve 2, but reserve 2 only has 300K available. * Call `invest_with_max_amount` on reserve 2 with `max_amount = 300K`. This withdraws 300K from reserve 2 into the vault. * Call `invest_with_max_amount` on reserve 1 with `max_amount = 300K`. This deposits that 300K into reserve 1. * Final state: reserve 1 has 800K and reserve 2 has 200K. The vault is closer to the 900K / 100K target, and reserve 2 utilization may rise to 100%, incentivizing borrowers to repay so more liquidity becomes withdrawable. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager, KaminoVault, getMedianSlotDurationInMsFromLastEpochs, } from '@kamino-finance/klend-sdk'; import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; const payer = await parseKeypairFile('/path/to/payer.json'); const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); const kaminoManager = new KaminoManager(rpc, slotDuration); const vault = new KaminoVault(rpc, address('')); const reserveAddress = address(''); const vaultState = await vault.getState(); const vaultReservesMap = await kaminoManager.loadVaultReserves(vaultState); const reserve = vaultReservesMap.get(reserveAddress); if (!reserve) { throw new Error(`Reserve ${reserveAddress} not found in vault allocations`); } const maxAmountLamports = '300000000000'; // 300,000 USDC with 6 decimals const cappedInvestIxs = await kaminoManager.investSingleReserveWithMaxAmountIxs( payer, vault, { address: reserveAddress, state: reserve.state }, maxAmountLamports, vaultReservesMap, ); ``` If `cappedInvestIxs` is empty, the computed move was below the vault's `minInvestAmount` or there was no eligible liquidity to move. Sync may still not reach the exact target if the reserve has no available liquidity left after the capped move. When you need to exit capital that is not currently withdrawable, use the [withdrawal queue](/curators/vaults/concepts/liquidity-and-withdrawals). ## What's next > [card] [Allocations (concept)](/curators/vaults/concepts/allocations) > > The model behind weights, caps, types, and priority. > [card] [Configure fixed-rate allocations](/curators/vaults/guides/configure-fixed-rate-allocations) > > The focused step-by-step for adding an FR allocation, with FR-specific parameter choices. # Configure farms Source: https://docs.kamino.com/curators/vaults/guides/configure-farms Post-creation farm setup — only needed if your vault was created without farms > [!NOTE] > > **This is a post-creation fallback guide, not a primary setup task.** When you create a vault via the SDK (`createVaultIxs`) or the UI, the Vault Farm and Insurance Pool farm are created automatically as part of the creation flow — see [Create a vault](/curators/vaults/guides/create-a-vault). You only need this guide if you created your vault via the CLI (which doesn't currently support farm creation) or otherwise skipped farm setup during init. The Autocompound Farm is the exception — it's always configured separately, currently UI-only. Every vault supports three farms. This guide walks through creating and attaching each one post-creation. For the model — what each farm does and how rewards interact with vault accounting — read [Yield & fees → Farm rewards](/curators/vaults/concepts/yield-and-fees#farm-rewards). ## The three farms | Farm | Role | SDK support | | - | - | - | | **Vault Farm** | Distributes any reward token to depositors (kToken holders). One per vault. | Available | | **Insurance Pool farm** (`FirstLossCapitalFarm`) | Holds your locked capital that absorbs losses before depositors. See [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) for the full setup. | Available | | **Autocompound Farm** | Distributes rewards in the vault's deposit token, automatically compounding into vault positions. | UI only — SDK support coming | If you create a vault via the SDK using `createVaultIxs`, the Vault Farm and Insurance Pool farm are created automatically. If you used the UI or CLI, you'll need to create them post-hoc. > [!WARNING] > > Farm creation is irreversible. The farm public key becomes immutable after creation, and farm authority transfers to the protocol. ## Create farms post-vault-creation If your vault was created without farms (UI or CLI path), use the SDK to create them. > [tab] SDK > > The Vault Farm and Insurance Pool farm follow the same three-transaction pattern: setup → update → register on the vault. > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > > const adminSigner = await parseKeypairFile('/path/to/your/keypair.json'); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoManager = new KaminoManager(rpc, slotDuration); > > const vault = new KaminoVault(rpc, address('')); > > // Helper for build/sign/send > async function send(ixs) { > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > tx => setTransactionMessageFeePayerSigner(adminSigner, tx), > tx => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > tx => appendTransactionMessageInstructions(ixs, tx), > ), > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > skipPreflight: true, > }); > } > > // Create farm account and configure farm-side settings > const { farm, setupFarmIxs, updateFarmIxs } = > await kaminoManager.createVaultFarmIxs(adminSigner, vault); > > await send(setupFarmIxs); // creates the farm account > await send(updateFarmIxs); // configures farm-side settings > > // Register the farm on the vault > // — for the Vault Farm: > const { updateVaultConfigIx } = await kaminoManager.updateVaultFarmIxs(vault, farm.address); > // — OR for the Insurance Pool farm: > // const { updateVaultConfigIx } = > // await kaminoManager.updateVaultFirstLossCapitalFarmIxs(vault, farm.address); > > await send([updateVaultConfigIx]); > console.log('Farm attached:', farm.address); > ``` > > ### Vault Farm > > After registration, you fund the farm with the reward token. Depositors claim proportional to their kToken holdings over the reward period. The farm has a **cooldown period** that prevents instant deposit-claim-withdraw cycling — set this when configuring reward distribution. > > ### Insurance Pool farm > > After registration, configure the deposit token and lockup period (the lockup is a fixed 30 days for normal withdrawals — see [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) for the full setup including the 2-of-2 emergency withdrawal flow). > > ### Autocompound Farm > > Configure the Autocompound Farm via the UI for now; SDK support is on the way. > [tab] UI > > The UI walks through farm creation step-by-step. Open your vault's farms / rewards section on `manage.kamino.com` and follow the prompts. The Autocompound Farm is configured via the same surface. > [tab] CLI > > > [!NOTE] > > > > Farm creation and management is not currently available via the Kamino CLI. Use the SDK or UI. ## Read incentive data The vault overview includes farm incentive data across all three farms. ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address } from '@solana/kit'; import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); const vault = new KaminoVault(rpc, address('')); const kaminoManager = new KaminoManager(rpc); const overview = await kaminoManager.getVaultOverview(vault, new Decimal(1.0)); console.log('Vault farm:', overview.vaultFarmIncentives); console.log('Reserve farms:', overview.reservesFarmsIncentives); console.log('Delegated farms:', overview.delegatedFarmIncentives); ``` ## What's next > [card] [Yield & fees](/curators/vaults/concepts/yield-and-fees) > > The yield and fee model, including how farms compose with interest yield. > [card] [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) > > The full Insurance Pool setup, including emergency withdrawal configuration. # Configure fixed-rate allocations Source: https://docs.kamino.com/curators/vaults/guides/configure-fixed-rate-allocations Add and manage allocations into fixed-rate reserves — UI, SDK, and CLI walkthroughs with FR-specific parameter choices This guide is the focused walkthrough for adding a vault allocation into a fixed-rate reserve. The general allocation primitives (weights, caps, sync, the Standard vs. Conditional choice) live in [Concepts → Allocations](/curators/vaults/concepts/allocations) and [Configure allocations](/curators/vaults/guides/configure-allocations); the FR-specific application of those primitives is in [Fixed Rates → Allocations](/curators/vaults/fixed-rates/allocations). This page assumes you've read those and are ready to act. ## Before you start You'll need: * An existing vault for the deposit token of the FR reserve (e.g. a USDC vault to allocate into a `USDC 5.5% 3M` reserve). * The address of the fixed-rate reserve. Find it via the Manage UI's reserve picker, or via [Markets → Fixed Rates](/curators/markets/fixed-rates) for the market manager who created it. * A decision on Standard vs. Conditional (see below). * For SDK or CLI: your admin keypair file path. ## Decide on Standard vs. Conditional Both work for FR reserves. The choice is about capital efficiency vs. visibility, not technical compatibility. | Pick | When | | - | - | | **Conditional** | Default for most FR exposure. Capital stays in floating reserves earning variable yield until borrow demand triggers an atomic deployment into the FR reserve. | | **Standard** | When you want capital visibly committed and immediately available for direct borrows — typically for seeding a new FR reserve or anchoring a strategic position. | | **Both on the same reserve** | A Standard base layer of visible liquidity plus Conditional capacity behind it. | For the full reasoning, see [Fixed Rates → Allocations → Why Conditional is the default for FR](/curators/vaults/fixed-rates/allocations#why-conditional-is-the-default-for-fr). ## Parameter cheat sheet Four parameter choices change for FR reserves vs. floating ones: | Parameter | Conditional | Standard | | - | - | - | | `allocation-type` | `Conditional` | `Standard` | | `allocation-weight` | `0` (weight is ignored) | Relative integer like any other Standard allocation | | `allocation-cap` | The **binding limit** — maximum the vault will deploy if matched | Hard ceiling on top of weight | | `priority` | `0` (default) — only set if you want this Conditional fill to draw from higher-priority sources | `0` (default) — raise to protect this Standard allocation from being drawn down by Conditional fills on other FR reserves | For the priority rule and worked examples, see [Concepts → Allocations → Priority](/curators/vaults/concepts/allocations#priority). ## Walkthrough > [tab] UI > > **1. Open the Allocations tab** > > Navigate to your vault on `kamino.com/curators/vaults` and open the **Allocations** tab. > > **2. Click Add Reserve** > > Opens the allocation configuration form. > > **3. Select the market** > > Pick the market that hosts the fixed-rate reserve (e.g. SOL/BTC Market). > > **4. Select the fixed-rate reserve** > > The reserve picker lists floating and fixed-rate reserves side by side. Fixed-rate reserves are tagged with their rate, term, and reserve type — for example `USDC 5.5% 3M`. Pick the cell of the rate grid you're targeting. > > **5. Toggle Conditional Allocation** > > On for Conditional (capital stays in floating until matched). Off for Standard (capital deploys immediately). > > **6. Set the cap** > > The maximum tokens the vault is willing to deploy into this reserve. For Conditional, this is the binding limit. For Standard, a hard ceiling. > > **7. Set weight (Standard only)** > > Skip for Conditional — the field is ignored. For Standard, set the relative weight against your other Standard allocations. > > **8. Set priority** > > Default `0`. Only adjust if you're using priority to protect specific source reserves (see Parameter cheat sheet above). > > **9. Submit** > > Sign with your admin wallet, or generate a Squads proposal if the vault is multisig-controlled. > [tab] SDK > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > KaminoVault, > Reserve, > ReserveAllocationConfig, > ReserveType, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import { Decimal } from 'decimal.js'; > > const adminSigner = await parseKeypairFile('/path/to/your/keypair.json'); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoManager = new KaminoManager(rpc, slotDuration); > > const vault = new KaminoVault(rpc, address('')); > const fixedRateReserveAddress = address(''); > > const reserveState = await Reserve.fetch(rpc, fixedRateReserveAddress); > const reserveWithAddress = { address: fixedRateReserveAddress, state: reserveState! }; > > // Conditional — default for FR > const conditionalConfig = new ReserveAllocationConfig( > reserveWithAddress, > 0, // weight ignored for Conditional > new Decimal('10000000'), // cap — binding limit (10M tokens) > new ReserveType.Conditional(), > 0, // priority > ); > > // OR — Standard, when you want visible committed liquidity > const standardConfig = new ReserveAllocationConfig( > reserveWithAddress, > 100, // weight relative to other Standard allocations > new Decimal('5000000'), // cap — hard ceiling on top of weight > new ReserveType.Standard(), > 0, // priority > ); > > const { updateReserveAllocationIx } = > await kaminoManager.updateVaultReserveAllocationIxs(vault, conditionalConfig, adminSigner); > > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > tx => setTransactionMessageFeePayerSigner(adminSigner, tx), > tx => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > tx => appendTransactionMessageInstructions([updateReserveAllocationIx], tx), > ), > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > skipPreflight: true, > }); > ``` > > The same `updateVaultReserveAllocationIxs` method handles both **adding a new reserve** and **updating an existing one** — the SDK detects the difference. To **mix Standard + Conditional on the same reserve**, call the method twice with the two configs. > [tab] CLI > > > [!NOTE] > > > > Complete the [CLI installation guide](/build/cli/installation-setup) first. Commands require `.env` with `ADMIN` and `RPC` configured. > > **Conditional allocation** (recommended default for FR): > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-reserve-allocation \ > --vault \ > --reserve \ > --allocation-weight 0 \ > --allocation-cap 10000000 \ > --allocation-type Conditional \ > --priority 0 \ > --mode simulate > ``` > > **Standard allocation** (for visible committed liquidity): > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-reserve-allocation \ > --vault \ > --reserve \ > --allocation-weight 100 \ > --allocation-cap 5000000 \ > --allocation-type Standard \ > --priority 0 \ > --mode simulate > ``` > > Always run `--mode simulate` first to inspect the resulting state. Then re-run with `--mode execute`, or `--mode multisig --multisig ` to emit a Base58 payload for [Squads](https://squads.so). > > **Mixing Standard + Conditional on the same reserve**: run the command twice with the two `--allocation-type` values. The vault will hold both allocations against the same reserve. ## Verify After submission lands: * **UI.** The new allocation appears in the Allocations tab with the reserve name, type tag (Standard / Conditional), cap, weight, and priority. * **SDK.** `vault.getVaultAllocations()` returns a map that includes the new reserve. See [Configure allocations → Read current allocations](/curators/vaults/guides/configure-allocations#read-current-allocations). * **API.** `GET /kvaults/vaults/{pubkey}` includes the allocation strategy. See [Allocation data](/curators/data/allocation-data). A Conditional allocation won't show capital deployed into the FR reserve until borrow demand triggers a fill — that's expected. The vault's actual position lives in your Standard floating allocations until then. ## After it lands * **Watch for fills.** If the FR reserve attracts demand, your Conditional cap may be drawn down to satisfy it. The fill is atomic — see [Lifecycle → The fill](/curators/vaults/fixed-rates/lifecycle#the-fill). * **Adjust caps responsively.** Raise to expose more capital, lower to commit less. Conditional caps can be dropped to `0` to disable the signal entirely. * **Plan exits ahead of maturity.** Once a Conditional fill lands and is committed to a borrow, exits go through the [withdrawal queue](/curators/vaults/concepts/liquidity-and-withdrawals#the-withdrawal-queue). Queue early if you want predictable exit timing — see [Lifecycle → Exiting via the withdrawal queue](/curators/vaults/fixed-rates/lifecycle#exiting-via-the-withdrawal-queue). ## What's next > [card] [Fixed Rates → Allocations](/curators/vaults/fixed-rates/allocations) > > The FR-specific application of Standard vs. Conditional with priority worked examples. > [card] [Fixed Rates → Lifecycle](/curators/vaults/fixed-rates/lifecycle) > > What your capital experiences from fill through term, rollover, and queued exits. > [card] [Fixed Rates → Strategy](/curators/vaults/fixed-rates/strategy) > > Postures, sizing, monitoring, and a worked \$100M vault example. > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > The general allocation workflow (floating reserves and the unallocated buffer). # Create a vault Source: https://docs.kamino.com/curators/vaults/guides/create-a-vault Deploy a new Kamino vault — UI walkthrough plus SDK and CLI alternatives, with a complete post-creation checklist This guide walks through deploying a new vault and completing the post-creation steps that make it production-ready. The conceptual background is in [How vaults work](/curators/vaults/concepts/how-vaults-work); this page is purely operational. ## Before you start You'll need: * A funded wallet with at least 1,000 lamports of the deposit token (used as the bootstrapping deposit at creation). * The mint address of the deposit token (e.g. `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` for USDC). * Decisions on: vault name, receipt-token ticker suffix, fee structure, operational parameters. For SDK or CLI use, also have your admin keypair file path ready. ## Choose your interface > [tab] UI > > ## Create via kamino.com/curators/vaults > > **1. Configure required parameters** > > Set the vault name, deposit token, receipt token name and ticker suffix. > > ![Create Vault modal](https://mintcdn.com/kamino-3d73a151/0BZCvX0581phKD7f/images/curators/vaults/create-vault-step-1.webp?fit=max\&auto=format\&n=0BZCvX0581phKD7f\&q=85\&s=160fba860dab87c752958165822a0e1d) > > | Parameter | Notes | > | - | - | > | Vault Name | Max 40 characters; editable post-creation | > | Deposit Token | Immutable; determines available reserves for allocation | > | Receipt Token Ticker | Format `kv[SYMBOL]-[SUFFIX]`; the prefix is immutable, the suffix is editable post-creation | > | Receipt Token Name | Format `kVault [SUFFIX] [NAME]`; max 32 chars total | > > **2. Set fees** > > Configure performance fee and AUM fee. Both default to 0% and are editable post-creation. See [Yield & fees](/curators/vaults/concepts/yield-and-fees#manager-fees) for the model. > > ![Fees Settings section](https://mintcdn.com/kamino-3d73a151/0BZCvX0581phKD7f/images/curators/vaults/create-vault-step-2.webp?fit=max\&auto=format\&n=0BZCvX0581phKD7f\&q=85\&s=c3e6c4af5586025afe6a54a77fb3d423) > > **3. Configure operational parameters (optional)** > > Set minimum deposit/withdraw/invest amounts, invest delay, withdrawal penalty, and crank fund fee. All are editable post-creation; the defaults are sensible. See the [parameter reference](/curators/reference/parameters) for definitions. > > ![Advanced Settings section](https://mintcdn.com/kamino-3d73a151/0BZCvX0581phKD7f/images/curators/vaults/create-vault-step-3.webp?fit=max\&auto=format\&n=0BZCvX0581phKD7f\&q=85\&s=f06a1870b16e09147bdcd3e1d1c23852) > > **4. Approved Reserves Only (optional)** > > The Create New Vault modal includes an **Approved Reserves Only** toggle. Enabling it activates both Whitelisted Reserves flags as part of the creation transaction — your vault ships with the smart-contract-level allocation restriction in place. **This is irreversible.** See [Concepts → Risk primitives](/curators/vaults/concepts/risk-primitives#whitelisted-reserves) before flipping it. If you don't enable it here, you can do so later via [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves). > > **5. Submit the creation transaction** > > Sign with the wallet that holds the bootstrapping deposit. The vault address is displayed after the transaction lands. > > **6. Complete post-creation setup** > > Continue to the [post-creation checklist](#post-creation-checklist) below. > [tab] SDK > > ## Create via TypeScript SDK > > > [!NOTE] > > > > The full vault creation flow including farm setup runs in three transactions. Use a private RPC endpoint for production — public RPCs are rate-limited. > > ```typescript theme={"theme":"css-variables"} > import { > createSolanaRpc, > createSolanaRpcSubscriptions, > address, > pipe, > createTransactionMessage, > setTransactionMessageFeePayerSigner, > setTransactionMessageLifetimeUsingBlockhash, > appendTransactionMessageInstructions, > signTransactionMessageWithSigners, > sendAndConfirmTransactionFactory, > } from '@solana/kit'; > import { > KaminoManager, > KaminoVaultConfig, > getMedianSlotDurationInMsFromLastEpochs, > } from '@kamino-finance/klend-sdk'; > import { parseKeypairFile } from '@kamino-finance/klend-sdk/dist/utils/signer.js'; > import { TOKEN_PROGRAM_ADDRESS } from '@solana-program/token'; > import { Decimal } from 'decimal.js'; > > const adminSigner = await parseKeypairFile('/path/to/your/keypair.json'); > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const rpcSubscriptions = createSolanaRpcSubscriptions('wss://api.mainnet-beta.solana.com'); > > const slotDuration = await getMedianSlotDurationInMsFromLastEpochs(); > const kaminoManager = new KaminoManager(rpc, slotDuration); > > // 1. Configure the vault > const vaultConfig = new KaminoVaultConfig({ > admin: adminSigner, > tokenMint: address('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), // USDC > tokenMintProgramId: TOKEN_PROGRAM_ADDRESS, > performanceFeeRatePercentage: new Decimal(15.0), > managementFeeRatePercentage: new Decimal(2.0), > name: 'MyVault', > vaultTokenSymbol: 'USDC', > vaultTokenName: 'MyVaultToken', > // Operational params — defaults shown > minDepositAmount: 1000, > minWithdrawAmount: 10, > withdrawalPenaltyBps: 1, > withdrawalPenaltyLamports: 1, > crankFundFeePerReserve: 1, > }); > > // 2. Generate creation instructions > const { vault: vaultSigner, initVaultIxs: instructions } = > await kaminoManager.createVaultIxs(vaultConfig); > > // 3. Helper to build, sign, and send a transaction > async function send(ixs) { > const { value: blockhash } = await rpc.getLatestBlockhash({ commitment: 'finalized' }).send(); > const signed = await signTransactionMessageWithSigners( > pipe( > createTransactionMessage({ version: 0 }), > tx => setTransactionMessageFeePayerSigner(adminSigner, tx), > tx => setTransactionMessageLifetimeUsingBlockhash(blockhash, tx), > tx => appendTransactionMessageInstructions(ixs, tx), > ), > ); > await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signed, { > commitment: 'confirmed', > skipPreflight: true, > }); > } > > // 4. Tx 1 — create the vault and register farms > await send([ > ...instructions.createAtaIfNeededIxs, > ...instructions.initVaultIxs, > instructions.createLUTIx, > instructions.initSharesMetadataIx, > ...instructions.setFarmToVaultIxs, > ]); > console.log('Vault created:', vaultSigner.address); > > // 4b. (Optional) Enable Whitelisted Reserves as part of the create flow. > // This is irreversible — see Concepts → Risk primitives before doing it. > // > // const allocIx = await kaminoManager.updateVaultAllowAllocationsInWhitelistedReservesOnlyIxs( > // new KaminoVault(rpc, vaultSigner.address), > // true, > // ); > // const investIx = await kaminoManager.updateVaultAllowInvestInWhitelistedReservesOnlyIxs( > // new KaminoVault(rpc, vaultSigner.address), > // true, > // ); > // await send([allocIx, investIx]); > > // 5. Tx 2 — create and configure farms (Vault Farm + Insurance Pool farm) > for (const farm of instructions.createVaultFarms) { > await send(farm.setupFarmIxs); > await send(farm.updateFarmIxs); > } > > // 6. Tx 3 — populate the lookup table (optional, optimizes future tx sizes) > await new Promise(r => setTimeout(r, 2000)); // wait for state to settle > await send(instructions.populateLUTIxs); > ``` > > **What `createVaultIxs` produces:** > > * `initVaultIxs` — vault account creation + initial config > * `createLUTIx` + `initSharesMetadataIx` — lookup table and receipt-token metadata > * `setFarmToVaultIxs` — registers the Vault Farm and Insurance Pool farm addresses on the vault > * `createVaultFarms` — array of farm setup instructions, run sequentially > * `populateLUTIxs` — populates the lookup table > > The Autocompound Farm is configurable post-creation via the UI; SDK support is on the way. > > Continue to the [post-creation checklist](#post-creation-checklist). > [tab] CLI > > ## Create via Kamino CLI > > > [!NOTE] > > > > Complete the [CLI installation guide](/build/cli/installation-setup) first. Commands require a `.env` file with `ADMIN` (path to vault owner keypair) and `RPC` configured. > > The CLI's `create-vault` command creates a vault with default settings. Use the SDK or UI for advanced configuration during creation. > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager create-vault \ > --mint \ > --mode execute > ``` > > Replace `` with the deposit token mint (e.g. `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` for USDC). Save the vault address from the output — you'll need it for every subsequent command. > > > [!WARNING] > > > > For testing, add `--staging` to use the staging program ID. Never use `--staging` against mainnet vaults. > > > [!NOTE] > > > > **Whitelisted Reserves cannot be enabled via the CLI's `create-vault` command.** If you want this protection (recommended for production), enable it as a post-creation step using the SDK or UI — see [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves). > > Continue to the [post-creation checklist](#post-creation-checklist). ## Post-creation checklist After the vault is created, complete these steps before it's production-ready. Run them in order. **1. Transfer admin to multisig** Move vault admin to a Squads multisig **first**, before any subsequent state-changing operations. Once transferred, every operation below flows through Squads as a proposal — which is the production model. See [Transfer admin to multisig](/curators/vaults/guides/transfer-admin). **2. Configure allocations** Without allocations, the vault has nowhere to deploy capital. Add at least one reserve. See [Configure allocations](/curators/vaults/guides/configure-allocations). **3. Configure fixed-rate allocations (if applicable)** If your strategy includes fixed-rate exposure, add allocations into specific FR reserves. See [Configure fixed-rate allocations](/curators/vaults/guides/configure-fixed-rate-allocations). Skip if your vault is floating-only. **4. Enable Whitelisted Reserves** Smart-contract-level constraint preventing allocation to unverified reserves. Required for Kamino UI listing. Skip if you already enabled it in the creation flow above. See [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves). **5. Set up the Insurance Pool** Lock your skin-in-the-game capital and trigger Kamino's match (up to \$250K). Required for Kamino UI listing. See [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool). **6. Verify farms (only if your create path missed them)** The Vault Farm and Insurance Pool farm are normally created during initialization on the SDK and UI paths. If you used the CLI or otherwise skipped farm creation, see [Configure farms](/curators/vaults/guides/configure-farms). ## What's next > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > Set how the vault distributes capital across reserves. > [card] [Parameters reference](/curators/reference/parameters) > > Complete reference for every vault parameter. # Enable permissioning Source: https://docs.kamino.com/curators/vaults/guides/enable-permissioning Switch your vault into permissioned mode and manage the depositor allowlist via the kperm program This guide walks through switching a vault into permissioned mode and managing the depositor allowlist. For the conceptual model — the cosigner pattern, the on-chain pieces, and what each operation gates — read [Permissioned vaults](/curators/vaults/concepts/permissioned-vaults) first. > [!NOTE] > > kperm is live for Kamino lending markets today. Vault-side support ships with the next kvault release; the SDK, CLI, and on-chain mechanics described here mirror the existing [permissioned markets](/curators/markets/permissioned-markets) flow. ## Before you start You'll need: * An existing vault. See [Create a vault](/curators/vaults/guides/create-a-vault). * The vault admin keypair, or — in production — a Squads multisig with the admin role. See [Transfer admin to multisig](/curators/vaults/guides/transfer-admin). * A list of wallet addresses to whitelist, or an automated source feeding them (e.g. a KYC backend that signals verified wallets to your service). ## Curator workflow **1. Decide what to permission** For most vaults, the answer is `DEPOSIT`. That gates entry; withdrawals remain open so depositors can always redeem their shares. Add `KEYRING` if your gating logic lives in an external policy program. You can change the gated set later by re-running the update with a different bitfield. **2. Switch the vault into permissioned mode** Set `permissioning_authority` to the Vault Permissioner PDA and `permissioned_ops` to the chosen bitfield. From this point, kvault requires the kperm cosigner for every gated action. **3. Whitelist users** Use the SDK, CLI, or REST API (see tabs below). All three issue the same `init_user_permission` (first grant) or `update_user_permission` (subsequent grants) instruction on-chain. **4. Test the rejection path** Send a deposit transaction from an un-whitelisted wallet on staging and confirm it reverts. Add that wallet to the allowlist and retry — it should succeed. > [tab] SDK > > ## Configure permissioning via SDK > > The kperm-aware methods live in `@kamino-finance/klend-sdk` alongside `KaminoManager` and `KaminoVault`. > > ### Curator: switch the vault into permissioned mode > > ```typescript theme={"theme":"css-variables"} > import { > KaminoManager, > KaminoVault, > DEFAULT_RECENT_SLOT_DURATION_MS, > PermissionedOp, > getVaultPermissionerPda, > } from '@kamino-finance/klend-sdk'; > import { PROGRAM_ID as KPERM_PROGRAM_ID } from '@kamino-finance/klend-sdk/dist/@codegen/kperm/programId'; > import { address } from '@solana/kit'; > > const kaminoManager = new KaminoManager(rpc, DEFAULT_RECENT_SLOT_DURATION_MS); > > const vaultAddress = address(''); > const vault = new KaminoVault(rpc, vaultAddress); > > const vaultPermissioner = await getVaultPermissionerPda(vaultAddress, KPERM_PROGRAM_ID); > const permissionedOpsBitfield = PermissionedOp.fromString('DEPOSIT'); > > const ixs = await kaminoManager.updateVaultPermissionIxs( > adminSigner, > vault, > vaultPermissioner, > permissionedOpsBitfield, > ); > // submit each ix in order > ``` > > `PermissionedOp.fromString` accepts pipe-separated names: `'DEPOSIT'`, `'DEPOSIT|KEYRING'`, etc. > > ### Whitelist a user (initial grant or update) > > ```typescript theme={"theme":"css-variables"} > import { initPermissionIx, updatePermissionIx, getPermissionPda } from '@kamino-finance/klend-sdk'; > import { UserPermission } from '@kamino-finance/klend-sdk/dist/@codegen/kperm/accounts'; > > const userAddress = address(''); > const grantedOps = PermissionedOp.fromString('DEPOSIT'); > > const userPermissionPda = await getPermissionPda(vaultAddress, userAddress, KPERM_PROGRAM_ID); > const existing = await UserPermission.fetch(rpc, userPermissionPda, KPERM_PROGRAM_ID); > > const ix = existing > ? await updatePermissionIx(globalAdminSigner, vaultAddress, userAddress, grantedOps, /* overwrite */ false) > : await initPermissionIx(globalAdminSigner, vaultAddress, userAddress, grantedOps); > // Sign and submit with the global admin's signer > ``` > > `updatePermissionIx` takes an `overwrite` flag: `true` replaces the user's allowed ops with `grantedOps`; `false` bitwise-ORs `grantedOps` into the existing set. > > ### Revoke a user > > ```typescript theme={"theme":"css-variables"} > import { removePermissionIx } from '@kamino-finance/klend-sdk'; > > const ix = await removePermissionIx(globalAdminSigner, vaultAddress, userAddress, KPERM_PROGRAM_ID); > // Sign and submit > ``` > > The `UserPermission` account stays on-chain with `permissioned_ops = 0`. Re-granting later avoids paying rent again. > > ### User flow: deposit into a permissioned vault > > The standard vault deposit builders detect when the target vault is permissioned and automatically wrap the produced kvault instructions with `permissioned_fwd_to_kvault`. Apps integrating against a permissioned vault continue to call the standard deposit builders — the SDK handles the wrap. > > For instructions built outside of the standard builders, wrap manually: > > ```typescript theme={"theme":"css-variables"} > import { permissionedFwdToKvault } from '@kamino-finance/klend-sdk/dist/@codegen/kperm/instructions'; > import { KVAULT_PROGRAM_ID, getPermissionPda } from '@kamino-finance/klend-sdk'; > > const userPermissionPda = await getPermissionPda(vaultAddress, userSigner.address, KPERM_PROGRAM_ID); > > const wrapped = permissionedFwdToKvault( > { ixData: kvaultIx.data }, > { > user: userSigner, > targetProgram: KVAULT_PROGRAM_ID, > userPermission: userPermissionPda, > }, > /* remainingAccounts = */ [...kvaultIx.accounts], > KPERM_PROGRAM_ID, > ); > // Submit `wrapped` as the user's transaction > ``` > [tab] API > > ## Programmatic whitelisting via REST API > > Kamino exposes a REST API that issues the on-chain `init_user_permission`, `update_user_permission`, and `remove_user_permission` instructions on the curator's behalf. Intended use: automated onboarding — KYC provider attests → backend marks the user verified → backend calls the API → the wallet is allowed on the target vault within seconds. > > The API takes the same inputs as the SDK and CLI: > > * Vault address > * User wallet address > * Operations to grant (any combination of `DEPOSIT`, `KEYRING`) > > Signing is handled by the kperm global admin which the API operates against on your behalf for whitelisted vaults. > > > [!NOTE] > > > > API base URL, authentication, and exact request schemas are not yet publicly documented. Coordinate with the Kamino team to obtain access for your vault. > [tab] Kamino CLI > > ## Configure permissioning via CLI > > ### Switch the vault into permissioned mode > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-permission \ > --vault \ > --operations "DEPOSIT" \ > --mode execute > ``` > > In one call, the command sets `permissioning_authority` to the Vault Permissioner PDA and sets `permissioned_ops` to the bitfield parsed from `--operations`. Operations are pipe-separated and case-insensitive: `DEPOSIT`, `KEYRING`. > > To change the gated set later, re-run with the desired bitfield. > > ### Whitelist a user > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager add-vault-permission \ > --vault \ > --user \ > --operations "DEPOSIT" \ > --mode execute > ``` > > The CLI auto-detects whether the user's `UserPermission` account already exists. If it does, the operations are merged via bitwise OR. If it doesn't, the account is created with the specified ops. > > ### Revoke a user > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager remove-vault-permission \ > --vault \ > --user \ > --mode execute > ``` > > Sets the user's `permissioned_ops` to `0`. The user can no longer take any gated action until re-whitelisted. ## On-chain accounts | Account | Program | PDA seeds | Stores | | - | - | - | - | | `VaultState` | kvault | (vault account) | `permissioning_authority` (Vault Permissioner PDA), `permissioned_ops` (u64 bitfield) | | `UserPermission` | kperm | `["permission", vault, user]` | `vault`, `user`, `permissioned_ops`, cached `vaultPermissioner`, bumps | | Vault Permissioner | kperm | `["vault", vault]` | Authority PDA the kperm program signs as when CPI'ing into kvault (signature-only; the PDA stores no data) | | `GlobalConfig` | kperm | `["global_config"]` | `globalAdmin`, `pendingAdmin` for the kperm program | Program ID for kperm: `KPermUZsf9tu4cSd9LNcMojCbiHfdbJXv9dr3pAUzz1`. ## Operational considerations | Topic | Detail | | - | - | | Performance | Permissioned actions add one CPI hop (kperm → kvault). Compute-unit cost rises modestly; users may need to bump priority fees on busy slots | | Multisig | When the vault admin is a Squads multisig, `update-vault-permission` becomes a multisig proposal subject to the standard threshold and review flow | | Whitelist authority | The kperm `globalAdmin` is shared across markets and vaults. For most curator vaults, a Kamino-controlled admin holds it; the curator delegates whitelisting to the REST API. For curators that want full sovereignty, coordinate with the team to use a curator-owned admin | | Composability | Permissioning is enforced at the kvault-instruction boundary. Programs that integrate with kvault by composing instructions (third-party UIs, aggregators) must use `permissioned_fwd_to_kvault` to interact with a permissioned vault | | Exit semantics | Withdrawals are always open. To shape the exit flow, use the standard vault [liquidity and withdrawal](/curators/vaults/concepts/liquidity-and-withdrawals) primitives | | Stacking with Whitelisted Reserves | Permissioning controls *who* deposits; [Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) controls *where* capital flows. Both can be enabled together for the strongest institutional configuration | ## Reference * [Permissioned vaults](/curators/vaults/concepts/permissioned-vaults) — conceptual model * [Permissioned markets](/curators/markets/permissioned-markets) — equivalent feature applied to lending markets * [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) — protocol-level reserve restriction (independent of permissioning) # Enable Whitelisted Reserves Source: https://docs.kamino.com/curators/vaults/guides/enable-whitelisted-reserves Restrict your vault to allocate only into Kamino-verified reserves at the smart contract level Whitelisted Reserves is the smart-contract-level protection that constrains where your vault can deploy capital. Once enabled, even a compromised admin key cannot direct vault funds into unvetted markets — the constraint is enforced by the program itself, not by your operational security. For the conceptual treatment of why this exists and what each flag controls, read [Risk primitives → Whitelisted Reserves](/curators/vaults/concepts/risk-primitives#whitelisted-reserves) first. This page is the operational walkthrough. > [!WARNING] > > **Enabling Whitelisted Reserves is one-way.** Both flags can only be set to `true`. Once enabled, they cannot be reverted — enforced at the smart contract level. Be deliberate. ## What you're enabling Two on-chain flags — `AllowAllocationsInWhitelistedReservesOnly` (controls new allocations) and `AllowInvestInWhitelistedReservesOnly` (controls new investment) — explained in [Concepts → Risk primitives → The two flags](/curators/vaults/concepts/risk-primitives#the-two-flags). Enable both: one alone leaves a gap that the second closes. Both together is what's required for Kamino UI listing. ## Setup > [tab] UI > > **1. Open vault settings** > > Navigate to your vault on `kamino.com/curators/vaults` and open the **Settings** tab. > > **2. Enable AllowAllocationsInWhitelistedReservesOnly** > > Toggle on. Confirm the transaction. Reminder: this is irreversible. > > **3. Enable AllowInvestInWhitelistedReservesOnly** > > Toggle on. Confirm the transaction. Also irreversible. > [tab] SDK > > ```typescript theme={"theme":"css-variables"} > import { createSolanaRpc, address } from '@solana/kit'; > import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk'; > > const rpc = createSolanaRpc('https://api.mainnet-beta.solana.com'); > const vault = new KaminoVault(rpc, address('')); > const kaminoManager = new KaminoManager(rpc); > > // Enable allocation whitelisting > const allocIx = await kaminoManager.updateVaultAllowAllocationsInWhitelistedReservesOnlyIxs( > vault, > true, > ); > > // Enable investment whitelisting > const investIx = await kaminoManager.updateVaultAllowInvestInWhitelistedReservesOnlyIxs( > vault, > true, > ); > > // Build and send each as a separate transaction with the standard @solana/kit pipe. > // Multisig vaults: route through Squads. > ``` > [tab] CLI > > > [!NOTE] > > > > Whitelisted Reserves enablement is not currently exposed via the CLI as a dedicated command. Use the UI or SDK. ## What stays unchanged * **Withdrawals** are always permitted. You can de-allocate from any reserve at any time, and depositors can enter or exit the vault at any time subject to available liquidity. * **The whitelist itself** is managed by Kamino at the protocol level. Curators activate enforcement on their vault but cannot add or remove reserves from the whitelist. * **Existing allocations** to non-whitelisted reserves are not removed by enabling the flags. They remain in your allocation list but new investment is blocked. Plan to remove them via [Configure allocations](/curators/vaults/guides/configure-allocations) before enabling if you want a clean state. ## Best practices * **Enable both flags.** One alone leaves a gap. Both together is the supported configuration. * **Enable during vault setup.** Before depositors enter — strongest signal and a prerequisite for UI listing. * **Pair with the Insurance Pool.** Whitelisted Reserves protects against where capital goes; the [Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) protects against what happens if something goes wrong. Together they represent the highest trust configuration. ## What's next > [card] [Risk primitives](/curators/vaults/concepts/risk-primitives) > > The model behind both protections. > [card] [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) > > Lock the loss backstop alongside Whitelisted Reserves. # Set up the Insurance Pool Source: https://docs.kamino.com/curators/vaults/guides/set-up-insurance-pool Configure the loss backstop, deposit your skin-in-the-game capital, and trigger the Kamino match The Insurance Pool is the strongest trust signal you can offer depositors. Your locked capital absorbs losses before any depositor takes a hit, with public on-chain visibility of the amount. Kamino matches your deposit up to \$250K. For the conceptual treatment of the loss waterfall and the emergency withdrawal model, read [Risk primitives → Insurance Pool](/curators/vaults/concepts/risk-primitives#the-insurance-pool) first. This page is the operational walkthrough. ## Before you start You'll need: * An existing vault. If you haven't created one yet, see [Create a vault](/curators/vaults/guides/create-a-vault). * The capital you want to lock as the backstop, in the vault's deposit token. * A multisig wallet you want to nominate for the emergency-withdrawal 2-of-2 (Kamino's security council is the other signer). ## Setup steps **1. Create the Insurance Pool farm** The Insurance Pool is implemented as a dedicated farm on your vault (the `FirstLossCapitalFarm`). If your vault was created via the SDK with the standard `createVaultIxs` flow, the farm was created automatically. If not, create it now. | Method | How | | - | - | | UI | Available under your vault's Insurance Pool / First Loss Capital settings | | SDK | Use `kaminoManager.createVaultFarmIxs(...)` and `kaminoManager.updateVaultFirstLossCapitalFarmIxs(...)` to create the farm and register it on the vault. See [Configure farms](/curators/vaults/guides/configure-farms#first-loss-capital-farm) for the exact instruction sequence. | | CLI | Not currently supported. Use UI or SDK. | **2. Configure the deposit token** Set the asset you'll deposit. For most vaults this is the same as the vault's deposit token, so your backstop is denominated in the same currency you're protecting. **3. Deposit your capital** Deposit into the Insurance Pool. You receive vault shares (kTokens) which are staked into the pool. The deposited amount is visible on-chain and surfaces on Kamino's UI as a public commitment. **4. Transfer farm authority to a multisig** After creation, transfer farm ownership to a multisig and add Kamino as a co-signer for emergency operations. This sets up the 2-of-2 model for emergency withdrawals. **5. Trigger the Kamino match** Kamino matches curator Insurance Pool deposits up to \$250K. If you deposit \$200K, Kamino contributes \$200K, bringing the pool to \$400K. The match is triggered through Kamino — contact your curator-relations point of contact when your deposit is ready. ## Withdrawal mechanisms Two paths exist; understanding both is important because they serve fundamentally different purposes. ### Normal withdrawal — 30-day cooldown Initiate a standard withdrawal to remove your insurance commitment. The mandatory **30-day cooldown** begins when you initiate; the withdrawal is a **public, on-chain signal**. Depositors and anyone monitoring the vault see that you're exiting. This is the expected path for curators winding down their commitment. The 30-day window gives depositors time to assess and react. ### Emergency withdrawal — instant, 2-of-2 multisig Emergency withdrawal exists for one purpose: **rapidly accessing Insurance Pool funds to compensate depositors after a loss event**. It bypasses the cooldown. The 2-of-2 multisig: 1. Your curator-controlled wallet 2. Kamino's security council Both must sign. Kamino's security council co-signs only when the withdrawal is for legitimate depositor compensation. > [!WARNING] > > Using emergency withdrawal to extract funds and avoid compensating depositors — rather than to make them whole — defeats the Insurance Pool's purpose and constitutes a breach of the curator commitment. ## The loss compensation flow When the vault incurs bad debt, compensation is **manual** — there is no automated on-chain detection. Process: 1. **Loss is socialized.** Kamino calls `socialize_loss` on klend; depositors take the hit. 2. **Assess impact.** Identify which reserve was affected and the loss magnitude. 3. **Release Insurance Pool funds.** Normal withdrawal (30-day cooldown) or emergency withdrawal (2-of-2) if urgency is needed. 4. **Snapshot affected depositors** at the loss timestamp. 5. **Distribute compensation** to affected depositors. For the full flow, see [Risk primitives → Loss compensation flow](/curators/vaults/concepts/risk-primitives#loss-compensation-flow). ## Best practices * **Run alongside Whitelisted Reserves.** The two protect different things — together they're the highest trust configuration. See [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves). * **Set up before depositors enter.** A vault with an established Insurance Pool from launch is more credible than one that adds it later. * **Size the pool to depositor expectations.** Institutional depositors will look at pool depth as a fraction of vault TVL when assessing risk. ## What's next > [card] [Risk primitives](/curators/vaults/concepts/risk-primitives) > > The model behind the Insurance Pool and Whitelisted Reserves. > [card] [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) > > The complementary protection — restrict where vault capital can go. # Transfer admin to multisig Source: https://docs.kamino.com/curators/vaults/guides/transfer-admin Move your vault to Squads multisig control — required before going to production Production vaults run under a [Squads](https://squads.so) multisig — every state-changing operation flows through a proposal and approval. This guide walks through transferring Vault Admin to a multisig and the operating model afterwards. For the model and role definitions, see [Roles & ownership](/curators/vaults/concepts/roles-and-ownership). ## Why transfer * **Operational security.** No single key can move vault funds. * **Required for UI listing.** Kamino's UI lists only multisig-controlled vaults that also have [Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) enabled. * **Required for the Insurance Pool match.** Kamino's match program requires multisig control. ## Before you start You'll need: * The Squads multisig address that will hold Vault Admin. * The current Vault Admin keypair (or signing access). ## The two-step transfer Transfer uses an initiate-then-claim pattern to prevent accidental ownership changes. ``` [ current admin ] initiate transfer [ pending admin set ] claim [ multisig holds vault ] ● ─────────────────────────────► ● ──────► ● │ │ current admin can cancel ▼ [ unchanged ] ``` The current admin can cancel the pending transfer until the new admin claims. After claim, the previous admin has no privileges. > [tab] UI > > **1. Initiate transfer** > > On `kamino.com/curators/vaults`, open your vault's settings → Admin Management. Set the new admin to your Squads multisig address. Sign the transaction. The vault enters the pending state. > > **2. Claim transfer (from the multisig)** > > The new admin (Squads multisig) submits an accept-ownership transaction. This is a Squads proposal that members approve and execute via the Squads dashboard. > [tab] SDK > > ```typescript theme={"theme":"css-variables"} > import { KaminoManager, KaminoVault } from '@kamino-finance/klend-sdk'; > import { address } from '@solana/kit'; > > const vault = new KaminoVault(rpc, address('')); > const manager = new KaminoManager(rpc); > > // Step 1 — current admin initiates transfer > const { updateVaultConfigIx, updateLUTIxs } = > await manager.updateVaultPendingAdminIxs( > vault, > address(''), > adminSigner, > ); > // Build and send: [updateVaultConfigIx, ...updateLUTIxs] > > // Step 2 — new admin (multisig) claims > const { acceptVaultOwnershipIx, initNewLUTIx } = > await manager.acceptVaultOwnershipIxs(vault); > // Build and send: [acceptVaultOwnershipIx, initNewLUTIx] > // This must run as the new admin — for a Squads multisig, route through Squads. > ``` > [tab] CLI > > **Step 1 — initiate transfer (run as current admin):** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager update-vault-pending-admin \ > --vault \ > --new-admin \ > --mode execute > ``` > > **Step 2 — accept ownership:** > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager accept-ownership \ > --vault \ > --mode execute > ``` > > For Squads-controlled multisigs, step 2 is executed through the Squads interface as a proposal rather than a direct CLI call. To produce the encoded transaction for the proposal: > > ```bash theme={"theme":"css-variables"} > yarn kamino-manager accept-ownership \ > --vault \ > --mode multisig \ > --multisig > ``` ## Operating after transfer Once the multisig holds Vault Admin, every state-changing operation becomes a Squads proposal. Two flows: ### SquadsX (recommended) Sign in to `kamino.com/curators/vaults` with [SquadsX](https://squads.so). The Send action automatically generates the transaction, creates the proposal, and routes it to the multisig dashboard for approval. ### Encoded transaction If you're not using SquadsX: 1. Configure the change on `kamino.com/curators/vaults`. 2. Click Simulate to verify and review the resulting state. 3. Copy the Base58-encoded transaction string from the simulation output. 4. Open Squads and import the transaction. 5. Gather approvals and execute. Programmatic operations follow the same pattern. SDK methods produce instructions that are wrapped into transactions you submit through Squads. CLI commands accept `--mode multisig --multisig ` to emit a Base58 payload. ## Allocation Admin transfer (optional) The Allocation Admin role is **single-step** — the Vault Admin sets it directly with no claim. Use this to delegate allocation management to a non-multisig wallet (e.g. an automated rebalancer) without granting full vault control. > [tab] UI > > Set under your vault's Admin Management settings. Single transaction. > [tab] SDK > > Use `kaminoManager.updateVaultAllocationAdminIxs(vault, newAdmin, signer)`. To revoke, set the Allocation Admin back to the default pubkey or to the Vault Admin itself. ## What's next > [card] [Roles & ownership](/curators/vaults/concepts/roles-and-ownership) > > The full role model and operating-under-multisig flows. > [card] [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) > > The other prerequisite for Kamino UI listing. # Vaults Source: https://docs.kamino.com/curators/vaults/index B2B lending infrastructure on Kamino — deploy a vault, allocate capital across reserves, and manage exposure A Kamino Vault is a programmable lending product. You deploy it for a single deposit token, route capital across Kamino lending reserves, and issue share tokens to depositors. As the curator, you control allocation strategy, fees, risk parameters, and rewards — all on-chain, transparent, and depositor-facing. This section is the operational reference for curators running vaults. If you're new to the model, start with [Concepts](/curators/vaults/concepts/how-vaults-work). If you have a workflow in mind, jump to [Guides](#guides). ## Start here > [card] [How vaults work](/curators/vaults/concepts/how-vaults-work) > > The vault primitive: share tokens, allocation, depositor flow, and the curator's role. > [card] [Create a vault](/curators/vaults/guides/create-a-vault) > > Deploy your first vault, configure fees, and complete post-creation setup. ## Concepts Read once to understand the system. > [card] [Allocations](/curators/vaults/concepts/allocations) > > How capital is distributed across reserves — Standard vs. Conditional, weights, caps, and priority. > [card] [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals) > > Unallocated buffer, instant vs. queued exits, and the withdrawal queue primitive. > [card] [Yield & fees](/curators/vaults/concepts/yield-and-fees) > > APY model, performance and AUM fees, withdrawal penalty, crank fee, and farm rewards. > [card] [Roles & ownership](/curators/vaults/concepts/roles-and-ownership) > > Admin types, the multisig model, and how Squads-based execution works. > [card] [Risk primitives](/curators/vaults/concepts/risk-primitives) > > The Insurance Pool and Whitelisted Reserves — the two protections you offer depositors. > [card] [Permissioned vaults](/curators/vaults/concepts/permissioned-vaults) > > Gate vault deposits behind a per-user allowlist. KYC, accredited-investor, and counterparty-gated configurations. > [card] [Fixed Rates](/curators/vaults/fixed-rates) > > Allocating into fixed-rate reserves: the rate grid, term premium, and the curator's strategy surface. ## Guides Task-oriented walkthroughs in the order you typically run them. ### Setup > [card] [Create a vault](/curators/vaults/guides/create-a-vault) > > Deploy the vault and set fees, mins, and penalties. Optionally enable Whitelisted Reserves at creation (UI/SDK). > [card] [Transfer admin to multisig](/curators/vaults/guides/transfer-admin) > > Move your vault to Squads multisig control before any subsequent state-changing operations. > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > Add, edit, and remove reserve allocations. > [card] [Configure fixed-rate allocations](/curators/vaults/guides/configure-fixed-rate-allocations) > > The FR-specific allocation walkthrough — Standard, Conditional, priority. Skip if you have no FR exposure. > [card] [Enable Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) > > Restrict your vault to protocol-verified reserves. Required for UI listing. > [card] [Set up the Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) > > Lock skin-in-the-game capital, trigger the Kamino match, configure emergency-withdrawal multisig. > [card] [Enable permissioning](/curators/vaults/guides/enable-permissioning) > > Switch the vault into permissioned mode and manage the depositor allowlist via kperm. ### Operate > [card] [Collect fees](/curators/vaults/guides/collect-fees) > > Withdraw pending fees, give up fees, and update fee rates. ### Reference / fallback > [card] [Configure farms](/curators/vaults/guides/configure-farms) > > Post-creation farm setup. Skip if your vault was created via SDK or UI — farms are typically created automatically there. ## Data & API > [card] [Vault data](/curators/data/vault-data) > > Query vault state, metrics, and historical performance. > [card] [Allocation data](/curators/data/allocation-data) > > Read current allocations and historical allocation changes. > [card] [Depositor data](/curators/data/depositor-data) > > Query depositor positions and shares. > [card] [Rewards data](/curators/data/rewards-data) > > Query farm reward programs and incentive data. ## Reference > [card] [Parameters](/curators/reference/parameters) > > Complete parameter reference for vaults, allocations, and farms. > [card] [Glossary](/curators/reference/glossary) > > One-line definitions for every term used in this section. > [!NOTE] > > All vault operations are managed via [kamino.com/curators/vaults](https://kamino.com/curators/vaults) and executed through [Squads](https://squads.so) multisig once the vault is in production. Programmatic operations are available via the [TypeScript SDK](https://github.com/Kamino-Finance/klend-sdk) and the [Kamino CLI](/build/cli/installation-setup). # Plan Your Vault Source: https://docs.kamino.com/curators/vaults/plan-your-vault Understand the decisions a curator makes when designing and operating a Kamino lending vault A Kamino lending vault accepts a single deposit asset and allocates it across selected Kamino lending reserves. Depositors receive vault shares representing their portion of the vault and earn the yield generated by those reserves. The curator decides where capital can go and adjusts the strategy as conditions change. ![Kamino curators vault overview](https://mintcdn.com/kamino-3d73a151/Kr04J8Tty1aPhdQ2/images/curators/vaults/vault-overview.webp?fit=max\&auto=format\&n=Kr04J8Tty1aPhdQ2\&q=85\&s=68346f227fe1a3266d333da6aef2a29c) A vault does not create a new lending market. It allocates deposits across existing reserves. The yield it generates depends on how those reserves perform and how the curator distributes capital between them. By the end of this guide Curators should understand: * What a Kamino lending vault does and what vault shares represent. * The settings that determine where capital is allocated and when it moves between reserves. * What determines how much capital remains available for withdrawals. * Which fees generate curator revenue and how farm rewards reach depositors. * What the Insurance Pool and Whitelisted Reserves protect. * Which vault responsibilities can be delegated and why administrative authority is transferred to a multisig. * When changing vault conditions may require an adjustment. *** ## A Vault in One Example Planning a vault starts with understanding how depositor capital moves through it. Consider a vault that accepts USDC and allocates it between two USDC reserves in different Kamino lending markets. Depositors supply USDC and receive vault shares. The vault distributes their USDC according to the curator's allocation targets. When a depositor adds USDC, the vault issues vault shares (SPL tokens) representing their portion of its total assets. As the vault earns interest, the value of each share increases. The depositor later redeems those shares for USDC at the current exchange rate. Suppose the vault holds \$1 million USDC and the curator sets a 60% allocation to one reserve and 40% to another. The vault targets \$600,000 in the first reserve and \$400,000 in the second. Because each reserve earns a different supply rate, the vault's yield reflects the amount allocated to each one. As the vault's balance changes, the amount held in each reserve can move away from the 60/40 target allocation. A permissionless crank periodically moves available capital so each reserve moves closer to its target. The curator sets or updates the percentage assigned to each reserve instead of moving every deposit manually. When a depositor withdraws, the vault redeems their shares for USDC. It first uses unallocated USDC and any capital available from its reserves. If the full amount cannot be returned immediately, the remainder enters a withdrawal queue and is paid as liquidity becomes available. The curator can earn revenue through a performance fee on profits and an assets under management (AUM) fee on the vault's total assets. Both fees accrue in the vault's deposit asset, which is USDC in this example, and can be collected by the curator. Knowledge Check A curator should be able to: * Understand what vault shares represent. * Understand how allocation percentages determine the amount assigned to each reserve. * Understand the crank's role in moving available capital closer to the curator's target allocations. * Explain how depositors withdraw from the vault. * Understand the two fee types that generate curator revenue. > [card] [How vaults work](/curators/vaults/concepts/how-vaults-work) > > Vault mechanics, share tokens, and the deposit-to-yield lifecycle. > [card] [Create a vault](/curators/vaults/guides/create-a-vault) > > Initialize a new vault and set its deposit asset. *** ## Selecting Assets for a Vault Each Kamino vault accepts a single asset. A USDC vault accepts USDC deposits and allocates them only to USDC reserves. It cannot allocate capital to SOL or any other asset. The same asset may be available in several Kamino lending markets. Each market has its own borrowers, supply rate, utilization, and available liquidity. The curator selects which of these reserves the vault can allocate capital to. The supply rate shown for a reserve can change as borrowing demand changes. A higher rate may reflect high utilization, which also leaves less liquidity available if the vault needs to withdraw capital. Farm incentives may also increase the displayed yield only while those rewards continue. Using several reserves can spread capital across lending markets, but the number of allocations alone does not determine diversification. Reserves exposed to similar borrowers or market conditions may still carry similar risk. Worth checking * Whether the expected yield is supported by borrowing demand and how much remains if farm rewards end. * Whether the selected reserves provide enough liquidity and meaningfully different exposure. *** ## Planning the Allocation Strategy For each reserve, the curator sets rules for when capital can enter and how much it can receive. Together, these settings determine how the vault distributes capital as market conditions change. A vault can allocate the same asset across several reserves, each offering a different way to earn yield. The curator decides whether capital should be placed in a reserve immediately or moved only when a borrower is ready to use it. A **Standard** allocation places capital in a variable rate reserve, where it earns interest that changes with utilization. A **Conditional** allocation keeps that capital earning in a Standard reserve until it matches demand for a fixed rate loan. The capital then moves into the fixed rate reserve and is lent to the borrower. For each Standard allocation, the **weight** sets the share of vault capital intended for that reserve. As the vault grows, the amount assigned to the reserve grows with it. The curator can set a **vault allocation cap** to stop that amount from increasing beyond a chosen limit. This prevents the vault from placing too much of its capital in one reserve. The cap applies only to the vault and does not change the reserve's own settings. ### Allocation Settings | Setting | What it determines | | - | - | | **Type** | Whether capital enters a reserve immediately through a Standard allocation or moves when fixed rate borrowing demand appears through a Conditional allocation. | | **Weight** | The proportion of capital assigned to each Standard allocation. | | **Cap** | The maximum amount of the vault asset that can be allocated to a reserve. | | **Priority** | Which Standard allocations may supply capital when a Conditional allocation receives borrowing demand. | Worth checking * Whether the vault should hold capital in variable rate reserves, offer fixed rate loans through Conditional allocations, or support both. * How much capital the vault should make available for fixed rate borrowing demand. > [card] [Allocations](/curators/vaults/concepts/allocations) > > Weight, cap, type, and priority mechanics. > [card] [Configure allocations](/curators/vaults/guides/configure-allocations) > > Set and update allocation targets. > [card] [Fixed rates](/curators/vaults/fixed-rates/index) > > Conditional allocations and fixed rate lending. *** ## Planning for Withdrawals A curator decides how much deposited capital should remain available for withdrawals instead of being allocated to lending reserves. This is the vault's **unallocated buffer**. A larger buffer supports more immediate withdrawals, but the capital it holds does not earn lending yield. The **UnallocatedWeight** allows the buffer to grow with the vault. The **UnallocatedTokensCap** stops that growth once the buffer is large enough, preventing too much depositor capital from sitting idle instead of earning yield. When a depositor withdraws, the vault uses the unallocated buffer first. If the buffer cannot cover the full amount, the vault draws from available liquidity in its reserve allocations. Any amount that cannot be returned immediately enters the withdrawal queue and is paid as liquidity becomes available. **Vault shares and reserve receipts.** Depositors normally hold vault shares, also called kTokens, representing their portion of the vault. The vault holds cTokens representing capital supplied to its lending reserves. If a withdrawal must be queued, the remaining vault shares may be exchanged for cTokens until the underlying asset becomes available. ### Withdrawal Settings | Setting | What it determines | | - | - | | **UnallocatedWeight** | The target share of vault capital kept available for withdrawals. | | **UnallocatedTokensCap** | The maximum amount of capital the vault may hold in the unallocated buffer. | Worth checking * How much withdrawal activity the vault is expected to support. * How much yield the vault can forgo to keep capital immediately available. > [card] [Liquidity & withdrawals](/curators/vaults/concepts/liquidity-and-withdrawals) > > Buffer sizing, withdrawal queue, and cToken mechanics. > [card] [Create a vault](/curators/vaults/guides/create-a-vault) > > Set buffer parameters during vault creation. *** ## Vault Revenue and Depositor Rewards A curator decides how the vault will generate revenue and whether depositors will receive rewards in addition to lending yield. These choices affect the return depositors keep and the income the curator earns for managing the vault. ### Setting Fees Curator revenue comes from two fees. A **performance fee** charges a percentage of the vault's profits. An **assets under management (AUM) fee** charges an annual percentage of the vault's total assets, regardless of its performance. Both accrue in the vault's deposit asset and can be collected by the curator. The vault also charges fees that do not generate curator revenue. The **withdrawal penalty** returns to the vault for the benefit of remaining depositors. The **crank fund fee** covers the protocol cost of allocating new deposits across reserves. ### Fee Settings | Fee | How it is calculated | Curator revenue? | | - | - | - | | **Performance fee** | A percentage of the vault's profits. | Yes | | **Assets under management (AUM) fee** | An annual percentage of the vault's total assets. | Yes | | **Withdrawal penalty** | The greater of a percentage fee or a fixed token amount charged when a depositor withdraws. | No. It returns to the vault for remaining depositors. | | **Crank fund fee** | A fixed amount charged for each reserve when a deposit is allocated. | No. It funds protocol operations. | ### Farm Rewards Farm rewards are separate from curator fees. Where they come from determines whether depositors claim them directly or receive them through a higher vault share value. | Reward type | Where it comes from | How depositors receive it | Curator revenue | | - | - | - | - | | **Vault Farm** | A reward token supplied by the curator or another sponsor. | Depositors claim rewards based on their vault share holdings during the reward period. | No | | **Reserve farm** | An incentive program attached to a reserve where the vault allocates capital. | Rewards are calculated for each depositor based on their vault position and the vault's allocation to that reserve. Depositors claim them separately. | No | | **Autocompound Farm** | Rewards supplied in the vault's deposit asset. | Rewards are reinvested and increase the value of vault shares. | Yes, indirectly. Reinvested rewards increase the vault's assets under management, which can increase AUM fee revenue and may also contribute to performance fees. | Knowledge Check A curator should be able to: * Identify which vault fees generate curator revenue and where the other fees go. * Distinguish which farm rewards depositors can claim directly. > [card] [Yield & fees](/curators/vaults/concepts/yield-and-fees) > > Performance fees, AUM fees, and reward mechanics. > [card] [Configure farms](/curators/vaults/guides/configure-farms) > > Set up Vault Farms, Reserve farms, and Autocompound Farms. *** ## Depositor Protections Before launch, the curator decides which depositor protections are appropriate for the vault. An **Insurance Pool** provides an added layer of coverage, while **Whitelisted Reserves** keeps allocations within a set approved by Kamino. ### Insurance Pool An Insurance Pool is capital the curator deposits into a dedicated pool attached to the vault. That capital continues earning the vault's APY while it remains locked. Kamino matches the curator's contribution up to \$250,000. A \$200,000 contribution therefore creates a \$400,000 Insurance Pool, while amounts above \$250,000 receive no additional match. If the vault incurs a loss, the Insurance Pool is used to compensate depositors before the remaining loss reaches them. Coverage is limited to the pool's balance, and compensation is coordinated manually with Kamino. Withdrawing curator capital requires a 30-day cooldown. An emergency withdrawal can bypass the cooldown, but it requires approval from both the curator and Kamino's Security Council and is reserved for compensating depositors after a loss. ### Whitelisted Reserves Whitelisted Reserves limits the vault to reserves verified by Kamino. The curator decides whether to enforce the whitelist but does not decide which reserves it contains. Before enabling it, the curator should confirm that the vault's planned allocations are included in the approved set. The protection uses two settings. One prevents the curator from creating or increasing allocations outside the whitelist. The other prevents depositor funds from entering those reserves. Both settings form part of the requirements for appearing on Kamino's interface, and neither can be disabled afterward. The whitelist does not prevent withdrawals. Existing allocations can still be reduced or removed, and depositors can withdraw when liquidity is available. ### Comparing Vault Safeguards | If the curator's priority is... | Safeguard to consider | What this requires | | - | - | - | | Providing capital-backed coverage if the vault suffers a loss | Insurance Pool | Curator capital remains locked, earns the vault APY, and is used to compensate depositors after a loss. | | Preventing the vault from entering reserves outside Kamino's approved set | Whitelisted Reserves | The allocation strategy is limited to reserves Kamino has approved. | | Preserving access to reserves outside the approved set | Insurance Pool without Whitelisted Reserves | The vault retains broader allocation flexibility but does not meet the safeguard requirements for Kamino interface listing. | | Restricting reserve access without committing curator capital | Whitelisted Reserves without an Insurance Pool | Allocations are restricted, but depositors do not receive capital-backed loss coverage and the vault does not meet the safeguard requirements for Kamino interface listing. | | Meeting the safeguard requirements for Kamino interface listing | Both safeguards | Curator capital is committed and allocations remain within the approved reserve set. Multisig ownership is also required. | Worth checking * How much curator capital can be committed to an Insurance Pool and remain subject to the 30-day withdrawal restriction. * Whether the planned allocation strategy can operate within Kamino's approved reserve set. > [card] [Insurance Pool](/curators/vaults/guides/set-up-insurance-pool) > > Fund the pool, understand cooldowns, and coordinate payouts. > [card] [Whitelisted Reserves](/curators/vaults/guides/enable-whitelisted-reserves) > > Enable the whitelist and confirm eligible reserves. *** ## Vault Roles and Permissions Before launch, the curator decides who will manage the vault and which responsibilities can be delegated. These choices determine who can change the vault's configuration once it begins operating. ### Assigning Vault Roles A vault separates full administrative authority from routine allocation management. The curator decides which actions should remain with the primary admin and which can be delegated to another wallet or automated service. The **Vault Admin** can change the vault's settings, add or remove reserves, update allocations, and set fees. The **Allocation Admin** can adjust the weights, caps, types, and priorities of existing allocations, but cannot add reserves or change the vault's broader configuration. This allows routine allocation changes without granting full authority over the vault. The **Farm Authority** manages the vault farm during its creation. Once the farm is created, this authority transfers to the protocol and is no longer managed by the curator. ### Planning Multisig Ownership For a production vault, the Vault Admin is transferred to a Squads multisig before deposits open. The curator decides who will hold signing authority and how many approvals will be required to change the vault. Once the multisig becomes Vault Admin, changes are submitted as proposals and executed only after the approval threshold is met. This prevents a single wallet from changing the vault and makes administrative decisions visible to the other signers. Multisig ownership is also required for a vault to appear on Kamino's interface. ### Authority by Action | Action | Authority | | - | - | | Change vault settings or fees | Vault Admin | | Add or remove a reserve | Vault Admin | | Update an existing allocation | Vault Admin or Allocation Admin | | Transfer administrative authority | Vault Admin | | Manage the vault farm during creation | Farm Authority | Knowledge Check A curator should be able to: * Understand which allocation changes can be delegated without granting full administrative authority. * Understand why administrative authority is transferred to a multisig before launch. > [card] [Roles & ownership](/curators/vaults/concepts/roles-and-ownership) > > Vault Admin, Allocation Admin, and Farm Authority. > [card] [Transfer admin](/curators/vaults/guides/transfer-admin) > > Move ownership from a hot wallet to Squads. *** ## Ongoing Vault Management Once the vault is live, the curator should watch for conditions that suggest its allocation strategy or withdrawal settings need to change. ### Adjusting the Vault | Issue | What is happening | Response | | - | - | - | | Capital remains far from its target allocations | To restore the target, the crank must withdraw capital from an overallocated reserve and move it into an underallocated reserve. It may be unable to complete that move if borrowers are using the capital in the first reserve or the second allocation has reached its cap. | Check the available liquidity in the first reserve and the cap on the second allocation. Revise the target or cap if the current configuration cannot be reached. **Vault Admin or Allocation Admin.** | | The withdrawal buffer is repeatedly exhausted | Depositors are withdrawing capital faster than the buffer is being replenished. The vault must draw from its reserve allocations, and withdrawals may be queued if that capital is unavailable. | Increase the UnallocatedWeight or UnallocatedTokensCap so more capital remains available. **Vault Admin.** | | An allocation is earning less than expected | Borrowing demand in that reserve may have fallen, reducing the interest earned by the vault. | Reduce its target weight and direct capital toward another suitable reserve. **Vault Admin or Allocation Admin.** | | A reserve has limited available liquidity | Most of the reserve's capital is already being used by borrowers. The vault may be unable to withdraw its allocation immediately. | Reduce the allocation weight or cap to limit further exposure. **Vault Admin or Allocation Admin.** | | An allocation reaches its cap as the vault grows | The reserve cannot receive more of the vault's capital, even if its target weight assigns it a larger amount. Additional capital must remain available or move to another eligible allocation. | Increase the cap if the reserve can support more exposure. Otherwise, direct additional capital elsewhere. **Vault Admin or Allocation Admin.** | ### Responding to Events | Issue | What is happening | Response | | - | - | - | | A reserve shows signs of a security issue | The vault may still be directing depositor capital into a reserve that is no longer considered suitable. Any loss in that reserve can reduce the value of the vault's holdings. | Set the allocation cap to zero to stop additional capital from entering; for a Standard allocation, its weight can also be set to zero. Remove the allocation once available capital has been withdrawn. **Vault Admin or Allocation Admin** can stop further allocation. Only the **Vault Admin** can remove the reserve. | | A reserve loss reduces the vault's assets | The vault's claim on that reserve is now worth less. This reduces the value of vault shares and may leave depositors with a loss. | Stop further allocation, assess the loss with Kamino, then use the Insurance Pool to compensate affected depositors. **Vault Admin or Allocation Admin** stops further allocation. Releasing Insurance Pool funds immediately requires the curator's designated signer and **Kamino's Security Council**. | | An unexpected allocation change appears | An Allocation Admin wallet or automated service may have changed a weight, cap, type, or priority without approval. It cannot add a new reserve or change other vault settings. | Replace or revoke the Allocation Admin, restore the intended configuration, then sync the vault toward its targets. **Vault Admin.** | | An unfamiliar Vault Admin proposal appears in Squads | A multisig signer may be compromised or someone may be attempting an unauthorized vault change. The proposal cannot execute unless it receives the required approvals. | Do not approve the proposal. Review its source and remove any compromised signer before another vault change is submitted. **Squads multisig members.** | Vaults do not have the same Emergency Council used by lending markets. Their response model relies on delegated allocation authority, the Vault Admin multisig, and the Insurance Pool's separate two-party withdrawal authority. Knowledge Check A curator should be able to: * Identify when allocation settings or the withdrawal buffer need to change as vault conditions evolve. * Understand which authority can make each adjustment or respond to an unexpected event. *** ## Pre-launch Checklist ### Vault Strategy * [ ] The vault asset and eligible reserves have been selected. * [ ] Each allocation is designated as Standard or Conditional. * [ ] Target weights, allocation caps, and priorities have been set. ### Withdrawals and Revenue * [ ] The unallocated buffer has been sized for expected withdrawal activity. * [ ] Performance and AUM fees have been set. * [ ] Any Vault Farms or Autocompound Farms have been planned. ### Safeguards and Authority * [ ] The Insurance Pool commitment has been decided. * [ ] The planned allocations are compatible with Whitelisted Reserves. * [ ] Vault Admin will be transferred to the intended multisig. * [ ] Allocation Admin responsibilities have been assigned. ### Ongoing Management * [ ] The conditions that would require allocation or buffer changes have been defined. * [ ] The authority responsible for each change has been confirmed. * [ ] The response to a reserve loss or unexpected administrative change has been reviewed. # Source: https://docs.kamino.com/index Complete documentation for Kamino Finance: Earn yield with automated vaults, Borrow and Lend, Multiply for leveraged positions, and concentrated liquidity on Solana. Developer Buildkit with REST API and TypeScript SDK. Curator tools for vault creation and management. # Kamino Documentation Explore the Kamino protocol with comprehensive documentation for developers, curators, and institutions. [Open Docs](/products) Earn Borrow Multiply Swap Audits Risk Safety Docs Product Product and risk docs for understanding Kamino.Read about product mechanics, usage guides, audits, safeguards, and the risk framework behind Kamino. [Products](/products/lending-vaults) [Learn](/learn/guides) [Security & Risk](/security) [Open Buildkit](/build) const vault = new KaminoVault(rpc, address);const shares = await vault.getUserShares(user); REST API TS SDK Buildkit Developer AI-ready docs for faster Kamino integrations.Build on Kamino with APIs, SDKs, Rust tooling, and practical examples. [API Reference](/build/api-reference/introduction) [SDK Guides](/build/developers/overview) [AI Tools](/build/agentic-finance/building-with-llms) [Open Curators](/curators) CREATE VAULT ALLOCATIONS SET UP FARMS MARKETS RESERVES REWARDS Curators Operator Vault and market docs.Design and manage custom lending strategies on Kamino for institutions and professional risk managers. [Vaults](/curators/vaults) [Markets](/curators/markets) [Parameters](/curators/reference/parameters) ## Curators on Kamino ![Allez Labs](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/allez-logo.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=3312631c709f84d2ac3807c261ad57af) ![Allez Labs](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/allez-logo-dark.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=e2d209914f8266eb47c4a2334c3ffa1e) ![Gauntlet](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/gauntlet-logo.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=fa512c9cdc4cb699bd4d7ce88a475b9e) ![Gauntlet](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/gauntlet-logo-dark.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=b5ef4dbdca8741f325bac747fc53fa41) ![Rockaway](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/rockaway-logo.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=6c8417a8e85289343a9ee8c53ba9f244) ![Rockaway](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/rockaway-logo-dark.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=96e29d15084d31c2abadf7c256ce1dcb) ![Steakhouse Financial](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/steakhouse-logo.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=8c710519e2f57a3a45be5b22d746d809) ![Steakhouse Financial](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/steakhouse-logo-dark.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=ae0526279b9eaf22a1c5e696ce393552) ![Sentora](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/sentora-logo.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=cc727abf15098caaa59da3863853390c) ![Sentora](https://mintcdn.com/kamino-3d73a151/EHpt5rRzyV5R3dXt/images/sentora-logo-dark.svg?fit=max\&auto=format\&n=EHpt5rRzyV5R3dXt\&q=85\&s=66c541f4efe88551f091b7800135fb5b) Kamino gives curators granular control over institutional-grade lending infrastructure. ------------------------------------------------ ### [Vaults](/curators/vaults)
  1. 1 #### Deploy Vault Initialize a lending vault that accepts a single deposit token.
  2. 2 #### Set Allocation Strategy Configure allocation weights, caps, and risk parameters across reserves.
  3. 3 #### Route Assets Distribute depositor assets across lending reserves and issue share tokens.
  4. 4 #### Earn Revenue Collect fees from vault operations and manage rewards distribution.
### [Markets](/curators/markets)
  1. 1 #### Create Market Deploy an isolated lending market with your own risk parameters.
  2. 2 #### Add Reserves Configure reserves with LTV, liquidation thresholds, rate curves, and oracles.
  3. 3 #### Configure Rewards Set up collateral and debt farms to distribute rewards to depositors and borrowers.
  4. 4 #### Transfer to Multisig Transfer market administration to a Squads multisig before launch.
## A complete toolchain for faster integrations. #### REST API Data, analytics, user positions, unsigned transactions. #### TypeScript SDK On-chain reads, transaction building, advanced operations. #### Rust Crate Rust clients, bots, on-chain CPI. #### AI Tools llms.txt, skill.md, agent assisted development. #### CLI Managing markets, reserves, vaults, and operational workflows. ```typescript theme={"theme":"css-variables"} const res = await fetch('https://api.kamino.finance/ktx/kvault/deposit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ wallet: 'YOUR_WALLET_ADDRESS', kvault: 'HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E', amount: '100.0', }), }); const { transaction } = await res.json(); ``` ```typescript theme={"theme":"css-variables"} import { createSolanaRpc, address, generateKeyPairSigner } from '@solana/kit'; import { KaminoVault } from '@kamino-finance/klend-sdk'; import { Decimal } from 'decimal.js'; const signer = await generateKeyPairSigner(); const vault = new KaminoVault( createSolanaRpc('https://api.mainnet-beta.solana.com'), address('HDsayqAsDWy3QvANGqh2yNraqcD8Fnjgh73Mhb3WRS5E') ); const depositIxs = await vault.depositIxs( signer, new Decimal(100.0) ); ``` ```rust theme={"theme":"css-variables"} use kvault_interface::{helpers, pda, VaultInfo, KVAULT_PROGRAM_ID}; use spl_associated_token_account::get_associated_token_address; let vault = VaultInfo::from_account_data( vault_pubkey, &vault_data.data, &reserve_infos )?; let user_token_ata = get_associated_token_address(&owner, &vault.token_mint); let (shares_mint, _) = pda::shares_mint(&KVAULT_PROGRAM_ID, &vault_pubkey); let user_shares_ata = get_associated_token_address(&owner, &shares_mint); let deposit_ix = helpers::deposit::deposit( &vault, owner, user_token_ata, user_shares_ata, 1_000_000, ); ``` #### Kamino MCP Server `npx add-mcp https://docs.kamino.com/mcp` Copy command #### Kamino CLI `yarn kamino-manager create-market --mode execute` Copy command ## How can we help? Build with Kamino. Get the support you need to ship.
Full name \* Email address \* Topic \* Tell us what you have in mind \* Send message
[X](https://x.com/kamino) [Discord](https://discord.com/invite/kamino) [Telegram](https://t.me/+DVzNEEQqiSRjODg0) [GitHub](https://github.com/Kamino-Finance) [Risk dashboard](https://risk.kamino.finance) [Security](/security) [App](https://app.kamino.finance) [Terms](https://kamino.com/terms) # KMNO Source: https://docs.kamino.com/kmno/index KMNO is the native token of the Kamino protocol KMNO is the native token of Kamino Finance, with a total supply of 10,000,000,000. The token launched via genesis event on April 30, 2024. ## Token Info | Parameter | Value | | - | - | | Ticker | KMNO | | Total Supply | 10,000,000,000 | | Token Generation Event | April 30, 2024 | | Initial Circulating Supply | \~1,000,000,000 | | Blockchain | Solana | ## Distribution | Allocation | Share | Notes | | - | - | - | | Community & Grants | 35% | Builder grants and community incentives managed by Kamino treasury | | Key Stakeholders & Advisors | 35% | 12-month lockup, then 24-month linear vest | | Core Contributors | 20% | 12-month lockup, then 24-month linear vest | | Liquidity & Treasury | 10% | Used to grow KMNO liquidity across platforms | | Genesis Allocation (subset of Community & Grants) | - | 7.5% of total supply distributed at TGE to existing platform participants (included within Community & Grants allocation above) | > [!NOTE] > > For the latest information on KMNO distribution and vesting, see the > [Kamino governance forum](https://gov.kamino.finance). # How to Long xStocks on Kamino Source: https://docs.kamino.com/learn/borrow/long-xstocks Open a leveraged long position on xStocks using Kamino's Borrow market. A leveraged long position increases your exposure to an xStock by borrowing against your existing holdings and using the borrowed funds to purchase more of the same asset. Unlike a one-click Multiply position, this strategy is built manually by supplying collateral, borrowing USDC, swapping it for more xStock, and optionally supplying the received tokens again. Leveraged positions carry liquidation risk. Always review your loan-to-value ratio, liquidation price, borrowing costs, and swap details before confirming a transaction. ## Opening a leveraged long position **1. Open the xStocks market** Go to **Borrow** and select the **xStocks Market**. ![xStocks Market on the Borrow page](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/xstocks-market.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=a9c715a6dff5f86ac2dac412df0e48c1) **2. Supply the xStock** Select the xStock you want to use as collateral. Enter the amount you want to supply and confirm the transaction in your wallet. ![Supply modal for an xStock](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/supply-xstock.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=10ac18781ab9295d1037ff7dc91ce4ff) Your supplied xStock will now act as collateral for the position. **3. Borrow USDC** Under **Borrow**, select USDC. Enter the amount you want to borrow. Before confirming, review: * Borrow APY * Loan-to-value ratio * Liquidation LTV Confirm the transaction in your wallet. ![USDC borrow modal and position health information](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/borrow-usdc.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=dc9290505d56150105cc5a2cb68a7e3e) **4. Swap the borrowed USDC for more xStock** Open Kamino **Swap** and exchange the borrowed USDC for the same xStock that you originally supplied. Review the quoted amount, price impact, and minimum received before confirming. ![USDC-to-xStock swap](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/swap-usdc-to-xstock.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=59e42a83565e8720e0be53804fafb554) You now have greater exposure to the xStock than you had with your original capital alone. **5. Optional: Supply the additional xStock** You can return to the xStocks Borrow market and supply the newly purchased xStock as additional collateral. This may allow you to borrow more USDC and repeat the process, commonly called **looping**. ![Supplying the additional xStock](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/supply-additional-xstock.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=4099d92ca97e73206809761c224ed022) Each loop increases both your exposure and your risk. A decline in the xStock's value can move the position closer to liquidation. ## Closing a leveraged long position ### Repay with collateral (one-click) **1. Select Repay with Collateral** Select **Repay with Collateral** on the debt token. **2. Enter the repayment amount** Enter the amount you want to repay. **3. Review and confirm** Review the quoted amount, price impact, and minimum received in the UI before confirming the transaction in your wallet. ![Repay with Collateral](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/repay-with-collateral-long.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=24dc7d81a9b77350027326bdfb22293c) ### Manual unwind ![Manual unwind of a leveraged long](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/manual-unwind-long.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=62a08a5b03cb8b18cae6c8f5a6676272) 1. Withdraw xStock to cover the outstanding USDC debt. 2. Swap the withdrawn xStock for USDC. 3. Repay the USDC loan using **Repay from wallet**. 4. Withdraw the remaining collateral. ## Risks to consider ### Liquidation risk If the value of your collateral falls relative to your debt, the position may reach its liquidation LTV. Keep a safety buffer rather than borrowing the maximum available amount. ### Borrowing costs Borrow APYs are variable and can change with market utilization. A position can lose money even when the directional trade is correct if borrowing costs are sufficiently high. ### Swap price impact Opening, looping, and closing positions require swaps. Low liquidity or a large transaction may result in price impact or slippage. ### Market and oracle risk xStocks can trade onchain around the clock, while issuance and redemption generally follow a 24/5 schedule. Liquidity and pricing conditions may therefore differ outside the underlying equity market's normal hours. ### xStock-specific risks xStocks are tokenized representations of equities or ETFs and are not identical to holding traditional shares. Availability is also restricted in certain jurisdictions. # How to Short xStocks on Kamino Source: https://docs.kamino.com/learn/borrow/short-xstocks Open a short position on xStocks using Kamino's Borrow market. A short position is created by borrowing an xStock and selling it for USDC. The position benefits if the xStock decreases in value, because it can then be repurchased at a lower price to repay the debt. Only xStocks currently enabled for borrowing can be used for this strategy. Short positions carry liquidation risk. If the xStock price rises, the cost to repay the debt increases. Always review your loan-to-value ratio, liquidation price, borrowing costs, and swap details before confirming a transaction. ## Opening a short position **1. Supply USDC as collateral** Open the **xStocks Market**, select USDC, and enter the amount you want to supply. Confirm the transaction in your wallet. ![Supplying USDC in the xStocks Market](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/supply-usdc.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=32f26a89dbc860ef6e973a9909bd66ed) **2. Borrow the xStock to short** Select the xStock you want to borrow. Enter the amount and review the position information, including: * Borrow APY * Loan-to-value ratio * Liquidation LTV Confirm the transaction. ![Borrowing an xStock](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/borrow-xstock.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=fe08c5b8513ce0d1e13c043478cfd9f7) **3. Swap the borrowed xStock for USDC** Open Kamino **Swap** and exchange the borrowed xStock for USDC. Review the swap quotation and confirm the transaction. ![xStock-to-USDC swap](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/swap-xstock-to-usdc.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=1058610c093d5cc676b05f79b6808d81) You now owe the borrowed xStock while holding the USDC received from selling it. **4. Optional: Supply the received USDC** The USDC received from the swap can be supplied to the xStocks Market as additional collateral. This can improve the position's collateral value or be used to increase the position further. However, borrowing more also increases liquidation and borrowing-cost risk. ![Supplying the received USDC](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/supply-received-usdc.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=6d98536b830b1e573304e96eaf312022) ## Closing a short position ### Repay with collateral (one-click) **1. Select Repay with Collateral** Select **Repay with Collateral** on the debt token. **2. Enter the repayment amount** Enter the amount you want to repay. **3. Review and confirm** Review the quoted amount, price impact, and minimum received in the UI before confirming the transaction in your wallet. ![Repay with Collateral](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/repay-with-collateral-short.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=9ba5083daaee15978d68d09d43e55a72) ### Manual unwind ![Manual unwind of a short position](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/manual-unwind-short.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=793158b85a65c84aa5ee6e3eb1d5f99b) 1. Withdraw USDC collateral to cover the outstanding xStock token debt. 2. Use USDC to swap into the amount of xStock required to repay the debt. 3. Repay the borrowed xStock. 4. Withdraw the remaining USDC collateral. When the xStock price has fallen, fewer USDC may be required to buy back the borrowed amount. If its price has risen, closing the position will require more USDC. ## Risks to consider ### Liquidation risk If the value of your collateral falls relative to your debt, the position may reach its liquidation LTV. Keep a safety buffer rather than borrowing the maximum available amount. ### Borrowing costs Borrow APYs are variable and can change with market utilization. A position can lose money even when the directional trade is correct if borrowing costs are sufficiently high. ### Swap price impact Opening and closing positions require swaps. Low liquidity or a large transaction may result in price impact or slippage. ### Market and oracle risk xStocks can trade onchain around the clock, while issuance and redemption generally follow a 24/5 schedule. Liquidity and pricing conditions may therefore differ outside the underlying equity market's normal hours. ### xStock-specific risks xStocks are tokenized representations of equities or ETFs and are not identical to holding traditional shares. Availability is also restricted in certain jurisdictions. # User Guides Source: https://docs.kamino.com/learn/guides Short, step-by-step walkthroughs for using every product in the Kamino app # User Guides Short, step-by-step walkthroughs that show you exactly how to use every product in the Kamino app. ![](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/lend/how-to-deposit-into-an-earn-vault.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=0cbea2ed3136004325ec1e0ba0a1e331) Earn ### [How to Deposit into an Earn Vault](/learn/lend/supplying-assets) ![](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/lend/how-to-earn-and-track-yield.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=c62f3784aabacffa9cdd0a188cac2827) Earn ### [How to Earn and Track Yield](/learn/lend/earning-yield) ![](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/lend/how-to-withdraw-from-an-earn-vault.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=7b579870b80c231410da3b4d0f30538f) Earn ### [How to Withdraw from an Earn Vault](/learn/lend/withdrawing-assets) ![](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/lend/tips-for-managing-risk.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=8dea9c961a4cc907daf5aece99d15e36) Earn ### [Tips for Managing Risk](/learn/lend/risks) ![](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/multiply/how-to-open-a-multiply-position.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=d5a4ba7b19446ef0b82e390affe054f8) Multiply ### [How to Open a Multiply Position](/learn/multiply/opening-a-position) ![](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/multiply/how-to-manage-a-multiply-position.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=d97f90464d34e03bc160f0eda6d2ca43) Multiply ### [How to Manage a Multiply Position](/learn/multiply/managing-a-position) ![](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/multiply/tips-for-avoiding-liquidation.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=74eb944bedc260c8b0ac6d669ef058f3) Multiply ### [Tips for Avoiding Liquidation](/learn/multiply/risks-and-liquidations) ![](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/portfolio/how-to-view-your-portfolio.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=0482db1596413076dc9255586b92446a) Portfolio ### [How to View Your Portfolio](/learn/portfolio/how-to-view-your-portfolio) ![](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/long-xstocks-card.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=f1fabef6fb45f74560018f6338b7c9d5) Borrow ### [How to Long xStocks on Kamino](/learn/borrow/long-xstocks) ![](https://mintcdn.com/kamino-3d73a151/E-tSDExrEbYYF1-q/images/learn/borrow/short-xstocks-card.webp?fit=max\&auto=format\&n=E-tSDExrEbYYF1-q\&q=85\&s=94b7ea1c5b154bcd7a8097b9ac7ad6e0) Borrow ### [How to Short xStocks on Kamino](/learn/borrow/short-xstocks) ![](https://mintcdn.com/kamino-3d73a151/nSj-oZqZbrFVVVcD/images/learn/swap/how-to-swap.webp?fit=max\&auto=format\&n=nSj-oZqZbrFVVVcD\&q=85\&s=1be67ec19946cc5695c16cc0376ff5ef) Swap ### [How to Swap Tokens](/learn/swap/how-to-swap) # How to Earn and Track Yield Source: https://docs.kamino.com/learn/lend/earning-yield Track your Earn Vault position and understand how your yield accrues and changes. Earn Vault yield compounds automatically into the value of your shares. You do not claim or reinvest it, you just track it from the vault page. ## How yield accrues Earn Vault yield comes from interest paid by borrowers across the reserves the vault is allocated to. As interest flows in, the value of each vault share increases, so your yield is auto-compounded: there is nothing to claim or reinvest. Your share count stays the same after you deposit. What changes is the redemption value of each share. ## Track your position Open the **My Position** panel on the vault page to monitor: * **Supplied amount**: the current value of your deposit * **Interest earned**: how much yield has accrued since you deposited * **Supply APY**: the current annualized yield rate ![My Position panel in an Earn Vault](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/lend/my-position.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=5d6cdb5f678f649768065bf5f919e4b9) ## Why your APY changes Vault APY is a weighted blend of the supply rates on the reserves the vault is allocated to, and those rates are variable. Your yield can rise or fall over time without any action from you, driven by: * **Borrow demand**: more borrowing raises utilization and supply rates, less borrowing lowers them. * **Reserve utilization**: each reserve's utilization curve sets how fast rates scale. Higher utilization means higher rates. * **Allocation changes**: when the curator adjusts allocations, the vault's blended rate shifts to the new reserve mix. The APY shown on the vault page is a trailing figure based on recent performance, not a guarantee of future returns. > [card] [How to Withdraw from an Earn Vault](/learn/lend/withdrawing-assets) > > Redeem your shares and withdraw your tokens. > [card] [Tips for Managing Risk](/learn/lend/risks) > > What to keep in mind about allocation, yield, and liquidity. # Tips for Managing Risk Source: https://docs.kamino.com/learn/lend/risks What to keep in mind about allocation, yield variability, and liquidity in Earn Vaults. Earn Vaults simplify earning yield, but they are not risk-free. Keep these points in mind before and after you deposit. ## Your deposit follows the whole allocation Your deposit is exposed to the blended performance and risk of the vault's full allocation, not a single reserve. If the curator changes allocations, your future exposure changes with them. ## Yield is not fixed Vault APY moves over time based on the underlying markets and reserve conditions. There is no guarantee that current rates will persist. See [How to Earn and Track Yield](/learn/lend/earning-yield) for what drives the changes. ## Withdrawals may not always be instant Small withdrawals are usually covered by the vault buffer, but larger withdrawals can depend on liquidity in the underlying reserves. During periods of high utilization, access to your liquidity may be slower. ## Simplicity does not remove market risk Earn Vaults are easier to use, but they still depend on lending market conditions. Passive management does not mean zero risk. For the full mechanics behind Earn Vaults, including yield calculations, allocation details, and withdrawal behavior, see the [Kamino Lending Vaults docs](/products/lending-vaults). # How to Deposit into an Earn Vault Source: https://docs.kamino.com/learn/lend/supplying-assets Deposit a single token into an Earn Vault and start earning optimized yield. Depositing into an Earn Vault puts a single token to work earning optimized yield. The vault allocates your deposit across Kamino lending reserves for you, and your position compounds automatically. ## Before you start * You deposit **one token**, and the vault spreads it across Kamino lending reserves for you, so you do not pick individual markets. * You receive **vault shares** in return. Your share count stays the same, and each share grows in value as the vault earns yield (auto-compounding). * Allocations are set by the vault's curator, so your position follows the vault's managed strategy. ## Deposit step by step **1. Connect your wallet** Connect your wallet to Kamino. **2. Select an Earn Vault** Browse the available Earn Vaults and choose the one that matches the token you want to deposit. ![Select an Earn Vault](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/lend/select-vault.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=36dda57be898d1e5cee61a3907bebfef) **3. Deposit** Enter the amount you want to deposit, click **Deposit**, and confirm the transaction in your wallet. ![Deposit into an Earn Vault](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/lend/deposit.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=419111fc67993e634e4140fe28fa9b90) **4. Automatic allocation** Once confirmed, your tokens are deposited into the vault and automatically allocated according to its strategy. Your deposit is now active and earning yield. > [card] [How to Earn and Track Yield](/learn/lend/earning-yield) > > Track your position and see your yield accrue. > [card] [How to Withdraw from an Earn Vault](/learn/lend/withdrawing-assets) > > Redeem your shares and withdraw your tokens. # How to Withdraw from an Earn Vault Source: https://docs.kamino.com/learn/lend/withdrawing-assets Redeem your vault shares and withdraw your tokens, including any yield earned. Withdrawing redeems your vault shares for the deposit token at the current share price. Any yield you have earned is included in what you receive. ## Withdraw step by step **1. Open your position** Navigate to the Earn Vault where you have an active position. **2. Withdraw** Click **Withdraw**, enter the amount you want to withdraw, and confirm the transaction in your wallet. ![Withdraw from an Earn Vault](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/lend/withdraw.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=8e2c9553eb7e82f6ab0fb591fbc5818a) **3. Receive tokens** Once confirmed, the tokens are returned to your wallet. > [!WARNING] > > Vaults keep a liquid buffer for withdrawals, but larger withdrawals may require capital to be recalled from the underlying reserves. In high-utilization conditions, withdrawals may be delayed until liquidity becomes available. > [card] [How to Earn and Track Yield](/learn/lend/earning-yield) > > Track your position and see your yield accrue. > [card] [Tips for Managing Risk](/learn/lend/risks) > > What to keep in mind about allocation, yield, and liquidity. # How to Manage a Multiply Position Source: https://docs.kamino.com/learn/multiply/managing-a-position Monitor your leveraged position, adjust leverage, collateral, or debt, and close it out. Once a Multiply position is open, you can track its performance and adjust or close it at any time, all in one-click transactions. ## Monitor your position Track your position in the **My Position** panel. Key metrics include: * **Net value**: the current value of your position after accounting for debt * **Net APY**: your effective yield after borrow costs * **Profit/Loss**: how your position has performed since opening * **LTV**: your current loan-to-value ratio relative to the liquidation threshold ## Adjust your position You can modify your position at any time. Available actions include: * **Withdraw**: reduce your position size and return funds to your wallet * **Adjust leverage**: increase or decrease your leverage multiplier * **Manage collateral and debt**: manually add or remove collateral, or repay debt directly ![Manage your Multiply position](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/multiply/manage-position.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=0800492eb0a110a90c55e024b6da9f6c) To make a change, select your action, enter the amount, and confirm the transaction in your wallet. ![Confirm a position action](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/multiply/execute-action.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=ba41efbbaec264434629d88b1070b973) ## Close your position When you are ready to close, Kamino reverses the opening process: it repays the debt, withdraws the collateral, swaps what is needed, and returns the remaining value to your wallet, all in a single transaction. To close, select **Withdraw** and withdraw the full amount. > [card] [Tips for Avoiding Liquidation](/learn/multiply/risks-and-liquidations) > > Understand liquidation risk and how to stay clear of it. > [card] [How to Open a Multiply Position](/learn/multiply/opening-a-position) > > Choose an asset, set your leverage, and open a position. # How to Open a Multiply Position Source: https://docs.kamino.com/learn/multiply/opening-a-position Choose an asset, set your leverage, and open a leveraged position in one transaction. Multiply opens a leveraged position for you in a single transaction. You choose an asset and target leverage, and Kamino handles the borrowing, swapping, and looping behind the scenes. ## Before you start * Opening a position uses a **flash loan** to build the full leveraged position in one transaction. If any step fails, the whole transaction reverts. * **Leverage amplifies losses as well as gains**, and every position carries variable-rate debt, so rising borrow costs can eat into or reverse your returns. * Some correlated pairs use **eMode** for higher leverage, which also narrows the buffer to your liquidation threshold. ## Open step by step **1. Connect your wallet** Connect your wallet to Kamino. **2. Choose a Multiply strategy** Browse the available Multiply strategies and choose the one that matches the asset and leverage you want. ![Choose a Multiply strategy](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/multiply/select-vault.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=f27b3ba0ec2f3f82840f49c5eeedcd90) **3. Review the details** Review the key details such as the asset pair, available leverage range, current APY, and strategy type. ![Review the strategy details](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/multiply/review-vault.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=0509ddeccb81ae70197485424023036d) **4. Deposit and set leverage** Enter your deposit amount, select your target leverage multiplier, review the swap pricing and slippage, then click **Deposit** and confirm the transaction in your wallet. Once confirmed, your leveraged position is active. > [card] [How to Manage a Multiply Position](/learn/multiply/managing-a-position) > > Monitor performance and adjust leverage, collateral, or debt. > [card] [Tips for Avoiding Liquidation](/learn/multiply/risks-and-liquidations) > > Understand liquidation risk and how to stay clear of it. # Tips for Avoiding Liquidation Source: https://docs.kamino.com/learn/multiply/risks-and-liquidations How leverage, borrow rates, and collateral affect liquidation risk, and how to stay clear of it. Multiply simplifies leveraged strategies, but leverage cuts both ways. Keep these points in mind to manage liquidation risk. ## Leverage amplifies losses, not just gains Multiply amplifies downside as well as upside. If the strategy performs poorly, losses can be larger and happen faster than in an unleveraged position. ## Watch your borrow rate Every Multiply position carries variable-rate debt. If borrow demand rises and rates climb, profitability can fall or turn negative. For some strategies, this is the main risk. ## Keep your LTV below the liquidation threshold If your position's LTV rises above its liquidation threshold, part of the position is liquidated until it returns to a healthier LTV. How much room you have depends on the strategy type: * **LST, RWA, and stablecoin strategies**: collateral is generally pegged or closely linked to the debt token, so liquidation risk mainly comes from elevated borrow rates over time (closer to a carry trade). * **Directional strategies** (e.g. JLP, xStocks): collateral is not pegged to the debt token, so risk comes from both rising borrow costs and the collateral price falling (closer to a leveraged long). ## Know your strategy type Not all Multiply positions behave the same way. Some are mainly exposed to borrow rate spread, others also to the collateral's price movement. Understand which type you are using before opening a position. For the full mechanics behind Multiply, including leverage structures, eMode, Net APY, and liquidation behavior, see the [Kamino Multiply docs](/products/multiply). # How to View Your Portfolio Source: https://docs.kamino.com/learn/portfolio/how-to-view-your-portfolio See all your Kamino positions, rewards, and history for a connected wallet in one place. The Portfolio page brings your entire Kamino activity into one view: current positions, claimable rewards, transaction history, and swap history for the connected wallet. ## Before you start Connect the wallet whose activity you want to see. Everything on the Portfolio page reflects the connected wallet and updates when you switch wallets. ## Open your Portfolio Open the **Portfolio** page in the Kamino app. Once your wallet is connected, the page populates with your data across every Kamino product. ![Kamino Portfolio page overview](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/portfolio/portfolio-data-1.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=672e26efde10966100150db73ef1b7dc) ## Portfolio data The summary tiles at the top give you an at-a-glance view of your account: * **Net value** of the connected wallet * **Fees & Interest** earned over the account's lifetime * **Claimable Rewards** available now * **KMNO Staked** * **Season Rewards** Below the tiles, the **Net Value** chart plots your portfolio value over time, with 7D, 30D, and 3M ranges. Use the **Display Value In** dropdown in the top right to switch all figures between USD and SOL. ![Display Value In USD or SOL](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/portfolio/portfolio-data-2.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=1234d2f8c04fe59eaec08a5fc499d856) ## Positions The **Positions Overview** tab lists your active positions across every Kamino product: lending, borrowing, liquidity, Earn, and Multiply. It is the quickest way to see where your assets are deployed. Click any position to open and manage it. ![Positions Overview](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/portfolio/positions.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=59d93cac6330291bbec01537d56d39e2) ## My Rewards The **My Rewards** tab shows rewards you have earned that are available to claim. Review what is available and claim directly from here. ![My Rewards](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/portfolio/rewards.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=ecae318f7823a51fc2777eef88fb6f1e) ## Transaction History The **Transaction History** tab is a record of your past Kamino activity for the connected wallet: deposits, withdrawals, borrows, repayments, and other portfolio transactions. ![Transaction History](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/portfolio/transaction-history-1.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=ba1b6ec13f3e656006083d48a8d989f8) For each entry, use the arrow icon to open the on-chain transaction in a block explorer. From the menu in the top right, you can also **Export CSV** or **Copy** your history. ![Export CSV or Copy from the menu](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/portfolio/transaction-history-2.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=b6d33ad9489510d54779c6dfb1d952bd) ## Swap History The **Swap History** tab shows your previous swaps for the connected wallet, including the assets involved and the transaction details. Use the arrow icon to open any swap on-chain in a block explorer. ![Swap History](https://mintcdn.com/kamino-3d73a151/PLATQ08CVUwkaQvR/images/learn/portfolio/swap-history.webp?fit=max\&auto=format\&n=PLATQ08CVUwkaQvR\&q=85\&s=6fbf37f5c5068b41417a4dc6103f03dd) # How to Swap Tokens Source: https://docs.kamino.com/learn/swap/how-to-swap Swap tokens on Solana using Kamino Swap, a meta-aggregator that compares routes across multiple engines to find the best output. Kamino Swap is a meta-aggregator: it requests quotes from multiple routing engines simultaneously, compares them, and selects the route that returns the most tokens. There is no platform fee. ## Before You Start * You need a **connected Solana wallet** with the tokens you want to swap. * Keep a small amount of **SOL** in your wallet to cover network transaction fees. * Look for the **green verified badge** next to token names. Token names and symbols can be copied, so always verify you are selecting the correct asset. ## Swap Step by Step **1. Connect your wallet** Open Kamino Swap and connect your wallet using the button in the top-right corner. Once connected, your available token balances appear in the swap interface. **2. Select the token to sell** Click the token field in the **Sell** section to open the token selector. Search by name, symbol, or contract address. Confirm the green verified badge before selecting. ![Select token to sell](https://mintcdn.com/kamino-3d73a151/nSj-oZqZbrFVVVcD/images/learn/swap/select-token-to-sell.webp?fit=max\&auto=format\&n=nSj-oZqZbrFVVVcD\&q=85\&s=4ea972ed0cd6506c635f598975fb6357) **3. Select the token to buy** Click the token field in the **Buy** section and choose the token you want to receive. Use the arrow button between the two fields to reverse the swap direction. ![Select token to buy](https://mintcdn.com/kamino-3d73a151/nSj-oZqZbrFVVVcD/images/learn/swap/select-token-to-buy.webp?fit=max\&auto=format\&n=nSj-oZqZbrFVVVcD\&q=85\&s=347ce04baa95f8af8f327aa0b49d16bb) **4. Enter the swap amount** Type the amount you want to swap. Use the **Max** or **Half** shortcuts to fill in your full or half balance. The system fetches a price quote automatically once you enter an amount. ![Enter swap amount](https://mintcdn.com/kamino-3d73a151/nSj-oZqZbrFVVVcD/images/learn/swap/enter-amount.webp?fit=max\&auto=format\&n=nSj-oZqZbrFVVVcD\&q=85\&s=4b0309e8c7e88cdd6e14097c657e8508) **5. Review settings** Click the **settings cog** below the swap amount to adjust slippage tolerance and priority fee. **Slippage tolerance** is the maximum price movement you accept between receiving the quote and the transaction executing. The default is **0.5%**, which is suitable for most swaps. Lower slippage gives tighter price protection but increases the chance of the transaction failing. Higher slippage makes execution more likely but may return fewer tokens. **Priority fee** controls how quickly Solana processes your transaction. The default **Normal** setting is sufficient for most conditions. Increase it during periods of network congestion. ![Review settings](https://mintcdn.com/kamino-3d73a151/nSj-oZqZbrFVVVcD/images/learn/swap/review-settings.webp?fit=max\&auto=format\&n=nSj-oZqZbrFVVVcD\&q=85\&s=2bc3663cff16b8813d60f295b137b675) **6. Review the quote** Before confirming, check: * **Estimated output** and **minimum received** * **Exchange rate** for the token pair * **Price impact**: the effect your trade has on the available price If the price impact looks unusually high, consider reducing the swap size. High impact usually means limited liquidity or that the trade is large relative to the available market. Quotes refresh automatically as market conditions change. Kamino also runs **active simulation**, which checks whether the quoted transaction will execute under current on-chain conditions, so the displayed output closely reflects what the transaction is actually expected to return. ![Review swap quote](https://mintcdn.com/kamino-3d73a151/nSj-oZqZbrFVVVcD/images/learn/swap/review-quote.webp?fit=max\&auto=format\&n=nSj-oZqZbrFVVVcD\&q=85\&s=3faf19f7c26332e3019f9948db08a8e0) **7. Confirm in your wallet** Click **Swap** to send the transaction to your wallet. Your wallet will display the tokens leaving, the tokens arriving, and any network fees. Verify the details match your intended swap, then approve. If the assets or amounts shown in your wallet do not match the swap you intended, cancel the transaction. Once confirmed, the transaction is submitted to the Solana network and the swapped tokens appear in your wallet. ![Confirm in wallet](https://mintcdn.com/kamino-3d73a151/nSj-oZqZbrFVVVcD/images/learn/swap/confirm-wallet.webp?fit=max\&auto=format\&n=nSj-oZqZbrFVVVcD\&q=85\&s=65aed71cbd6dab18f9fa92a797fa449b) ## If a Swap Fails Swaps can fail if market conditions change between quoting and execution. If this happens: * Refresh the quote and try again. * Check that you have enough SOL to cover transaction fees. * Increase slippage tolerance slightly for volatile tokens. * Reduce the swap size if price impact is high. * Wait briefly if conditions are changing rapidly. Your original tokens remain in your wallet when a swap fails. A small network fee may still apply. # Borrow Orders Source: https://docs.kamino.com/products/borrow/borrow-orders Standing borrow orders that fill automatically as liquidity becomes available Borrow Orders are standing requests to borrow a specified asset that fill automatically as liquidity enters the market. In supply-constrained pools, borrow demand regularly exceeds available supply — without automation, users must either monitor availability continuously or run bots to capture liquidity the moment it appears. A Borrow Order removes that requirement: you specify the asset, amount, and expiry, and the protocol fills the order automatically whenever matching supply is available. Interest does not accrue on unfilled portions — it begins only when each portion fills. ## How orders fill Orders fill as liquidity becomes available in the target market. A single order can fill incrementally across multiple transactions — a \$300,000 order might fill in \$50,000 chunks as separate deposits enter the pool. Each filled portion begins accruing interest immediately and the borrowed funds are sent directly to your wallet at the time of fill. The unfilled remainder stays open until it fills, expires, or you cancel it. Fill ordering is random. There is no priority by order size, submission time, or any other factor — the first transaction to execute the fill wins. This means large orders receive no advantage, and older orders have no queue position. > [!NOTE] > > Interest starts accruing on each filled portion at the slot it fills. An unfilled order has zero interest cost regardless of how long it has been open. ## Post-fill LTV Post-fill [LTV](/products/borrow/concepts#ltv--the-three-values) is the governing constraint for all Borrow Order operations. It is calculated as: ``` Post-fill LTV = (Active borrow + Total open order amount) / Collateral value ``` The system treats all open orders as if they will fill simultaneously. A **5% buffer** is enforced: post-fill LTV cannot exceed `Max LTV − 5%`. This determines how much additional borrowing capacity you have available for new orders: ``` Maximum new order capacity = Max LTV − 5% − Current LTV ``` The buffer exists because if post-fill LTV were at Max LTV and collateral prices dropped, any fills executing at that moment would make the position immediately liquidatable. The 5% margin provides a safety window between the worst-case fill scenario and the liquidation threshold. Post-fill LTV is distinct from the Current LTV shown in your position overview: | Metric | What it includes | Used for | | - | - | - | | Current LTV | Active borrow ÷ collateral value | Liquidation health, position display | | Post-fill LTV | (Active borrow + all open orders) ÷ collateral value | Order capacity, collateral withdrawal limits | Current LTV is not affected by open orders. Only filled borrows contribute to it. **Collateral withdrawals are also gated by post-fill LTV.** You cannot withdraw collateral if doing so would push post-fill LTV above `Max LTV − 5%`. The restriction is evaluated against the worst case — all open orders filling after the withdrawal. See [Borrowing](/products/borrow/borrowing) for a full explanation of LTV ratios. > [!WARNING] > > Collateral withdrawals are blocked if the withdrawal would push post-fill LTV above Max LTV minus 5%, even if your current active borrow leaves substantial headroom. ## Collateral price drops If the value of your collateral falls, open orders are not automatically reduced or cancelled — they remain at their original amount. However, the system will not execute a fill that would breach the post-fill LTV limit. If a fill would push post-fill LTV above `Max LTV − 5%`, the order simply does not fill until conditions change. If collateral value recovers or you add more collateral, the order becomes fillable again at its original amount — no action is required on your part. ## Order management You can have **one open Borrow Order per debt asset per obligation**. Partial fills, amount adjustments, and expiry adjustments cover all management needs without requiring multiple concurrent orders. | Action | Behavior | | - | - | | Cancel order | Removes the unfilled portion. Any filled portions remain as active borrows. No fees. | | Adjust amount | Increase or decrease the unfilled order amount, subject to post-fill LTV constraints. | | Adjust expiry | Change the expiry date on an open order. | On expiry, the unfilled portion is removed automatically. Any portions that filled before expiry remain as active borrows and continue accruing interest normally. There are no fees or penalties for expired orders. ## Fixed-rate borrow orders Borrow Orders are also the mechanism for requesting fixed-rate loans. In the fixed-rate context, an order includes a target rate and term alongside the borrow amount. When [Conditional Liquidity](/products/borrow/concepts#conditional-liquidity--the-key-innovation) exists at matching terms, the fill is atomic. When no matching liquidity exists, the order remains open as visible demand that vault managers can observe and fill. This means a fixed-rate borrow order functions both as an execution instruction and as a price signal to the supply side of the market. See [Fixed Rates](/products/borrow/fixed-rates) for mechanics and rate negotiation details. → See [Concepts](/products/borrow/concepts#borrow-orders) for a full explanation of how fixed-rate Borrow Orders work, including partial fills, random fill order, and the relationship with Conditional Liquidity. # Borrowing Source: https://docs.kamino.com/products/borrow/borrowing How borrowing works on Kamino — collateral, LTV, interest, and repayment ## Overcollateralized model All positions on Kamino Borrow are [overcollateralized](/products/borrow/concepts#overcollateralized-lending). You cannot borrow more than your collateral is worth, and there are no unsecured loans. The protocol continuously monitors the ratio of your debt to your collateral value, and positions that breach [liquidation thresholds](/products/borrow/concepts#liquidation-mechanics) become eligible for liquidation. This model means every dollar of borrowing is backed by more than a dollar of collateral at all times. ## LTV ratios Three [LTV](/products/borrow/concepts#ltv--the-three-values) ratios govern every position: * **Current LTV** — Your actual debt-to-collateral ratio at any moment. This is used to assess position health and determine how close you are to liquidation. * **Max LTV** — The maximum LTV at which you can open or add to a borrow position. Acts as a buffer between normal operation and the liquidation threshold. * **Liquidation LTV** — The threshold at which your position becomes eligible for liquidation. Always higher than Max LTV, providing a window between the borrowing ceiling and forced liquidation. For example, SOL collateral might have Max LTV = 75% and Liquidation LTV = 80%. You can borrow up to 75% of your SOL value, but your position isn't liquidatable until the ratio reaches 80%. ## Borrow Factors [Borrow Factors](/products/borrow/concepts#borrow-factors) adjust your effective borrowing capacity based on the risk profile of the asset you are borrowing. Stable, liquid assets like USDC carry a Borrow Factor of 1 — no adjustment applied. Higher-risk assets carry Borrow Factors above 1, which reduce the capacity you can borrow against a given amount of collateral. The formula governing borrow capacity is: ``` Borrow Capacity = (Collateral Value × Max LTV) / Borrow Factor ``` With \$100 of SOL collateral and Max LTV of 80%: | Debt Asset | Borrow Factor | Available to Borrow | | - | - | - | | USDC | 1 | \$80 | | BONK | 2 | \$40 | Borrow Factors also affect the effective Liquidation LTV for a position. Positions holding higher-BF debt assets will be liquidatable at a lower actual debt value than the headline Liquidation LTV suggests — the Borrow Factor compresses the safety margin from both sides. ## Interest Interest accrues continuously on all outstanding debt. Rates are variable and determined by the [utilization](/products/borrow/concepts#how-variable-rates-work) of the lending pool — as more of a pool's liquidity is borrowed, the rate rises. Your debt balance grows over time, which means the health of your position can deteriorate even if collateral prices remain flat. > [!WARNING] > > Interest rates are variable. If borrow rates rise significantly or collateral value falls, your position will move toward liquidation without any action on your part. Monitor your positions regularly and maintain a buffer below Max LTV. For a full explanation of how rates are calculated, see [Fees & Interest Rates](/products/borrow/fees). ## Repay with Collateral Kamino lets you repay debt using your deposited collateral directly, without needing to source the repayment token externally. The protocol uses Kamino Swap to convert a portion of your collateral into the debt asset and repays the loan in a single atomic transaction. This is useful for deleveraging a position when you do not hold the borrowed asset elsewhere — you can reduce exposure and improve position health without needing to move funds in from outside. ## Multiple assets In Cross Mode, a single position can hold multiple collateral assets and multiple debt assets simultaneously. Position health is assessed across all assets combined, meaning your combined collateral value is measured against your combined debt. This allows more flexible capital use, but also means that a decline in any single collateral asset affects the health of the whole position. See [Markets](/products/borrow/markets) for a full explanation of Cross Mode vs. Isolated Mode. # Concepts Source: https://docs.kamino.com/products/borrow/concepts The foundational ideas behind Kamino Borrow — from reserves and markets to how variable and fixed rates work Kamino Borrow operates two distinct rate models: **variable** and **fixed**. Neither is the default or the special case. Variable rates suit flexible, opportunistic positions. Fixed rates suit carry strategies, planned time horizons, and institutional deployment. Both are fully supported, first-class models built on the same underlying infrastructure. The concepts below apply to both unless a section is explicitly labelled otherwise. *** ## Foundations ### The peer-to-pool model Kamino Borrow is a peer-to-pool lending market. Depositors contribute assets into shared liquidity pools. Borrowers draw from those pools. The protocol mediates automatically — setting rates, tracking position health, and executing liquidations — with no counterparty matching required. This contrasts with order-book lending, where a specific lender must be matched to a specific borrower before a loan can begin. Peer-to-pool lending has no such requirement. Capital is fungible within the pool, and any borrower can draw from it the moment they post sufficient collateral. The consequence is permissionless borrowing: no underwriting, no identity check, no credit assessment. The collateral is the only guarantee. As long as the borrower's position remains overcollateralized, the protocol enforces the loan automatically and the lender has no exposure to borrower identity or intent. *** ### What is a reserve A reserve is a pool for a single asset within a market. All deposits of USDC in the SOL/BTC Market enter the same USDC reserve. All borrows of USDC in the SOL/BTC Market draw from that same pool. The same deposited dollar is lent simultaneously to multiple borrowers through accounting — the reserve tracks total deposits, total amount borrowed, the current rate, and each lender and borrower's proportional share. Each asset has its own reserve because different assets carry different risk profiles and warrant different rate parameters. SOL and USDC should not share a pool — their volatility, liquidity, and acceptable LTV ratios differ materially. Reserves exist in both rate models. In the variable model, there is one reserve per asset per market. In the fixed model, there is one reserve per rate-and-duration combination per asset per market — the USDC 5.5% 3-month reserve is completely separate from the USDC 6.0% 6-month reserve. The reserve is the fundamental unit across both models. *** ### What is a market A market is an isolated collection of reserves governed by shared risk parameters. Collateral deposited in one market cannot be used to borrow from another. Liquidity does not flow between markets. Risk does not either — a liquidation cascade or parameter change in one market has no effect on positions in another. Kamino currently operates four markets: | Market | Purpose | | - | - | | **SOL/BTC Market** | The primary market. Supports Solana's core assets: SOL, wETH, tBTC, USDC, USDT, JitoSOL, mSOL, bSOL. Deepest liquidity, broadest collateral support. | | **JLP Market** | Optimised for JLP (Jupiter Liquidity Provider tokens) as collateral. Allows JLP holders to borrow against their LP position without unwinding it. | | **Altcoins Market** | Supports higher-volatility assets with tighter risk parameters and lower LTV ratios. For assets that do not meet SOL/BTC Market standards. | | **Prime Market** | Institutional-grade market supporting real-world assets (RWA) and requiring the PRIME token for access. Custom risk configurations for larger positions. | For full detail on market structure, position modes, and cross-collateralization, see [Markets](/products/borrow/markets). *** ### Overcollateralized lending Every loan on Kamino is backed by more collateral value than the loan itself is worth. A borrower cannot receive \$1,000 without first depositing collateral worth more than \$1,000. This requirement exists because DeFi lending has no identity layer. There is no credit history, no legal recourse, and no way to compel repayment beyond the collateral already posted. Overcollateralization is not a tax on the borrower — it is the mechanism that makes anonymous, permissionless lending possible at all. It substitutes collateral for the creditworthiness checks that traditional lenders rely on. The degree of required overcollateralization varies by asset and market, governed by Max LTV and Liquidation LTV parameters. *** ### LTV — the three values LTV (Loan-to-Value) measures your debt relative to your collateral. ``` LTV = debt value / collateral value ``` Three distinct LTV values apply to every position: | LTV value | Definition | | - | - | | **Max LTV** | The ceiling at which you can open or increase a borrow. You cannot originate new debt that would push your LTV above this value. | | **Liquidation LTV** | The threshold at which your position becomes eligible for liquidation. Always higher than Max LTV. | | **Current LTV** | Your live debt-to-collateral ratio right now. The number that determines position health at every moment. | **The buffer that actually matters** is the gap between Current LTV and Liquidation LTV — not the gap between Current LTV and Max LTV. Max LTV is already consumed at origination. The real safety margin is how much further your collateral can fall before the protocol can begin liquidating you. Concrete example: * Deposit 50 SOL at \$200 = \$10,000 collateral. Borrow \$7,000 USDC → Current LTV = 70% * SOL drops to \$175 → collateral = \$8,750 → Current LTV = **80%** → eligible for liquidation The formula for tolerable price decline: ``` Tolerable decline = (Liquidation LTV − Current LTV) / Liquidation LTV = (80% − 70%) / 80% = 12.5% ``` A 12.5% SOL price drop triggered liquidation from a position that started comfortably below Max LTV. **Interest compounds your risk silently.** At a 10% annual borrow rate on \$7,000 USDC, with collateral prices flat: | Time | Debt balance | Current LTV | | - | - | - | | Day 1 | \$7,002 | 70.02% | | 6 months | \$7,350 | 73.50% | | 12 months | \$7,700 | 77.00% | After a year, the position has drifted from 70% to 77% LTV with no price movement. This applies identically in both variable and fixed rate models — fixed rates eliminate rate uncertainty but not the compounding effect. > [!WARNING] > > Variable borrow rates can spike during high-utilization periods. A rate spike from 10% to 40% makes debt accumulate four times faster than expected. Monitor positions during volatile markets. *** ### Borrow Factors Borrow Factors are a risk adjustment multiplier applied to debt assets. Stable, liquid assets like USDC carry a Borrow Factor of 1.0 — no adjustment. Higher-risk or less liquid assets carry Borrow Factors above 1.0, which reduce your effective borrowing capacity and raise your risk-adjusted LTV. ``` Risk-adjusted debt = actual debt value × Borrow Factor ``` ``` Borrow Capacity = (Collateral Value × Max LTV) / Borrow Factor ``` With \$10,000 collateral and 80% Max LTV: | Debt asset | Borrow Factor | Available to borrow | | - | - | - | | USDC | 1.0 | \$8,000 | | BONK | 2.0 | \$4,000 | A Borrow Factor of 2.0 halves your effective borrowing capacity. It also doubles your effective risk-adjusted LTV for an equivalent real debt size — a position that looks healthy by market values may be much closer to liquidation once the Borrow Factor is applied. > [!WARNING] > > Always check the Borrow Factor before borrowing any asset. It may make your effective safety buffer significantly smaller than headline market values suggest. *** ### Liquidation mechanics When a position's Current LTV exceeds Liquidation LTV, it becomes eligible for liquidation. Two design choices protect borrowers from catastrophic outcomes: **Close factor — 20% per round.** Liquidators may only close up to 20% of a position in a single liquidation event. If the position remains above Liquidation LTV after the first round, a second round can be applied. A borrower who adds collateral or repays debt between rounds can stop the process entirely. This prevents full wipeout from a brief, shallow breach. If LTV exceeds the market's insolvency-risk threshold (typically 95%), the close factor increases to 100% to prevent bad debt. **Dynamic liquidation bonus.** The bonus paid to liquidators scales with how far the position's LTV has breached the Liquidation LTV threshold. It starts at a per-reserve minimum bonus for positions just past the threshold, scales upward as the breach deepens, and is capped at a per-reserve maximum. Near 100% LTV, a solvency cap reduces the bonus so that liquidation does not worsen the position's health. Borrowers liquidated promptly near the threshold lose less collateral; deeper breaches carry larger bonuses but more execution risk for the liquidator. For full liquidation mechanics, eligibility conditions, and how to avoid liquidation, see [Liquidations](/products/borrow/liquidations). *** ### eMode / Elevation Mode When collateral and borrowed assets are closely correlated — for example, JitoSOL as collateral and SOL as debt — their prices move together. A price shock large enough to push a JitoSOL/SOL position into liquidation is far less likely than a shock to a JitoSOL/USDC position. eMode (Elevation Mode) recognizes this by permitting significantly higher Max LTV for approved correlated pairs. | Mode | Example pair | Approximate Max LTV | Approximate max leverage | | - | - | - | - | | Standard | SOL / USDC | \~75% | \~4x | | eMode Main | mSOL, bSOL, JupSOL / SOL | \~87% | \~7.7x | | eMode Jito | JitoSOL / SOL | \~90% | \~10x | eMode is the mechanism that powers Kamino's [Multiply](/products/multiply) product — capital-efficient leveraged exposure to correlated asset pairs. For configuration and eligibility, see [Markets](/products/borrow/markets). *** ## Variable Rate Model ### How variable rates work Variable rates are governed by a single observable signal: **utilization** — the fraction of a reserve's total deposits that is currently borrowed. ``` Utilization = borrowed amount / total deposited amount ``` The system is self-correcting. High utilization pushes rates up, which simultaneously discourages new borrowing and attracts new deposits — both effects reduce utilization. Low utilization pushes rates down, which stimulates borrowing and may prompt lenders to redeploy capital elsewhere — both effects raise utilization. Over time, rates tend toward an equilibrium where the reserve operates within a target utilization band. Two extremes to understand: * **100% utilization** — all deposited capital is borrowed. No withdrawals are possible until borrowers repay. This is the failure mode the rate curve is designed to prevent. * **0% utilization** — no capital is borrowed. Lenders earn nothing. This resolves naturally as borrowers arrive. *** ### The interest rate curve and the kink Kamino uses a two-segment rate curve with a **kink** at the target utilization level. **Below the kink** — rates rise gradually. The pool is healthy: borrowing is affordable, withdrawal liquidity is available, lenders earn competitive yield. **Above the kink** — rates escalate steeply. This is a correction mechanism, not a punishment. The steep rates create strong pressure for borrowers to repay and for new lenders to deposit, which pulls utilization back below the kink. The high rates are temporary — they resolve as the market responds. Illustrative borrow rates for a USDC reserve: | Utilization | Approximate borrow rate | | - | - | | 40% | 3–5% | | 80% (kink) | 12–18% | | 90% | 35–60% | | 95% | 90–160% | **What lenders actually earn:** ``` Supply APY ≈ Borrow Rate × Utilization × (1 − Protocol Spread) ``` At 12% borrow rate, 80% utilization, 15% protocol spread: ``` Supply APY = 12% × 80% × (1 − 0.15) = 8.16% ``` Supply APY is always below the borrow rate because the idle portion of the pool earns nothing but still sits in the denominator of the utilization calculation. Higher utilization means more of the pool is earning, which is why high-utilization reserves offer better lender yields. **Trade-off summary:** Variable rates offer maximum flexibility — borrow and repay at any time, no fixed term, no maturity to manage. The cost is zero rate certainty. A 5% borrow rate today can be 20% tomorrow if utilization spikes. *** ## Fixed Rate Model ### Why fixed rates exist — and what they trade off Variable rates are capital-efficient and self-correcting, but they are unpredictable. A leveraged carry strategy that earns 8% annualised can flip to a loss overnight if the borrow rate spikes from 5% to 20%. For treasury management or institutional deployment, unpredictable borrowing costs are a planning problem, not just a risk. Fixed rates solve this by locking the borrow cost for a defined term. A 5.5% 3-month loan charges 5.5% through the end of its term regardless of what utilization does in the variable pool. The cost is flexibility — you are committed to a term, and exiting early carries a penalty during the first term. Neither model is inherently superior. They serve different needs: | | Variable | Fixed | | - | - | - | | Rate certainty | None | Full — for the term | | Flexibility | Full — repay any time | Limited — early exit penalty in first term | | Best for | Opportunistic positions, short-horizon trades | Carry strategies, treasury deployment, structured positions | | Complexity | Low | Higher — terms, rollover, withdrawal queue | *** ### The rate grid Fixed rates are not a modification of the variable pool. They are a separate structure: multiple independent reserves per debt token, each defined by a specific rate AND a specific duration. The USDC 5.0% 3-month reserve and the USDC 5.5% 6-month reserve are entirely distinct: * Own liquidity pool * Own set of borrowers * Own set of lenders * No interaction between them Example rate grid for USDC in a single market: | Rate | 1 month | 3 months | 6 months | 12 months | | - | - | - | - | - | | 5.0% | USDC 5.0% 1m | USDC 5.0% 3m | — | — | | 5.5% | — | USDC 5.5% 3m | USDC 5.5% 6m | — | | 6.0% | — | USDC 6.0% 3m | USDC 6.0% 6m | USDC 6.0% 12m | | 7.0% | — | — | USDC 7.0% 6m | USDC 7.0% 12m | Not every cell is populated. Curators and governance determine which rate-duration combinations exist. A large repayment in one reserve does not affect liquidity in any other. Reserve isolation is complete. *** ### The yield curve and term premium The rate grid creates a visible, on-chain term structure — what the market currently prices for 1-month, 3-month, 6-month, and 12-month USDC lending. This is the yield curve for that asset. The **term premium** is the additional yield lenders require to lock capital for a longer duration. If the 3-month USDC rate is 5.0% and the 6-month rate is 5.5%, the term premium for the additional 3 months is 0.5%. It reflects the lender's compensation for reduced liquidity and increased uncertainty over a longer horizon. When demand for longer-duration borrowing rises, rates in longer-duration reserves rise relative to shorter ones — the market signals that long-term capital is scarce. This is how traditional fixed-income markets work. Kamino's rate grid brings this price discovery on-chain for the first time in DeFi. *** ### Conditional Liquidity — the key innovation Fixed-rate reserves have an inherent problem for lenders: capital sitting in a fixed-rate reserve earns nothing until a borrower arrives. A vault pre-positioning into the USDC 5.5% 6-month reserve before any borrowers appear destroys yield — all that capital sits idle. Conditional Liquidity solves this. Capital remains in a variable-rate reserve, earning the live variable yield. The vault simultaneously posts a conditional signal on one or more fixed-rate reserves, declaring that it can fill up to a specified amount at that rate and duration. No capital moves. No yield is lost. When a matching Borrow Order is submitted: 1. The protocol pulls the required amount from the vault's variable-rate position 2. Deposits it into the target fixed-rate reserve 3. Delivers it to the borrower The entire move is atomic. Between signal and fill, the capital earns variable-rate yield. A single pool of capital can signal across multiple rate-duration pairs simultaneously. If the USDC 5.5% 3-month reserve fills first, the remaining signal on USDC 6.0% 6-month is satisfied from the same capital pool — first match wins, and only that portion moves. > [!NOTE] > > Conditional Liquidity is a vault-level feature. Retail lenders depositing directly into a reserve provide committed liquidity to that specific reserve immediately and do not post conditional signals. *** ### Borrow Orders In the variable model, borrowing is immediate: collateral posted, borrow executed in the same transaction (subject to available liquidity). In the fixed-rate model, borrowers express demand via a standing Borrow Order. A Borrow Order specifies: * **Debt token** — e.g., USDC * **Maximum acceptable rate** — the order will not fill at any rate above this ceiling * **Minimum duration** — the shortest term the borrower will accept * **Expiry** — how long the order remains open before auto-cancelling When matching Conditional Liquidity exists, the fill is atomic — the order executes immediately. When no matching liquidity exists, the order remains open as visible on-chain demand that vault managers can observe and respond to. **Partial fills are allowed.** A large order can fill in tranches over time as liquidity enters the market. Each filled portion begins accruing interest immediately. The unfilled remainder stays open. **Fill order is random.** There is no priority by order size, submission time, or any other factor. Large orders have no advantage over small ones. No interest accrues on unfilled portions. An open order that never fills costs nothing. *** ### Rollover and the withdrawal queue Fixed-rate loans have a defined term with an end date. Loans are created with auto-rollover on by default, and at the end date the protocol rolls the loan into a new fixed-rate term in the same reserve, at the same rate. Rollover succeeds when the reserve has liquidity available and no withdrawal tickets are queued, and the loan extends for another full term at the same rate. Rollover happens during a window that opens before the end date, with its length configured per market, and completes shortly after opening when liquidity is available. If the fixed-rate rollover does not succeed and the market has an open-term rollover window configured, the protocol attempts a **variable-rate fallback**: the position migrates into the variable-rate reserve for the same asset. If neither path succeeds, the loan does not roll over and there is no pending state. You can also repay and close the loan at any time before the end date. **Rollover is not guaranteed.** It requires available liquidity in the target reserve and no lenders queued for withdrawal. **The withdrawal queue** is how lenders signal intent to exit before term end. Lenders cannot withdraw on demand mid-term, because capital is committed for the duration. Instead, they submit a withdrawal ticket specifying the amount they want returned. Tickets enter a per-reserve FIFO queue and fill as capital re-enters through repayments. The queue directly gates borrower rollover. **Any queued withdrawal ticket in a reserve blocks rollover for all borrowers in that reserve.** Lenders wanting out take priority over borrowers wanting to stay. Borrowers planning to roll should check for queued tickets before the term ends. **Auto-repay.** A position that reaches its end date without rolling over, and that the borrower does not close, enters Auto-repay: Kamino gradually repays the debt using the borrower's collateral, subject to fees, over a window configured per market, in small increments. Auto-repay begins at the end date, and its cost ramps with time, so closing early in the window costs less than letting it run, and closing before the end date avoids Auto-repay entirely. > [!WARNING] > > Taking no action at the end date is only safe when there is liquidity for the loan to roll over. If it cannot roll over and you do not close it, Auto-repay begins at the end date. Confirm the state of the relevant reserves ahead of the end date, and close the position if it cannot roll over. *** ### Early repayment You can repay a fixed-rate loan at any time before the term ends. During the **first term only**, an Early Repay Penalty applies. The penalty compensates lenders for the early return of capital they committed for the agreed duration. It is calculated based on the minimum interest that would have accrued had the loan run its full term. After a rollover into a subsequent term, there is no Early Repay Penalty. You can exit at any time without cost. > [!NOTE] > > The Early Repay Penalty applies during the first term only. Once a loan rolls over into a new term, you can exit at any time without penalty. # Fees & Interest Rates Source: https://docs.kamino.com/products/borrow/fees How interest rates are determined on Kamino Borrow — utilization curves, spreads, and liquidation penalties ## How interest rates work Kamino uses [utilization](/products/borrow/concepts#how-variable-rates-work)-based [interest rate curves](/products/borrow/concepts#the-interest-rate-curve-and-the-kink). Utilization is the ratio of borrowed assets to total deposited assets in a reserve — if a pool holds \$1,000 and \$700 is borrowed, utilization is 70%. As utilization rises, the borrow rate rises with it: low utilization means cheap borrowing, which attracts demand; high utilization means expensive borrowing, which pressures borrowers to repay and attracts new lenders. The curves are parameterised so that each reserve self-corrects toward a target utilization band. As utilization approaches 100%, rates escalate sharply to prevent full pool depletion and ensure lenders retain the ability to withdraw. ## Lender yield vs. borrow rate Lenders do not earn the full borrow rate. The supply APY is: ``` Supply APY ≈ Borrow Rate × Utilization ``` If borrowers pay 8% and utilization is 70%, lenders earn approximately 5.6%. The idle 30% of capital earns nothing and dilutes the aggregate return. This spread between borrow rate and supply APY is the structural cost of instant liquidity — by maintaining a buffer of undeployed capital, the pool guarantees lenders can exit at any time without waiting for borrowers to repay. ## Interest rate spreads The protocol retains a portion of interest paid by borrowers. This spread is taken from the borrow rate before it is passed through to lenders, and it varies by market and asset. | Asset(s) | Market | Protocol Spread | | - | - | - | | SOL | SOL/BTC Market | 11% | | USDC | SOL/BTC Market | 15% | | USDT | SOL/BTC Market | 15% | | mSOL, JitoSOL, bSOL | SOL/BTC Market | 15% | | wETH | SOL/BTC Market | 15% | | tBTC | SOL/BTC Market | 15% | | USDC | JLP Market | 20% | | USDC | Altcoins Market | 20% | > [!NOTE] > > Spreads are expressed as a percentage of interest paid by borrowers — not as a percentage of principal. A 15% spread on a 10% borrow rate means lenders receive 8.5%, not 10%. ## Liquidation Bonus When a position is liquidated, the liquidator receives a bonus paid in collateral on top of the amount needed to repay the debt. The bonus is dynamic and scales with how far the position's LTV has breached its Liquidation LTV threshold: * **At the threshold**: the bonus equals the per-reserve minimum (e.g., 2% for a major asset). * **Deeper breach**: the bonus scales upward, matching the distance between current LTV and Liquidation LTV, up to the per-reserve maximum. * **Near 100% LTV**: a solvency cap reduces the bonus so that liquidation does not push the position further toward insolvency. Each liquidation can close up to **20%** of the position's debt. If LTV exceeds the market's insolvency-risk threshold (typically 95%), the entire position can be liquidated at once. For the borrower, prompt liquidation is the better outcome: a position resolved just past the threshold incurs only the minimum bonus. A position that deteriorates further faces larger bonuses and, near the insolvency-risk threshold, full liquidation. See [Liquidations](/products/borrow/liquidations) for the full mechanics and a worked example. ## No other fees There are no deposit fees, withdrawal fees, or origination fees on Kamino Borrow. The only costs to borrowers are interest on outstanding debt and, if applicable, liquidation penalties on unhealthy positions. > [!TIP] > > Fixed Rates offers an alternative to utilization-based rates. For borrowers who need rate certainty, see [Fixed Rates](/products/borrow/fixed-rates). → See [Concepts](/products/borrow/concepts#the-interest-rate-curve-and-the-kink) for a deeper explanation of the rate curve, the kink, and how utilization governs lender yield. # Fixed Rates Source: https://docs.kamino.com/products/borrow/fixed-rates Fixed-rate borrowing on Kamino — rate certainty, term structure, and price discovery Fixed Rates introduces predictable borrowing costs to Kamino by letting borrowers lock in a rate for a defined term — 1 month, 3 months, 6 months, or longer — without exposure to utilization-driven rate swings. A 5.5% 3-month loan charges 5.5% through the end of its term regardless of what the variable rate market does. For lenders and liquidity vaults, Fixed Rates introduces [Conditional Liquidity](/products/borrow/concepts#conditional-liquidity--the-key-innovation): capital stays deployed and earning in variable reserves until a fixed-rate borrow match is found, eliminating the opportunity cost of pre-positioning. The system generates DeFi's first on-chain [yield curve](/products/borrow/concepts#the-yield-curve-and-term-premium) — a live, market-priced term structure visible across all active fixed-rate reserves. > [!NOTE] > > **Before you open a fixed-rate position, know how it ends:** > > * It carries a fixed rate and a single fixed end date. > * It rolls over into a new term automatically by default (auto-rollover). > * If it reaches the end date without rolling over and you do not close it, Auto-repay unwinds the position gradually. > * You can close the position at any time before the end date. ## The rate grid Each market maintains multiple [reserves](/products/borrow/concepts#what-is-a-reserve) per debt token. Instead of a single USDC reserve, the market exposes a full [rate grid](/products/borrow/concepts#the-rate-grid): one variable reserve plus one reserve per rate-and-duration combination currently offered. Each reserve is independent — it has its own liquidity, its own utilization, and its own borrowers. A position in the `USDC 5.5% 3m` reserve has no interaction with the `USDC 6.0% 6m` reserve. Example rate grid for USDC debt in a single market: | Rate | 1 month | 3 months | 6 months | 12 months | | - | - | - | - | - | | 5.0% | USDC 5.0% 1m | USDC 5.0% 3m | — | — | | 5.5% | — | USDC 5.5% 3m | USDC 5.5% 6m | — | | 6.0% | — | USDC 6.0% 3m | USDC 6.0% 6m | USDC 6.0% 12m | | 7.0% | — | — | USDC 7.0% 6m | USDC 7.0% 12m | Not every cell is populated. Curators and governance determine which reserves exist; liquidity is not guaranteed across all combinations. Reserves with no active lenders have no borrowing capacity regardless of demand. Reserve isolation matters for risk. A large repayment or withdrawal in `USDC 6.0% 6m` does not affect liquidity in adjacent reserves. Borrowers and lenders interact only within their specific reserve. ## Conditional Liquidity Liquidity vaults face an inherent problem when offering fixed-rate lending: capital sitting in a fixed-rate reserve earns nothing until a borrower arrives. Conditional Liquidity solves this by letting vaults signal capacity on fixed-rate reserves without moving capital. Capital remains in variable-rate reserves, earning the live variable yield. The vault posts a conditional signal on one or more fixed-rate reserves, declaring that it can fill up to a specified amount at that rate and duration. When a matching [Borrow Order](/products/borrow/borrow-orders) is submitted, the protocol atomically: 1. Pulls the required amount from the vault's variable-rate position 2. Deposits it into the target fixed-rate reserve 3. Delivers it to the borrower No capital sits idle waiting for a match. Between signal and fill, the vault earns variable-rate yield. A single pool of capital can be conditionally signaled across multiple reserves simultaneously — if the `USDC 5.5% 3m` reserve fills first, the signal on `USDC 6.0% 6m` is satisfied from the same capital pool, first match wins. > [!NOTE] > > Conditional Liquidity is a vault-level feature. Retail lenders depositing directly into a reserve do not post conditional signals — they provide committed liquidity to that specific reserve immediately. ## Borrow Orders Borrowers access fixed-rate reserves through the Borrow Orders system. A Borrow Order specifies the desired debt token, rate ceiling, term, and amount. The protocol matches the order against available conditional and committed liquidity across the rate grid and fills at the best available rate up to the borrower's ceiling. See [Borrow Orders](/products/borrow/borrow-orders) for the full mechanics of order submission, partial fills, and matching logic. ## Early repayment You can repay a fixed-rate loan at any time before the term ends, without waiting for the full term. During the **first term only**, an Early Repay Penalty may apply. The penalty compensates lenders who committed capital for the agreed duration. After a rollover into a subsequent term, there is no Early Repay Penalty. The penalty is calculated based on the minimum interest that would have accrued had the loan run longer. > [!NOTE] > > The Early Repay Penalty applies during the first term only. Once a loan rolls over into a new term, you can exit at any time without penalty. ## Rollover A fixed-term position moves through three phases: | Phase | Duration | What happens | | - | - | - | | **Active term** | The loan term (1, 3, 6, or 12 months) | Borrowing at your fixed rate. You can close at any time; an Early Repay Penalty applies during the first term. | | **Rollover window** | Configured per market | Kamino attempts to roll the position into a new fixed-rate term at the same rate. If no fixed-rate liquidity is available, the protocol can fall back to the variable-rate reserve for the same asset (if configured). You can repay, or wait for rollover to process automatically. If neither path succeeds and you have not repaid, Auto-repay begins at the end date. | | **Auto-repay** | Configured per market | The debt is gradually repaid using your collateral, subject to fees. | Fixed-rate loans have a term with a defined end date, equal to `loan_start + term_duration`. New loans are created with auto-rollover on by default, and the protocol rolls the loan over into a new fixed-rate term at the end date. The new term runs in the same reserve, at the same rate the borrower already has. Auto-rollover can be turned off later from the position. Rollover happens during a Rollover window that opens before the end date; its length is configured per market. When the reserve has liquidity, rollover completes shortly after the window opens. When there is no liquidity to roll into, the loan does not roll over, and there is no pending or in-progress state. ### How auto-rollover works During the Rollover window, if the reserve has available liquidity and no withdrawal tickets are queued, the loan extends for another full term at the same rate. If the fixed-rate rollover does not succeed and the market has an open-term rollover window configured, the protocol attempts a **variable-rate fallback**: the position migrates into the variable-rate reserve for the same asset in the same market. If neither path succeeds, the loan does not roll over and reaches its end date. Queued withdrawal tickets are the most common reason rollover is blocked: lenders requesting capital back take priority over loan extensions. See [Withdrawal Queue](#withdrawal-queue) below and [Concepts](/products/borrow/concepts#rollover-and-the-withdrawal-queue) for details. When auto-rollover is on but there is no liquidity to roll into (fixed or variable), you have two options: * **Wait** until the end of the term in case liquidity is seeded at the last moment, or * **Close the position** before the end date to avoid Auto-repay. ### Auto-repay A fixed-rate position that reaches its end date without rolling over is not closed in a single liquidation. Auto-repay begins at the end date and gradually repays the debt using your collateral, subject to fees, over a window configured per market, in small increments. The Auto-repay cost ramps with time. It starts small immediately after the end date and increases across the window, so a position closed early in the window settles at a lower cost than one left to run to the end of the window. Acting promptly is materially cheaper than waiting, and closing before the end date avoids Auto-repay entirely. > [!WARNING] > > Taking no action at the end date is only safe when there is liquidity for the loan to roll over. In tight liquidity conditions, a loan that cannot roll over begins Auto-repay at the end date, so confirm the state of the relevant reserves ahead of the end date and close the position if it cannot roll over. ## Withdrawal Queue Fixed-rate reserves lock lender capital for the duration of the term — lenders cannot withdraw on demand mid-term. To exit a position before borrowers repay, lenders submit a withdrawal ticket specifying the amount they want returned. Tickets enter a per-reserve FIFO queue. Queued tickets are filled as capital re-enters the reserve through borrower repayments and liquidations. A queued ticket also **blocks rollover for all borrowers in that reserve**, which means borrowers at maturity are forced to repay rather than extend. This is by design: lenders who have signaled intent to exit cannot be re-committed to a new term without their consent. Because the rollover block forces repayment at the next maturity wave, capital returns at the latest by the end of the reserve's term. Borrowers planning to roll should check whether any withdrawal tickets are queued before the term ends. > [!NOTE] > > Withdrawal ticket status is visible on-chain. If a reserve has queued tickets approaching your term end, plan for repayment rather than assuming rollover will succeed. ## The emerging yield curve The rate grid is more than a product feature — it is DeFi's first live term structure for lending rates. Each populated cell represents a market-clearing price for capital at a specific duration. The difference in rate between a 3-month reserve and a 6-month reserve for the same token is the [term premium](/products/borrow/concepts#the-yield-curve-and-term-premium): the additional yield lenders require to lock capital for longer. This structure enables real price discovery for duration risk. When demand for 6-month USDC borrowing rises, rates in 6-month reserves rise relative to 3-month reserves, signaling to the market that longer-term capital is scarce. Vaults can observe the spread across the grid and allocate conditional liquidity to the cells offering the best risk-adjusted yield for their duration tolerance. For borrowers managing treasury exposure or structured positions, the yield curve provides a reference: you can see exactly what the market charges across all available terms before committing, and choose the duration that best matches your liability profile. Variable-rate borrowing remains available via the standard reserve for positions where term certainty is not required — see [Borrowing](/products/borrow/borrowing) for how variable-rate positions work. > [!TIP] > > Fixed Rates integrates fully with [Multiply](/products/multiply). You can lock your borrow cost for the entire term of a leveraged position — turning a carry trade with variable rate risk into a predictable spread for a defined duration. # Borrow Source: https://docs.kamino.com/products/borrow/index Kamino's peer-to-pool lending market on Solana Kamino Borrow is a [peer-to-pool](/products/borrow/concepts#the-peer-to-pool-model) lending market on Solana. Lenders deposit assets into shared liquidity pools to earn yield; borrowers draw [overcollateralized](/products/borrow/concepts#overcollateralized-lending) loans against their collateral. The protocol handles rate discovery, position health tracking, and liquidations automatically — no counterparty matching required. Kamino Borrow also powers [Multiply](/products/multiply), which uses the lending market's underlying mechanics to construct leveraged yield positions in a single transaction. > [!NOTE] > > **Overcollateralized** means every loan is backed by more collateral value than the loan itself is worth. There is no credit history, no identity check, and no legal recourse — the collateral is the only guarantee. This is what makes anonymous, permissionless lending possible. [Learn more](/products/borrow/concepts#overcollateralized-lending) > [!NOTE] > > **Peer-to-pool** means depositors contribute to a shared pool and borrowers draw from it — no specific lender is matched to a specific borrower. The protocol intermediates automatically, enabling instant borrowing without waiting for a counterparty. [Learn more](/products/borrow/concepts#the-peer-to-pool-model) > [card] [Supplying](/products/borrow/supplying) > > How deposits enter liquidity pools, how kTokens work, and how supply yield is earned. > [card] [Borrowing](/products/borrow/borrowing) > > Collateral requirements, borrow limits, interest accrual, and how debt positions are managed. > [card] [Fixed Rates](/products/borrow/fixed-rates) > > Fixed-rate borrowing — rate certainty, term structure, conditional liquidity, and the on-chain yield curve. > [card] [Borrow Orders](/products/borrow/borrow-orders) > > Standing borrow orders that fill automatically as matching liquidity becomes available. > [card] [Markets](/products/borrow/markets) > > The structure of Kamino's lending markets, reserve configurations, and eMode. > [card] [Liquidations](/products/borrow/liquidations) > > How position health is measured, when liquidations trigger, and how the penalty system works. > [card] [Concepts](/products/borrow/concepts) > > The foundational ideas behind Kamino Borrow — reserves, markets, LTV, rate models, and more. # Liquidations Source: https://docs.kamino.com/products/borrow/liquidations How Kamino Borrow monitors position health and executes liquidations > [!WARNING] > > Once a position crosses Liquidation LTV, liquidation can occur at any time. There is no grace period — liquidation bots operate continuously. ## What triggers liquidation A position becomes eligible for liquidation when Current LTV exceeds Liquidation LTV. [LTV](/products/borrow/concepts#ltv--the-three-values) is calculated using risk-adjusted debt values: ``` Current LTV = risk-adjusted debt value / collateral value ``` Risk-adjustment applies [Borrow Factors](/products/borrow/concepts#borrow-factors) to each debt asset, which can compress the effective safety margin for positions holding higher-risk borrowed assets. See [Borrowing](/products/borrow/borrowing) for how Borrow Factors work. Positions do not liquidate the moment they are opened — they only become eligible when asset price movements push the LTV above the liquidation threshold after origination. ## Partial liquidations Kamino does not liquidate entire positions in a single event. Each liquidation can close a maximum of **20%** of the position's debt. If the position remains above Liquidation LTV after the first round, another round can be applied. This iterative structure protects borrowers who briefly breach the threshold: a small overshoot results in a proportionally small liquidation, not full position closure. A borrower who adds collateral or repays debt between rounds can stop the process entirely. If a position's LTV exceeds the market's insolvency-risk threshold (typically **95%**), the close factor increases to 100%, allowing full liquidation in a single event. This prevents positions from sliding into bad debt (where debt exceeds collateral value) when partial liquidations would be too slow. ## Dynamic liquidation bonus Liquidators are compensated with a bonus paid in collateral. The bonus is **dynamic**: it scales with how far the position's LTV has breached the Liquidation LTV threshold. The bonus moves through four phases as a position deteriorates: | LTV region | Bonus behavior | | - | - | | At Liquidation LTV | Starts at the **minimum bonus** configured for the reserve | | Above Liquidation LTV + min bonus | Scales upward: bonus equals the distance between current LTV and Liquidation LTV | | At Liquidation LTV + max bonus | Capped at the **maximum bonus** configured for the reserve | | Approaching 100% LTV | **Solvency cap**: bonus decreases so that it never exceeds the remaining distance to 100% LTV, because a bonus larger than that gap would worsen the position's health | ### Worked example For a reserve with a 2% minimum bonus, 8% maximum bonus, and 75% Liquidation LTV: | Current LTV | Bonus | Reason | | - | - | - | | 75% | 2% | At liquidation threshold, min bonus applies | | 77% | 2% | Distance (2%) equals min, floor still holds | | 80% | 5% | Distance (5%) exceeds min, bonus scales with breach | | 83% | 8% | Distance (8%) hits max cap | | 88% | 8% | Held at max | | 92% | 8% | Solvency cap begins: only 8% remains to 100%, bonus equals the cap | | 96% | 4% | Solvency cap overrides: only 4% remains to 100% | | 99% | 1% | Near bad debt, bonus minimized to protect solvency | ![Dynamic liquidation bonus curve](https://mintcdn.com/kamino-3d73a151/nSj-oZqZbrFVVVcD/images/products/borrow/dynamic-liquidation-bonus-curve.webp?fit=max\&auto=format\&n=nSj-oZqZbrFVVVcD\&q=85\&s=6a6366b8d22e7f34cb89f1a95e9062a4) The solvency cap is what prevents liquidations from pushing a position deeper into trouble. A position at 96% LTV cannot absorb an 8% bonus without exceeding 100% LTV, so the protocol forces the bonus down to what the position can sustain. This structure serves both sides. Borrowers who are promptly liquidated near the threshold lose less collateral (a small bonus). Liquidators facing deeper breaches earn larger bonuses but take on more execution risk. Near insolvency, the protocol prioritizes recovering the position over rewarding the liquidator. ## Who can liquidate Liquidations on Kamino Borrow are permissionless. Any actor can call the liquidation instruction on an unhealthy position and earn the bonus. In practice, automated bots monitor all open positions continuously and execute the moment a position crosses the liquidation threshold. The minimum bonus is sufficient compensation for immediate action. ## Auto-deleveraging (last resort) In extreme scenarios where standard liquidations fail to resolve unhealthy positions — such as severe market volatility or insufficient liquidator activity — Kamino has an auto-deleveraging mechanism that can proportionally reduce the largest leveraged positions in the system. This is a last-resort safety measure designed to protect the solvency of the lending pools when normal market incentives are insufficient. It has not been triggered in Kamino's operational history. ## Avoiding liquidation The primary levers for managing liquidation risk are: * **Maintain a buffer** — Keep Current LTV well below Liquidation LTV. A tight buffer leaves no margin for collateral price drops or rising debt from accruing interest. * **Monitor collateral value** — A decline in collateral price directly increases Current LTV, moving the position toward the liquidation threshold without any borrower action. * **Monitor borrow rates** — Variable rates mean your debt balance grows faster when rates rise. Sustained high utilization in a pool increases debt continuously, compressing your buffer. * **Add collateral or repay debt** — Either action reduces Current LTV. Repaying debt is typically more capital-efficient when you are close to the threshold. * **Use Repay with Collateral** — Allows you to deleverage atomically by converting deposited collateral into the debt asset and repaying in a single transaction, without needing to source the repayment token externally. See [Borrowing](/products/borrow/borrowing). # Markets Source: https://docs.kamino.com/products/borrow/markets Kamino Borrow's market structure — isolated environments, position modes, and elevation groups ## Market isolation Each Kamino Borrow [market](/products/borrow/concepts#what-is-a-market) is a self-contained environment with its own accepted collateral assets, borrowable assets, risk parameters, and liquidity. Collateral deposited in one market cannot be used to borrow from another, and the markets do not share liquidity or risk exposure. This isolation limits contagion — a liquidation cascade or parameter change in the JLP Market has no effect on positions in the SOL/BTC Market. ## Available markets > [card] SOL/BTC Market > > The primary market supporting Solana's core assets: SOL, wETH, tBTC, USDC, USDT, and liquid staking tokens including JitoSOL, mSOL, and bSOL. The deepest liquidity and the broadest asset selection across all Kamino markets. > [card] JLP Market > > Optimised for JLP (Jupiter Liquidity Provider tokens) as collateral. Enables JLP holders to borrow against their LP position without unwinding it. > [card] Altcoins Market > > Supports higher-volatility assets with correspondingly tighter risk parameters and lower LTV ratios. Designed for assets that do not qualify for the SOL/BTC Market's parameters. > [card] Prime Market > > Institutional-grade market with custom risk configurations. Designed for larger positions and counterparties with specific requirements. ## Cross Mode Cross Mode is the default position mode. A single Cross Mode position can hold multiple collateral assets and multiple debt assets at the same time. Position health — your [LTV](/products/borrow/concepts#ltv--the-three-values) — is calculated across all assets in the position together, so the combined collateral value is weighed against the combined debt. This cross-collateralization means that strong performance in one asset can offset weakness in another, but it also means that the health of every debt in the position is tied to the performance of all collateral. Cross Mode applies more conservative LTV parameters than Isolated Mode because the risk interactions between multiple assets are more complex. ## Elevation Groups (eMode) Assets within the same category can be configured as an [elevation group](/products/borrow/concepts#emode--elevation-mode), allowing significantly higher LTV ratios between them. The rationale is correlation: if collateral and debt are closely correlated assets — for example, JitoSOL as collateral and SOL as debt — the two values tend to move together, which substantially reduces the risk that a price move will push the position into liquidation. A JitoSOL/SOL position can therefore safely operate at much higher LTV than a JitoSOL/USDC position. Elevation Groups are the mechanism that powers Kamino's Multiply product, enabling capital-efficient leveraged exposure to correlated asset pairs. > [!NOTE] > > Similar to Isolated Mode, Elevation Groups are only supported in the SOL/BTC Market for select stablecoin and Multiply pairs. → See [Concepts](/products/borrow/concepts#emode--elevation-mode) for the full eMode rate and leverage table. # Supplying Source: https://docs.kamino.com/products/borrow/supplying How supplying assets into Kamino Borrow works ## Pool mechanics When you supply an asset, it enters a shared liquidity pool alongside all other lenders of that asset. Borrowers draw from this pool and pay interest on their outstanding debt. As a lender, you earn a proportional share of that interest — your share of the pool determines your share of the yield. There is no lender-borrower matching; the pool itself intermediates. ## kTokens On deposit you receive kTokens — for example, kUSDC or kSOL — that represent your claim on the pool. These are standard fungible tokens and can be transferred or used as collateral for other positions within Kamino. When you withdraw, you redeem your kTokens for the underlying asset plus all interest that has accrued since deposit. > [!NOTE] > > The exchange rate between kTokens and the underlying asset increases monotonically over time. As borrowers pay interest into the pool, each kToken becomes redeemable for a larger amount of the underlying asset. Your kToken balance does not change — your yield is entirely expressed through the appreciating exchange rate. ## How your yield is calculated Supply APY is a function of two variables: the borrow rate and the [utilization](/products/borrow/concepts#how-variable-rates-work) ratio. ``` Supply APY ≈ Borrow Rate × Utilization ``` If borrowers are paying 8% and the pool is 70% utilised, lenders earn approximately 5.6%. The remaining 30% of capital is idle and earns nothing, which dilutes the aggregate return. This is why high-utilization pools offer better supply yields — a greater fraction of the deposited capital is actively deployed earning interest. ## Utilization [Utilization](/products/borrow/concepts#how-variable-rates-work) is the ratio of borrowed assets to total deposited assets in a reserve. It is the primary input to Kamino's interest rate model. When utilization is high, borrow rates rise — this simultaneously discourages new borrowing and attracts new supply, pushing utilization back down. When utilization is low, borrow rates fall — this stimulates borrowing and may prompt lenders to redeploy capital elsewhere. The [interest rate curves](/products/borrow/concepts#the-interest-rate-curve-and-the-kink) are parameterised to keep each reserve operating within a target utilization band, balancing competitive supply yields against adequate withdrawal liquidity. ## What Supply APY includes and excludes The Supply APY figure reflects only interest paid by borrowers and passed through to lenders. It does not include KMNO emissions, external token incentives, or farm reward programs. Where such programs exist for a given reserve, they are displayed separately and stack on top of the base supply APY. ## Withdrawal liquidity You can withdraw at any time as long as the pool has available liquidity — that is, not all deposited assets are currently borrowed. Kamino's interest rate curves are designed to prevent full utilization from persisting: as utilization approaches 100%, rates escalate sharply, creating strong economic pressure for borrowers to repay and new lenders to deposit before the pool is exhausted. In practice this means a buffer of idle capital is maintained in all healthy reserves, and withdrawals are available under normal conditions. → See [Concepts](/products/borrow/concepts#the-interest-rate-curve-and-the-kink) for a full explanation of how the interest rate curve and kink work. # Products Source: https://docs.kamino.com/products/index Every Kamino product, explained and documented. ![](https://mintcdn.com/kamino-3d73a151/wADNksI7oget4gqs/images/borrow/kamino-dots.svg?fit=max\&auto=format\&n=wADNksI7oget4gqs\&q=85\&s=71e8a7b14234a4ab2271754603e62861) Every Kamino product,\ explained and documented ======================== ## Earn Grow your assets with managed, automated yield. ### [Lending Vaults](/products/lending-vaults) Single-token managed yield aggregation across Kamino's lending markets. ### [Liquidity](/products/liquidity) Automated concentrated liquidity vaults for Solana DEX pools. ## Institutional Yield Generate returns via regulated lending operations to institutional borrowers. ### [Overview](/products/institutional-yield) How institutional yield works and the lending operations behind each vault. ### [Legal Structure](/products/institutional-yield/structure) The SPV and lending operations behind Institutional Yield. ### [Concepts](/products/institutional-yield/concepts) Institutional lending, SPVs, and liquidity mechanics. ### [Commodity Yield](/products/institutional-yield/commodities) Yield backed by short-term, fully collateralized commodity trade finance. ### [Digital Assets Yield](/products/institutional-yield/digital-assets) Yield from overcollateralized institutional lending against digital assets held at qualified custodians. ### [Risks](/products/institutional-yield/risks) Risk disclosure for institutional yield products. ### [Loan Agreement](/products/institutional-yield/loan-agreement) The agreement depositors sign when they deposit into Institutional Yield. ### [FAQ](/products/institutional-yield/faq) Answers to the most common questions about Institutional Yield. ## Borrow Borrow against your assets, at variable or fixed rates. ### [Borrow](/products/borrow) Kamino's peer-to-pool lending market on Solana. ### [Fixed Rates](/products/borrow/fixed-rates) Rate certainty, term structure, and price discovery for borrowing. ### [Borrow Orders](/products/borrow/borrow-orders) Standing borrow orders that fill automatically as liquidity becomes available. ## Multiply Open leveraged positions in a single transaction. ### [Multiply](/products/multiply) Leveraged yield strategies that amplify staking, LP, and RWA returns in a single transaction. ### [How It Works](/products/multiply/how-it-works) The mechanics behind Multiply: flash loans, eMode, and yield amplification. ### [Strategies](/products/multiply/strategies) SOL LSTs, JLP, stablecoins, RWAs, and tokenized stocks: the Multiply strategy types and their mechanics. ### [Concepts](/products/multiply/concepts) Flash loans, looping, Net APY, and the categories of Multiply strategies. ### [Risks](/products/multiply/risks) Liquidation, borrow rate, and strategy-specific risks to understand before using Multiply. ## Swap Trade and route across Solana's best venues. ### [Swap](/products/swap) Routes trades across 15+ venues based on your specified parameters. ### [Limit Orders](/products/swap/limit-orders) Standing orders that execute at your target price, with zero slippage and zero fees. # Collateral & Transaction Structure Source: https://docs.kamino.com/products/institutional-yield/commodities/collateral How Commodity Loans are collateralized: escrowed cash, physical commodities, the security package, back-to-back contracts, and independent verification Every Commodity Loan is designed to stay covered at all times. Before funds are released into the trade, the loan is backed 1:1 by cash held in a segregated account. After release, it is more than 100% collateralized by physical commodities, measured against the contracted onward-sale price. This page explains how collateral changes through the transaction, how funds are released, and how the lending operation's security package protects the underlying Commodity Loan. *** ## The two collateral configurations ### 1. Escrowed cash Before shipment, financing may sit in a **segregated escrow account** at a tier-one bank, or back a **letter of credit** issued in favor of the commodity seller. These arrangements evidence the buyer's capacity to pay. Funds are released only after independent verification of the shipment and delivery of the agreed documentation. In this configuration the loan is matched 1:1 by cash. > [!NOTE] > > An **escrow account** is a bank account whose funds move only when pre-agreed conditions are met; here, that means verified shipment documents. A **letter of credit** is a bank's commitment to pay the seller, backed by that escrowed cash. ### 2. The physical commodity After funds are released, title to the goods passes to the Commodity Yield Fund and the loan is collateralized by the commodity itself. The commodity is bought at a discount to prevailing market prices, while its onward sale price is fixed by contract at a higher level. The contractual sale value is therefore expected to exceed the loan principal. Exposure to the physical commodity is typically short, often measured in days or weeks. The rest of the transaction lifecycle is cash-covered. *** ## Security package > [!NOTE] > > A **security package** is the bundle of legal protections a lender takes around a trade: control of the bank accounts, a claim on the sale proceeds, security over the goods, and performance bonds. If a counterparty fails, these give the lender enforceable routes to recover its money. Beyond the collateral itself, each Commodity Loan is documented with a security package that gives the lending operation legal control over the financed trade. Depending on the transaction, it can include: * **Control over cash flows**: money leaves the designated escrow or controlled accounts only when contractually defined conditions precedent and documentation requirements are met * **Assignment of receivables**: amounts owed by end buyers under the onward sale contracts are assigned or pledged to the lending operation, so payments flow to accounts it controls * **Security over the trading assets**: security interests (liens or equivalent) over the commodities and related trade assets while held by or on behalf of the lending operation * **Performance protection**: performance bonds or guarantees (often around 2% of transaction value), plus contractual cost-reimbursement obligations if a counterparty fails to perform Together with conservative collateral levels and continuous monitoring, these are designed to provide multiple layers of downside protection. They do not eliminate credit, operational, legal, market, or other risks. *** ## Back-to-back contracts Most transactions are structured **back to back**. The trader signs two contracts at or around the same time: a purchase contract for the commodity at a discount to market, and an onward sale contract with an end buyer at a fixed price. This is intended to substantially reduce open commodity price risk, though basis risk, counterparty risk, and timing risk may still arise. The Commodity Yield Fund typically retains title to the commodity until the end buyer pays under the onward sale contract. Both legs often settle on the same day: title transfers, and the proceeds are credited to segregated or controlled bank accounts. > [!NOTE] > > **Basis risk** is the risk that the two legs of the trade stop lining up; for example, a mismatch in terms between the purchase and the sale. **Timing risk** is a gap between the two legs settling. *** ## Escrow and banking Escrowed cash is held with global tier-one banks. Subject to the escrow terms and regulatory constraints, it may be invested in high-quality liquid instruments such as short-dated US Treasuries. The identity of banks, the nature of the instruments held, and portfolio composition are disclosed in transparency materials, subject to confidentiality and regulatory limitations. See [Transparency](/products/institutional-yield/commodities/transparency). *** ## Insurance and marine risk Financed goods are insured on an all-risk cargo basis for at least the full shipment value. The financing entity is named as loss payee or co-insured, so it can claim directly for covered loss or damage. Cover typically includes transit loss or damage, theft, war, and strikes, subject to standard exclusions and policy limits. Transactions are generally financed on a free-on-board (FOB) or similar basis. The lending operation does not assume unhedged freight, shipping, or marine price risk beyond the insured profile. Vessels are conventionally insured in established marine markets (including Lloyd's), which structurally exclude sanctioned and "gray-fleet" carriers. The lending operation applies sanctions controls. It seeks to avoid exposure to sanctioned jurisdictions, entities, and vessels, and undue concentration at maritime chokepoints. > [!NOTE] > > **Free on board (FOB)** means responsibility for the goods passes at the loading port. The financed leg of the trade therefore excludes ocean freight and its costs, and the cargo itself is insured for the journey. *** ## Independent verification Funds leave escrow only after independent verification of the shipment by internationally recognized inspection agencies such as SGS, Intertek, Alfred H. Knight, or Alex Stewart. These agencies check quality and quantity against the contractual specifications, and issue assay and weighbridge certificates that are contractually binding on the relevant parties. Payment is released only against a complete documentary package. Depending on the commodity and jurisdiction, this typically includes: * commercial invoice and packing list * certificate of origin, and export and mining permits where applicable * weighbridge certificate and independent assay/quality certificate * warehouse receipts or holding certificates * transport and shipping documents * the executed purchase and sale agreements and relevant insurance certificates *** ## Transaction lifecycle A typical transaction proceeds as follows: 1. **Trial transaction.** New counterparties typically start with a smaller trial transaction. It validates delivery performance, documentation, and operational processes before exposure scales. 2. **Contracting.** The trader signs a purchase contract at a discount to spot and an onward sale contract at a fixed price. Financing is placed into a segregated escrow account, or provided via a letter of credit backed by escrowed cash. 3. **Shipment and inspection.** The commodity ships, typically on FOB terms. At the agreed delivery point, an independent inspection agency verifies quality and quantity and issues the certificates. 4. **Settlement and title transfer.** After satisfactory inspection and documentation, escrow releases funds to the seller and title passes to the Commodity Yield Fund. The onward sale leg then settles: the end buyer pays, title passes to the buyer, and the proceeds are credited to a segregated or controlled account to repay the Commodity Loan and associated margins. 5. **Redeployment.** Proceeds flow back into a segregated account, restoring cash coverage. Subject to risk parameters and demand, they are typically redeployed into the next shipments of a rolling program (for example, repeated deliveries over 12 months). The vault's withdrawal notice periods are aligned with this cycle, so that where practicable, proceeds can be returned to the vault rather than rolled when redemptions are required. *** ## Commodities covered Collateral commodities include copper, oil, coffee, granulated sulphur, diesel, petrol, and jet fuel, among others. Short-term perishable commodities are excluded. The lending operation does not face sanctioned jurisdictions, countries, individuals, or trading entities thereof. *** ## LTV LTV varies per transaction. At all times, the loan is covered at minimum by either cash in a segregated bank account (held directly or backing a letter of credit) or a commodity worth more than the loan. When the position faces cash, coverage is 1:1; when it faces the commodity, the commodity was bought at a discount to spot and is worth more than the loan. LTV is measured against the **contractual sale price** of the commodity rather than a fluctuating spot price. Both legs of the transaction are contracted at fixed prices, so the value covering the loan is locked. When a transaction completes and the proceeds sit in the bank, the position is reported as cash. See [Transparency](/products/institutional-yield/commodities/transparency) for how this is reported per loan. *** ## Liquidations A liquidation would only occur if a buyer did not perform on a contracted purchase, which is unlikely, as buyers are purchasing the commodity at a discount to spot. Because settlement happens at the delivery point, a failure to perform is identified quickly, and the escrowed funds or the commodity are retained. Where a counterparty has posted a performance bond, that bond is also forfeited. If the lending operation is left holding the commodity, it can sell it to another buyer. # Example Trade: Copper Source: https://docs.kamino.com/products/institutional-yield/commodities/example-trade A step-by-step walkthrough of a single copper trade, from escrow funding to settlement This page walks through a single illustrative trade to show how the vault's capital is put to work and how the collateral behaves along the way. It follows a copper shipment, the most common trade type at launch. > [!NOTE] > > The numbers below are illustrative and rounded for clarity. Real trades vary in size, commodity, tenor, and structure; see [Collateral & Transaction Structure](/products/institutional-yield/commodities/collateral) for the full framework. *** ## The setup A copper trader has lined up two contracts at the same time: * **A purchase contract** to buy a shipment of LME Grade A copper cathodes at a discount to the market price: say **\$10.0M**. * **An onward sale contract** to sell that same shipment to an end buyer at a fixed price: say **\$11.0M**. Both contracts are signed before any capital moves. The trader needs short-term working capital to fund the purchase, and this is what the vault finances. Because the purchase and sale prices are both locked in, the trade is not expected to carry material open exposure to the copper price, although basis, counterparty, and timing risk may still arise. The vault deploys **\$10.0M** to finance the purchase. That \$10.0M is the loan we follow below. *** ## Step by step **1. Escrow funding** The \$10.0M is placed into a segregated escrow account at a global tier-one bank. At this point the loan is backed 1:1 by cash. **Collateral state:** escrowed cash · **\$10.0M** · fully cash-covered. **2. Shipment and inspection** The copper ships on a free-on-board basis. When it reaches the delivery point, an independent, internationally recognized inspection agency (such as SGS) verifies its quality against the LME Grade A specification (an assay) and its quantity (a weighbridge certificate). These certificates are binding on all parties. **Collateral state:** escrowed cash · **\$10.0M**; funds have not moved yet. **3. Payment release and title transfer** Once the full documentary package is satisfied (invoice, certificate of origin, permits, the inspection certificates, and transport documents), the escrow releases the \$10.0M to the seller and title to the copper passes to the fund. For a short window (hours in this illustrative trade, though depending on the transaction it can run to days or weeks), the position faces the physical copper. Valued at the contracted sale price of \$11.0M against a \$10.0M loan, the commodity is worth more than the loan. **Collateral state:** physical copper · **\~\$11.0M** · LTV \~91%. **4. Onward sale and settlement** In this illustrative trade, settlement of both legs occurs on the same day: the end buyer pays the contracted \$11.0M and title passes to them. The loan principal plus the trade margin returns to the segregated account. **Collateral state:** cash again · loan repaid. **5. Redeployment** The proceeds roll into the next transaction in the program. A copper program typically runs as a rolling 12-month schedule of repeat deliveries, and over the course of the program a cash buffer can build up in the controlled account, adding a further layer of coverage. **Collateral state:** escrowed cash, ready for the next trade. *** ## Where the collateral sits over time The key thing to see from the walkthrough is that the position faces the physical commodity only for a short window between paying the seller and receiving the buyer's funds: hours in this example, though it can extend to days or weeks. For the rest of the trade it is cash. | Phase | Collateral | Coverage | | - | - | - | | Awaiting shipment and inspection | Escrowed cash | 1:1 | | Between paying the seller and the buyer paying (hours in this example) | Physical copper, bought below market | Worth more than the loan (\~91% LTV) | | After settlement | Cash, then redeployed | 1:1 | This is why the vault reports the collateral type per loan: whether a position currently faces escrowed cash or the physical commodity. See [Transparency](/products/institutional-yield/commodities/transparency). *** ## If a counterparty fails to perform Suppose the end buyer fails to pay. Because settlement happens at the delivery point, the failure is identified quickly, and the fund still holds title to the copper, bought at a discount and so worth more than the \$10.0M loan. It can be sold to another buyer to recover principal, although recovery timing and value depend on finding a replacement buyer and completing the sale. Where the counterparty posted a performance bond, that bond is also retained. For the commodity-specific risk factors, see [Commodity Yield risks](/products/institutional-yield/risks#commodity-yield). # Commodity Yield Source: https://docs.kamino.com/products/institutional-yield/commodities/index Stablecoin-denominated yield from short-term, fully collateralized commodity trade finance through a CIMA-supervised fund Kamino Institutional Commodity Yield bridges onchain demand for stablecoin-denominated yield with institutional demand for short-term, collateralized credit. Global commodity trade depends on working capital. Producers and traders moving essential industrial commodities through supply chains, including metals, energy products, and selected non-perishable soft commodities, often need financing between purchasing goods and receiving payment from qualified off-takers. Returns in this market are generated primarily from the commercial margins on physical commodity trades. Financing demand is significant and recurring. Access to this market has historically been limited for onchain depositors. Kamino Institutional Commodity Yield provides that access through strict lending criteria, ongoing portfolio transparency, and a regulated off-chain lending operation implemented through an approved fund structure supervised by the **Cayman Islands Monetary Authority (CIMA)**. > [!NOTE] > > Kamino's on-chain protocol and Institutional Yield vaults (including the Commodity Yield vault) are not themselves licensed, approved, or supervised as regulated financial services or products by CIMA, the Financial Market Authority (FMA), or any other regulatory authority. References in this documentation to regulated funds, lending entities, or custodians relate exclusively to independent off-chain counterparties and do not extend to Kamino or its on-chain products. > [card] [Collateral & Transaction Structure](/products/institutional-yield/commodities/collateral) > > Escrowed cash, physical commodities, back-to-back contracts, the security package, and independent shipment verification > [card] [Transparency](/products/institutional-yield/commodities/transparency) > > Per-loan reporting, monthly attestation, and regulatory oversight For the deposit flow, the SPV structure, withdrawals, and the Loan Agreement, which are shared across all Institutional Yield vaults, see the [product overview](/products/institutional-yield) and [Legal Structure](/products/institutional-yield/structure). *** ## Strategy highlights * **Real-economy exposure.** Kamino Institutional Commodity Yield generates returns from financing income on short-duration Commodity Loans. These loans fund pre-arranged trades in essential industrial commodities, including metals, energy products, and selected non-perishable soft commodities. * **Short duration, recurring deployment.** Commodity Loans typically have a duration of one to three months. When a loan settles, returned principal is first applied to queued withdrawal requests. Remaining capital may then finance repeat deliveries under structured trading programs, subject to borrower performance and risk limits. * **Defined collateral coverage.** Each Commodity Loan is designed to remain covered at all times. Before funds are released into the trade, the loan is backed 1:1 by cash held in a segregated account. After release, it is more than 100% collateralized by physical commodities, measured against the contractual onward-sale price. The lending operation's transaction-specific security package may include controlled accounts, security over the financed commodities and related trade assets, and assignments or pledges of receivables. Collateral coverage is continuously monitored, with independent verification required before funds are released. * **Disciplined selection, tight mandate.** Each eligible transaction is structured back to back: before financing is provided, the commodity purchase and onward sale are contractually agreed at fixed prices. The commodity is purchased below the contracted onward-sale price, creating a defined commercial margin within the trade. This structure is designed to limit material unhedged commodity-price exposure. Speculative inventory positions, unsecured prepayments, and transactions with material unhedged commodity-price exposure fall outside the mandate. *** ## How it works ![Kamino Institutional Commodity Yield capital and return flow](https://mintcdn.com/kamino-3d73a151/xfYHZtgt_rk3q-Ya/images/institutional-yield/commodities/how-it-works.png?fit=max\&auto=format\&n=xfYHZtgt_rk3q-Ya\&q=85\&s=e930ba8930f33faf4b283bbb88373583) **1. Deposit USDC and receive vault tokens.** Vault depositors transfer USDC into the Kamino Institutional Commodity Yield vault and receive **kicUSDC** (Kamino Institutional Commodity USDC). These vault tokens represent the depositor's proportional share of the vault's net asset value and are issued and redeemed at the prevailing share price. **2. Enter into the Loan Agreement with the Institutional Yield SPV.** By depositing into the vault, the vault depositor extends an unsecured loan to the Institutional Yield SPV under the standard Institutional Yield [Loan Agreement](/products/institutional-yield/loan-agreement). The depositor's legal relationship is with the SPV. The depositor has no direct claim against the underlying borrowers and no direct security interest in the collateral securing the Commodity Loans. **3. Capital is allocated to the off-chain Commodity Yield structure.** The Institutional Yield SPV allocates capital to a regulated off-chain lending operation implemented through an approved fund structure supervised by CIMA. The off-chain structure originates and manages short-duration Commodity Loans to corporate borrowers and commodity traders. **4. A Commodity Loan finances a qualifying trade.** Before financing is provided, the commodity purchase and onward sale are contractually agreed at fixed prices. The Commodity Loan is backed 1:1 by cash in a segregated account before funds are released into the trade. Following independent verification and release, the loan is more than 100% collateralized by physical commodities, measured against the contractual onward-sale price. The lending operation also maintains a transaction-specific security package over the financed trade. See [Collateral & Transaction Structure](/products/institutional-yield/commodities/collateral). **5. The trade settles, withdrawals are processed, and remaining capital may be redeployed.** When the onward sale settles, the proceeds repay the Commodity Loan and its financing costs. Income generated by the loan portfolio, net of applicable fees and expenses, accrues to the vault and increases the redemption value of kicUSDC. Withdrawals within the vault's instant liquidity buffer settle immediately. Larger requests enter an on-chain first-in, first-out (FIFO) queue. As Commodity Loans settle, returned principal is first applied to queued withdrawal requests. Remaining capital may then finance new Commodity Loans. The buffer size and queue status are shown in the vault interface. *** ## Vault characteristics | Parameter | Terms | | - | - | | **Deposit currency** | USDC | | **Vault token** | kicUSDC (Kamino Institutional Commodity USDC), representing the vault depositor's proportional share of the vault's net asset value. Depositor rights are governed by the Institutional Yield Loan Agreement. | | **Borrower type** | Corporate commodity borrowers and traders that have completed the lending operation's KYC, AML, and credit-assessment procedures. | | **Collateral** | (i) Physical commodities (including copper, oil, coffee, granulated sulphur, diesel, petrol, and jet fuel), excluding short-term perishables; and/or (ii) cash financing held in segregated escrow accounts, including cash backing letters of credit | | **Transaction structure** | New counterparties typically start with a small trial transaction. Subject to performance and documentation, trades continue as rolling programs of repeat deliveries over a predefined period (for example, a 12-month schedule) | | **Collateral management** | Funds sit in segregated escrow accounts at tier-one banks and are released only after independent verification of the shipment and receipt of the agreed documentation. Collateral coverage is monitored against contractual parameters | | **Ownership transfer** | In the majority of transactions, the Commodity Yield Fund retains title to the commodity until the end buyer's payment is received under the onward sale contract. Settlement of purchase and sale legs is typically back to back | | **Collateralization** | Intended at all times to be covered at minimum 1:1 by segregated cash and/or overcollateralized by commodities purchased at a discount, measured against the contractual sale price rather than volatile spot prices | | **Insurance** | Financed goods are insured on an all-risk cargo basis for at least the full shipment value, with the financing entity named as loss payee or co-insured, enabling direct claims for covered loss or damage | | **Loan duration** | Commodity Loan tenors of approximately 1–3 months. The vault's withdrawal notice framework is calibrated to this transaction cycle for withdrawals beyond the instant liquidity buffer | | **Regulatory oversight** | The Commodity Yield Fund is an approved fund supervised by CIMA and subject to applicable regulatory reporting and oversight. This supervision does not extend to Kamino's on-chain protocol or vaults | | **Independent attestation** | Monthly portfolio attestation by an independent accounting firm, including verification of outstanding loan balances, collateral coverage, and key portfolio metrics | *** ## Lending framework Strict parameters govern how deposited funds are deployed: * Every loan is covered at minimum 1:1 by cash in a segregated bank account (held directly or backing a letter of credit), or overcollateralized by a commodity worth more than the loan * Funding is released only after the physical commodity shipment has been independently checked and approved and all documentation is in place * Liquidations would only occur if a buyer did not perform, which is unlikely, as buyers are purchasing the commodity at a discount to spot * The lending operation does not face sanctioned jurisdictions, countries, individuals, or trading entities thereof *** ## Disclaimers and eligibility Commodity Yield is intended for use only by persons who are legally permitted to interact with such products in their jurisdictions and who understand and accept the associated risks. Access may be restricted by geo-blocking or other measures. Nothing in this documentation constitutes investment, financial, legal, or tax advice, or a recommendation or solicitation to buy, sell, or hold any financial product or digital asset. Depositors should take independent advice and make their own assessment of whether participation in Commodity Yield is appropriate in light of their objectives, experience, financial situation, and risk tolerance. # Reporting & Transparency Source: https://docs.kamino.com/products/institutional-yield/commodities/transparency What data is available to depositors, how it's sourced, and the verification mechanisms that underpin Commodity Yield Because Commodity Loans exist off-chain, the transparency framework is designed to give depositors as much visibility as possible into the health and composition of the loan portfolio, through multiple independent channels. *** ## Per-loan data The Commodity Yield Fund provides per-loan data directly from its loan and risk management systems. This data is ingested by Kamino and displayed in the Commodity Yield vault interface. | Data point | Granularity | | - | - | | **Commodity Loan principal** | Per loan | | **Type of collateral (escrow / commodity)** | Per loan | | **Collateral coverage (contractual)** | Per loan | | **Approximate tenor / maturity date** | Per loan | | **Portfolio-weighted collateral coverage** | Aggregate across all loans | | **Number of active Commodity Loans** | Aggregate | | **Total nominal exposure** | Aggregate | *** ## Monthly independent attestation > [!NOTE] > > An **attestation** is a signed report from an independent accounting firm confirming that stated facts (here, loan balances and collateral coverage) match the underlying records. An independent accounting firm conducts monthly attestations of the Commodity Yield portfolio. Each signed attestation report verifies, among other things: * the aggregate and per-loan principal outstanding * collateral coverage and alignment with the documented framework * key portfolio health indicators, such as loan ageing, defaults, or restructurings These attestations provide an external verification layer for the off-chain lending activity. *** ## Regulatory oversight The Commodity Yield Fund is an approved fund under the supervision of the **Cayman Islands Monetary Authority (CIMA)** and is subject to applicable regulatory reporting and oversight. This regulatory status applies exclusively to the Commodity Yield Fund; it does not imply that Kamino, the Institutional Yield SPV, or the on-chain Commodity Yield vault are licensed, approved, or supervised by CIMA. # Concepts Source: https://docs.kamino.com/products/institutional-yield/concepts Foundational explanations of institutional lending, SPVs, and liquidity mechanics This page explains the foundational concepts behind Institutional Yield. If you're new to the product, start here before reading the detailed pages on [structure](/products/institutional-yield/structure), [risks](/products/institutional-yield/risks), and the individual vaults. *** ## What Institutional Yield is Kamino Institutional Yield is a fully collateralized institutional lending product. Capital deposited into a vault is deployed to a regulated lending operation that originates loans to institutional borrowers. Every loan is either overcollateralized or backed 1:1 by cash. The product is structured as a family of vaults. Each vault deploys to its own lending operation, with its own borrower base, collateral type, and regulator: * **[Commodity Yield](/products/institutional-yield/commodities)**: loans to corporates and commodity traders, backed by physical commodities or escrowed cash; the lending operation is supervised by the Cayman Islands Monetary Authority (CIMA) * **[Digital Assets Yield](/products/institutional-yield/digital-assets)**: loans to KYC-verified institutional borrowers, backed by high-quality digital assets (currently BTC) held at qualified custodians; the lending operation is supervised by the Financial Market Authority (FMA) in Liechtenstein Every vault's portfolio is independently attested each month by an accounting firm. For a detailed comparison with standard on-chain lending, see the [overview page](/products/institutional-yield#comparison-to-standard-defi-lending). *** ## Collateralized lending **Fully collateralized** means the collateral is worth at least as much as the loan. **Overcollateralized** means the value of the collateral exceeds the value of the loan; if collateral value declines, this buffer absorbs the loss before the loan becomes under-collateralized. How collateralization is achieved differs per vault. In the Digital Assets vault, every loan is overcollateralized, capped at 60% LTV against digital asset collateral. In the Commodity Yield vault, each Commodity Loan is intended to be covered 1:1 by escrowed cash, or overcollateralized by a commodity purchased below its contracted sale price. Contracts are arranged back to back at fixed prices, substantially reducing open commodity price risk. ### LTV (Loan-to-Value) LTV is the ratio of the loan amount to the collateral value: **LTV = Loan Amount / Collateral Value** | LTV | Meaning | | - | - | | 30% | Collateral worth more than 3x the loan; very conservative | | 50% | Collateral worth 2x the loan; conservative | | 60% | Collateral worth at least 40% more than the loan; the maximum allowed in the Digital Assets vault | | 75–86% | Typical range for on-chain DeFi lending; higher risk | In the Digital Assets vault, the 60% cap accounts for the fact that off-chain liquidation is slower than on-chain smart contract execution. The larger buffer compensates for the time needed to coordinate custodian liquidation. In the Commodity Yield vault, LTV is measured against the contractual sale price of the commodity rather than a fluctuating spot price, since both the purchase and the onward sale are contracted at fixed prices from the outset. *** ## Rates Rates are **set at origination** for each loan term. The rate is negotiated between the lending operation and the institutional borrower, then held constant for the full loan duration. At each rollover (when a loan term ends and a new one begins), the rate is renegotiated based on prevailing market conditions. **What this means for depositors:** * Yield is predictable within each loan term * Yield may change at each rollover, up or down depending on market conditions *** ## Liquidity mechanics Each vault has two withdrawal mechanisms: an instant buffer and a FIFO queue. Capital deployed into active loans is returned as those loans mature. Liquidity is managed to process withdrawals as efficiently as possible. ### 1. Instant buffer A portion of AUM is held as uninvested capital, available for immediate withdrawal. This buffer is sourced from: * Capital not yet deployed into active loans * Principal returned from recently matured loans * New deposits that have not yet been allocated The buffer is managed to maintain a target level. During periods of rapid deployment or high withdrawal demand, the buffer may temporarily be reduced. ### 2. Queued withdrawals (FIFO) Withdrawal requests beyond the instant buffer enter a **FIFO (first-in, first-out) queue**. Requests are resolved in order as underlying loans mature and principal returns to the vault. * The queue processes withdrawals strictly in the order they were submitted * Wait time depends on when the next batch of loans matures The FIFO queue is built into the vault's on-chain infrastructure and processes withdrawals automatically as liquidity becomes available. *** ## The trust model Institutional Yield operates under a different trust model than standard on-chain lending: | Dimension | On-chain DeFi | Institutional Yield | | - | - | - | | **Collateral verification** | Permissionless; anyone can verify on-chain | Verified by the supervising regulator and independent attestation | | **Rate enforcement** | Code (smart contract) | Contract (legal agreement) | | **Liquidation** | Automatic (smart contract) | Manual (executed by the lending operation) | | **Transparency** | Full on-chain visibility | Real-time data + monthly attestation | | **Recourse** | Smart contract holds collateral | Legal claim on SPV assets (limited recourse) | Understanding which trust model you are exposed to, and what can go wrong within that model, is important context before depositing. # Collateral & Custody Source: https://docs.kamino.com/products/institutional-yield/digital-assets/collateral How collateral is held, the LTV framework, custodian structure, and what happens when collateral coverage changes All loans originated by the Digital Assets Yield lending operation are overcollateralized with high-quality assets. Currently, all collateral is Bitcoin (BTC). Accepted collateral types are disclosed on the vault UI and may evolve over time; any changes will be reflected transparently in vault reporting. This page explains how collateral is held, the protections in place, and what happens when collateral coverage changes. *** ## Collateral assets Every loan in the Digital Assets Yield portfolio is backed by collateral posted by the institutional borrower. Currently, all collateral is BTC. The collateral is held at **qualified custodians**: licensed financial institutions operating under regulatory supervision. *** ## Tripartite agreement Collateral is held under a **tripartite agreement**: a three-party contract between: 1. **The borrower** (the institutional entity taking the loan) 2. **The lending operation** (the entity originating the loan) 3. **The custodian** (the qualified institution holding the collateral) The tripartite agreement governs the rights and obligations of each party with respect to the collateral. Under this structure: * The custodian holds the collateral independently of both the borrower and the lender * The lending operation has a contractual claim on the collateral in the event of borrower default * The custodian enforces the agreement independently; it is not controlled by either party *** ## No title transfer A critical feature of the collateral structure is that **no ownership transfer of collateral occurs to the lender**. The borrower's collateral remains their property at all times during the loan term. **What this means in practice:** * The collateral stays in the borrower's name at the qualified custodian * The lending operation has a contractual lien on the collateral: it can instruct the custodian to liquidate in the event of default, but cannot access, move, or use the collateral during the loan term * The custodian enforces the tripartite agreement independently of both parties **Why this matters:** When a lender takes possession of collateral, the borrower is exposed to the lender's operational risk, such as mismanagement, insolvency, or misuse of assets. Under the no-title-transfer model, the borrower's collateral is never in the lender's possession, eliminating the risk of lender mismanagement of collateral. *** ## Bankruptcy remoteness Assets held at qualified custodians are **bankruptcy remote**. If a custodian fails (becomes insolvent, goes bankrupt, or ceases operations), the collateral held at that custodian **cannot be seized by the custodian's creditors**. In practice: * Client assets are segregated from the custodian's own assets at all times * In the event of custodian insolvency, client assets are returned to clients or transferred to an alternative custodian; they do not enter the insolvency estate * Creditors of the custodian have no legal claim on client-custodied assets * This protection is enforced by the laws of the jurisdiction where the custodian is regulated *** ## Rehypothecation prohibition **Rehypothecation, the practice of a custodian or lender re-using client collateral for lending, pledging, or financing, is explicitly prohibited by contract.** Under the tripartite custodian agreement: * The custodian cannot lend, pledge, or trade the collateral * The collateral is held in **segregated accounts**, fully separated from the custodian's own assets and those of other clients * The lending operation cannot re-use the collateral for any purpose other than securing the specific loan it backs *** ## LTV framework ### Maximum LTV: 60% All loans are originated at a maximum Loan-to-Value ratio of 60%. In practice, loans are typically originated at lower LTV. The current LTV for each loan and the portfolio-weighted average LTV are reported in real time via the vault UI. ### What 60% max LTV means for collateral price declines | Collateral price decline from origination | LTV at max origination (60%) | Status | | - | - | - | | 0% | 60% | At maximum | | 10% | 67% | Above max; margin call territory | | 20% | 75% | Significant breach | | 40% | 100% | Full collateral coverage consumed | A 40% decline in collateral price from origination would bring a loan originated at exactly 60% LTV to full collateral coverage (100% LTV). Loans originated at lower LTV have correspondingly larger buffers. *** ## Collateral monitoring Collateral positions are monitored **continuously and in real time** through an industry-standard loan management system. Every loan, every collateral position, and every change is tracked; if a borrower's collateral value changes (due to market price movement, additional collateral posted, or partial withdrawal), the change is visible immediately. Per-loan collateral data (loan amount, collateral value, LTV) is provided to Kamino for display in the vault UI. This data comes directly from the lending operation's systems and is continuously updated. *** ## Margin calls and liquidation * Loans are originated at a maximum 60% LTV, with typical LTV lower * Collateral positions are monitored continuously via an industry-standard loan management system * If collateral price declines cause LTV to breach the margin call threshold, the lending operation can require the borrower to post additional collateral * If the borrower fails to post additional collateral, the lending operation can instruct the custodian to liquidate collateral under the terms of the tripartite agreement * Liquidation also takes place if the borrower fails to repay the loan at maturity # Digital Assets Yield Source: https://docs.kamino.com/products/institutional-yield/digital-assets/index Stablecoin yield from overcollateralized institutional lending against digital assets held at qualified custodians Institutional Digital Assets Yield is the Institutional Yield vault that lends against digital asset collateral. Loans are extended to institutional borrowers that meet strict [lending criteria](#lending-criteria), with high-quality, liquid collateral (currently BTC) posted at [qualified custodians](/products/institutional-yield/digital-assets/collateral). In this structure, there is [no collateral ownership transfer](/products/institutional-yield/digital-assets/collateral#no-title-transfer) to the lender, and rehypothecation of collateral is contractually prohibited, with collateral sitting in segregated accounts at the custodian. Every loan is capped at 60% LTV (typically lower). The lending operation reports to the Financial Market Authority (FMA) in Liechtenstein and is [independently attested monthly](/products/institutional-yield/digital-assets/transparency#monthly-attestation). Depositors see [real-time, per-loan data](/products/institutional-yield/digital-assets/transparency#real-time-loan-data) sourced from the same systems the regulator monitors. > [card] [Collateral & Custody](/products/institutional-yield/digital-assets/collateral) > > Collateral framework, qualified custodians, LTV structure, and margin calls > [card] [Transparency](/products/institutional-yield/digital-assets/transparency) > > Real-time reporting, monthly attestation, and what data depositors can access For the deposit flow, the SPV structure, withdrawals, and the Loan Agreement, which are shared across all Institutional Yield vaults, see the [product overview](/products/institutional-yield) and [Legal Structure](/products/institutional-yield/structure). *** ## How the vault deploys capital Capital deposited into the vault flows through the Institutional Yield SPV to the lending operation, which originates overcollateralized loans to KYC-verified institutional borrowers. Each loan is backed by collateral held at qualified custodians under tripartite agreements. Collateral ownership remains with the borrower; the custodian holds the collateral independently, and rehypothecation is contractually prohibited. Interest earned on the loan portfolio flows back through the structure to the vault, and share value appreciates proportionally. Rates are set at origination for each loan term. *** ## Vault characteristics | Parameter | Terms | | - | - | | **Target yield** | 6–8% APY | | **Deposit currency** | At launch, USDC. The product is designed to support a variety of stablecoins over time. | | **Collateral** | High-quality digital assets (currently BTC) at qualified custodians | | **Maximum LTV** | 60% (typically lower) | | **Instant liquidity buffer** | A portion of AUM is held for immediate withdrawals | | **Redemption model** | Hybrid: instant buffer + queued withdrawals | | **Monthly attestation** | Independent accounting firm | *** ## Lending criteria The vault deploys only to lending operations that meet strict criteria. The following must be met for loans to flow from the vault to borrowers: | Criterion | Requirement | | - | - | | **Underlying collateral** | High-quality, liquid assets (currently BTC). Accepted collateral types are disclosed on the vault UI and may evolve over time; any changes will be reflected transparently in vault reporting. | | **Maximum LTV** | 60% (typically lower; real-time LTV visible in vault UI) | | **Collateral rehypothecation** | Prohibited; ownership remains with the borrower | | **Loan duration** | Rolling terms (e.g. 60-day) | | **Interest calculation** | 365-day year basis | | **Regulatory oversight** | Lending operation approved and supervised by the Financial Market Authority in Liechtenstein | # Reporting & Transparency Source: https://docs.kamino.com/products/institutional-yield/digital-assets/transparency What data is available to depositors, how it's sourced, and the verification mechanisms that underpin Digital Assets Yield Because Digital Assets Yield loans exist off-chain, the transparency framework is designed to give depositors as much visibility as possible into the health and composition of the loan portfolio, through multiple independent channels. *** ## Real-time loan data The lending operation provides per-loan data directly from its systems. This data is sourced from an industry-standard loan management and collateral tracking platform used by major institutional counterparties. ### What depositors can see | Data point | Granularity | Source | | - | - | - | | **Collateral asset** | Per loan | Lending operation | | **Loan amounts** | Per loan | Lending operation | | **Collateral value** | Per loan (collateral value at current market price) | Lending operation | | **LTV per loan** | Per loan | Calculated from loan amount and collateral value | | **Portfolio-weighted average LTV** | Aggregate | Calculated from per-loan data | | **Number of active loans** | Aggregate | Lending operation | | **Total collateral value** | Aggregate | Lending operation | This data is displayed in the **Vault Analytics** section of the Digital Assets Yield vault UI on Kamino. *** ## Monthly attestation An independent accounting firm conducts monthly attestations of the Digital Assets Yield portfolio. The attestation covers: * **Loan balances outstanding**: total and per-loan amounts verified against the lending operation's records * **Collateral coverage ratios**: independent verification that collateral values match reported positions * **Portfolio health metrics**: assessment of overall portfolio status The attestation is a formal, signed document produced by a professional accounting firm. It is the primary independent verification mechanism for off-chain lending activity. *** ## Additional oversight The lending operation also reports to the Financial Market Authority (FMA) in Liechtenstein, providing additional regulatory oversight beyond the independent attestation. *** ## Comparison to other institutional lending products | Mechanism | Digital Assets Yield | Typical off-chain lending | | - | - | - | | **Per-loan data** | Available: loan amounts, collateral values, LTV per loan | Rarely disclosed | | **Real-time data** | Continuous feed from lending operation systems | Usually monthly or quarterly reports only | | **Independent attestation** | Monthly (independent accounting firm) | Quarterly or annual | | **Regulatory oversight** | Top-tier jurisdiction (FMA) | Typically unregulated | # FAQ Source: https://docs.kamino.com/products/institutional-yield/faq Direct answers to the most common questions about Institutional Yield ## What vaults are available? Institutional Yield is a family of vaults, each deploying to its own regulated lending operation: * **[Commodity Yield](/products/institutional-yield/commodities)**: loans to corporates and commodity traders, backed by physical commodities or escrowed cash. The lending operation deploys through an approved fund supervised by the Cayman Islands Monetary Authority (CIMA). * **[Digital Assets Yield](/products/institutional-yield/digital-assets)**: loans to KYC-verified institutional borrowers, backed by high-quality digital assets (currently BTC) held at qualified custodians. The lending operation is approved and supervised by the Financial Market Authority (FMA) in Liechtenstein. *** ## Is my deposit secured or unsecured? **Your loan to the SPV is unsecured.** The collateral exists at the lending operation level, between the lending operation and its borrowers. Your legal claim is on the SPV's assets, which are primarily composed of those fully collateralized lending positions. The underlying loans are fully collateralized, but your deposit into the SPV does not have direct collateral attached to it. Your protection comes from the fact that the SPV's assets are backed by fully collateralized loans, combined with the reporting and attestation framework that provides visibility into the lending operation. See [Loan Agreement](/products/institutional-yield/loan-agreement). *** ## What happens if a borrower defaults? It depends on the vault, because the collateral takes a different form in each: **Commodity Yield**: a default would mean a buyer failing to perform on a contracted purchase. The lending operation retains title to the commodity until the buyer's funds are received. If the buyer fails to pay, it therefore still holds the commodity, purchased at a discount to the contracted sale price, and can sell it. Where the transaction has not yet shipped, the financing sits in a segregated escrow account and no funds have been released. **Digital Assets Yield**: the lending operation instructs the qualified custodian to liquidate the borrower's collateral under the tripartite agreement, and the proceeds repay the loan. Because loans are originated at a maximum 60% LTV (and typically lower), the collateral should more than cover the loan in most scenarios. In either vault, depositors face a loss only if the underlying loan cannot be repaid and realizing the collateral is insufficient to cover the balance. *** ## What happens if there is a loss in the portfolio? If a lending operation experiences a loss that cannot be recovered through collateral realization: * The loss reduces the SPV's available assets * This reduces the value backing depositor claims * The loss would be reflected in the vault share price; share value would decrease proportionally *** ## How do I know the collateral actually exists? Multiple independent verification layers confirm collateral in every vault: 1. **Real-time data** from the lending operation's loan management and risk systems, piped to the vault UI 2. **Monthly attestation** by an independent accounting firm, providing formal verification of loan balances and collateral coverage 3. **Regulatory reporting** to the vault's supervising regulator (CIMA for Commodity Yield, the FMA for Digital Assets Yield) In the Commodity Yield vault, physical shipments are additionally checked and approved by an independent third party before any funds are released. See [Commodity Yield transparency](/products/institutional-yield/commodities/transparency) and [Digital Assets Yield transparency](/products/institutional-yield/digital-assets/transparency). *** ## When can I withdraw my deposit? * **Immediately**: if the withdrawal is within the liquidity buffer (capital not deployed into active loans) * **After loan maturity**: if the buffer is exhausted, your withdrawal enters a FIFO queue and is processed as underlying loans mature and principal returns There is no early redemption for capital deployed into active loans. Loan terms are rolling, so the maximum wait in the queue depends on when the next batch of loans matures. See [Liquidity mechanics](/products/institutional-yield/concepts#liquidity-mechanics). *** ## Who attests to the portfolios? An independent accounting firm conducts monthly attestations of each vault's portfolio, covering loan balances, collateral coverage, and portfolio health. Each lending operation also reports to its supervising regulator: CIMA for Commodity Yield, and the FMA in Liechtenstein for Digital Assets Yield. *** ## What is the SPV and why does it exist? The SPV is the legal entity that receives depositor funds and deploys them to the lending operations. It exists to: * **Ring-fence risk**: SPV liabilities are contained within the SPV and do not reach Kamino's on-chain protocol * **Provide a legal structure** for off-chain institutional lending See [Legal Structure: The SPV](/products/institutional-yield/structure#the-spv). *** ## What yield can I expect? Target, historical, and current projected returns for each vault are displayed on the Kamino UI. The actual yield depends on: * The rate negotiated with borrowers for each loan term * The proportion of vault capital deployed vs. held in the liquidity buffer (undeployed capital earns lower yield) * Portfolio performance *** ## How is Institutional Yield different from other on-chain institutional lending products? | Feature | Kamino Institutional Yield | Typical comparison | | - | - | - | | **Collateral** | Overcollateralized or backed 1:1 by cash in every vault: physical commodities or escrowed cash (Commodity Yield), digital assets at qualified custodians under tripartite agreements (Digital Assets Yield) | Varies; some products accept diverse or incentivized collateral | | **Regulatory oversight** | Every lending operation approved and supervised by a financial regulator (CIMA, FMA) | Typically unregulated | | **Independent attestation** | Monthly (independent accounting firm) | Often quarterly or annual, if any | | **Real-time data** | Per-loan data from lending operation systems | Rarely available | *** ## Can I see individual loans? Yes. Each lending operation provides per-loan data including loan amount, collateral value, and LTV. This data is displayed in the vault UI. Borrower identities are protected by confidentiality requirements. *** ## Who are the borrowers? In the Commodity Yield vault, borrowers are corporates and commodity traders. In the Digital Assets Yield vault, borrowers are KYC-verified institutional entities. Due to confidentiality requirements, individual borrower identities are not disclosed. Loan-level data (amounts, collateral values, LTV) is available without borrower identification. *** ## Does Institutional Yield introduce new smart contract risk? No. Institutional Yield vaults use the same battle-tested Kamino smart contracts that power other Kamino products. There is no new on-chain technical risk; the vault infrastructure is identical to the existing, audited Kamino vault framework. *** ## What stablecoins are accepted? At launch, **USDC**. The product is designed to support a variety of stablecoins over time. # Institutional Yield Source: https://docs.kamino.com/products/institutional-yield/index Generate returns via regulated lending operations to institutional borrowers Kamino Institutional Yield is a family of vaults that generate stablecoin yield by deploying capital to institutional, fully collateralized, and regulated lending operations. Every vault shares the same underlying structure: deposits flow through a special-purpose vehicle (SPV) into a regulated lending operation, which originates fully collateralized loans to institutional borrowers. Each vault deploys to its own lending operation, with its own borrower base, collateral type, and regulatory oversight. Every Institutional Yield vault meets the same baseline standards: * **Regulated lending counterparties**: capital is deployed only to third-party lending operations that are approved and supervised by a financial regulator * **Fully collateralized loans**: every loan is either overcollateralized or backed 1:1 by cash * **Monthly independent attestation**: an independent accounting firm attests to each vault's portfolio every month * **Per-loan transparency**: loan-level data is reported in the vault UI, sourced directly from the lending operation's systems * **Audited on-chain infrastructure**: every vault uses the same battle-tested Kamino smart contracts, with an instant liquidity buffer and an on-chain FIFO withdrawal queue > [!NOTE] > > New to Institutional Yield? The [Concepts](/products/institutional-yield/concepts) page explains the core structure: what an SPV is, how collateralized lending works, and how withdrawals and liquidity are structured. *** ## The vaults > [card] [Commodity Yield](/products/institutional-yield/commodities) > > Loans to corporates and commodity traders, backed by physical commodities or escrowed cash. The lending operation is supervised by the Cayman Islands Monetary Authority (CIMA). > [card] [Digital Assets Yield](/products/institutional-yield/digital-assets) > > Loans to institutional borrowers, backed by high-quality digital assets (currently BTC) held at qualified custodians. The lending operation is supervised by the Financial Market Authority (FMA) in Liechtenstein. | | Commodity Yield | Digital Assets Yield | | - | - | - | | **Borrowers** | Corporates and commodity traders | KYC-verified institutional entities | | **Collateral** | Physical commodities or escrowed cash | High-quality digital assets (currently BTC) at qualified custodians | | **Collateralization** | Varies per transaction: 1:1 escrowed cash, or overcollateralized by a commodity worth more than the loan | Maximum 60% LTV (typically lower) | | **Loan duration** | 1–3 months (notice period 1–3 months) | Rolling terms (e.g. 60-day) | | **Regulatory oversight** | Approved and supervised by CIMA | Approved and supervised by the FMA in Liechtenstein | | **Independent attestation** | Monthly, by an independent accounting firm | Monthly, by an independent accounting firm | *** ## How it works **1. Deposit stablecoins into an Institutional Yield vault on Kamino.** You receive vault share tokens at the current share price. As part of the deposit process, you agree to the [Loan Agreement](/products/institutional-yield/loan-agreement) with the Institutional Yield SPV. This agreement governs your legal relationship as a depositor into the product. **2. Capital flows into the Kamino Institutional Yield structure.** Stablecoins flow through the SPV to the vault's lending operation. The lending operation originates and manages fully collateralized loans to institutional borrowers. **3. The lending operation originates fully collateralized loans.** Every loan is either overcollateralized or backed 1:1 by cash. The form the collateral takes is vault-specific; see [Commodity Yield collateral](/products/institutional-yield/commodities/collateral) and [Digital Assets Yield collateral](/products/institutional-yield/digital-assets/collateral). **4. Yield flows back to vault depositors.** Interest earned on the loan portfolio flows back through the structure to the vault. Share value appreciates proportionally as the vault accrues interest. Rates are set at origination for each loan term. Loan terms can vary between borrowers. The current liquidity buffer is shown in the vault UI. ### Withdrawals Each vault maintains an instant liquidity buffer. Withdrawals within the buffer settle immediately. Withdrawals beyond the buffer enter an on-chain FIFO (first-in, first-out) queue and are processed as underlying loans mature and principal is returned to the vault. See [Liquidity mechanics](/products/institutional-yield/concepts#liquidity-mechanics) for full details. *** ## Product documentation > [card] [Concepts](/products/institutional-yield/concepts) > > Collateralized lending, LTV, rates, liquidity mechanics, and the trust model > [card] [Legal Structure](/products/institutional-yield/structure) > > The SPV and lending operations behind every vault > [card] [Risks](/products/institutional-yield/risks) > > Risk disclosure: structural and vault-specific risks > [card] [Loan Agreement](/products/institutional-yield/loan-agreement) > > The agreement depositors sign when they deposit > [card] [FAQ](/products/institutional-yield/faq) > > Direct answers to the most common questions *** ## Comparison to standard DeFi lending | Attribute | Standard DeFi | Institutional Yield | | - | - | - | | **Yield source** | On-chain borrow demand | Institutional, fully collateralized lending | | **Borrower profile** | Pseudonymous | Identified institutional entities | | **Collateral location** | Smart contracts (on-chain) | Off-chain: qualified custodians, escrow accounts, or physical commodities, depending on the vault | | **Rate type** | Floating (utilization-based) | Set at origination | | **Regulatory oversight** | Protocol-level governance | Lending operations approved and supervised by a financial regulator | | **Liquidity** | Instant (utilization-dependent) | Hybrid: instant buffer + queued | | **Transparency** | Open-source smart contracts, on-chain verification | Real-time reporting from lending operation systems + monthly independent attestation | *** ## Contact **Institutional Yield Enquiries:** [institutions@kamino.com](mailto:institutions@kamino.com) *** ## Disclaimer Kamino Institutional Yield vaults are made available subject to Kamino's Terms and Conditions and geo-blocking policy. By accessing this page or interacting with the vaults, you confirm that you are not located in a restricted jurisdiction and that your participation complies with all laws and regulations applicable to you. Nothing on this page or within the associated documentation constitutes financial, investment, legal, or tax advice, nor should it be construed as a solicitation or offer to buy or sell any financial instrument or to participate in any particular investment strategy. Regulatory approval and supervision described above apply only to the lending operation for each vault — CIMA for Commodity Yield, the FMA for Digital Assets Yield. This supervision covers the lending operation's licensing, its ongoing reporting obligations, and its origination and management of the underlying loans. The SPV, the Kamino Institutional Yield vaults, and Kamino are not licensed, registered, or supervised by CIMA, the FMA, or any other financial regulator. Depositors do not receive deposit insurance, a regulatory guarantee, or any regulatory recourse as a result of a lending operation's regulatory status. A depositor's relationship to the structure is governed solely by the Loan Agreement, and their position is that of an unsecured creditor of the SPV. # Loan Agreement Source: https://docs.kamino.com/products/institutional-yield/loan-agreement The agreement depositors sign when they deposit into Institutional Yield When you deposit into an Institutional Yield vault, you agree to a **Loan Agreement** with the SPV. This agreement governs your legal relationship as a depositor into the product. The full Loan Agreement is available on request. Please contact [institutions@kamino.com](mailto:institutions@kamino.com) to receive a copy. # Risks Source: https://docs.kamino.com/products/institutional-yield/risks Risk disclosure for Institutional Yield This section sets out the risks associated with depositing into an Institutional Yield vault. The structural risks below apply to every vault in the product family; vault-specific risks follow. *** ## Unsecured loan to the SPV The depositor's legal relationship is with the SPV. The [Loan Agreement](/products/institutional-yield/loan-agreement) characterizes this loan as **unsecured**. Depositors have no direct security interest in the collateral backing the underlying loans (such as commodities, escrow accounts, receivables, or digital assets); that collateral secures the loans between the lending operation and its borrowers, one level below the depositor. The depositor's economic exposure is to fully collateralized lending: the depositor's claim is on the SPV's available assets, which are primarily composed of those fully collateralized lending positions. Losses at the level of a lending operation or its collateral may propagate to the SPV and be reflected in the net asset value of the relevant vault and its vault tokens. *** ## Lending operation risk Each lending operation is a regulated entity, but regulation does not eliminate risk. Possible failure modes include: * **Operational failure**: errors in loan origination, collateral monitoring, or the execution of margin calls and settlements * **Failure to liquidate**: if a borrower defaults and the lending operation does not act promptly, collateral value may decline further before liquidation occurs * **Regulatory action**: the supervising regulator could suspend or revoke the lending operation's approval, potentially freezing operations *** ## Liquidity risk Capital deployed into active loans cannot be retrieved prior to loan maturity. There is no early redemption mechanism. While each vault maintains an instant liquidity buffer, withdrawals exceeding that buffer enter a FIFO queue and are resolved only as underlying loans mature and principal is returned to the vault. *** ## Not a deposit or insured product Participation in an Institutional Yield vault does not constitute a bank deposit and is not covered by any government-backed deposit protection or insurance scheme. No rate of return or capital preservation is guaranteed. The value of your deposit may go down as well as up, and past performance, if any, is not indicative of future results. *** ## Vault-specific risks ### Commodity Yield In addition to the structural risks above, Commodity Yield involves risks specific to commodity trade finance: * **Commodity price and basis risk**: although transactions are structured back to back with fixed prices, severe market dislocations, basis risk, or timing mismatches may impair recoveries. * **Counterparty risk**: defaults or non-performance by traders, buyers, sellers, or logistics providers can lead to delays, enforcement actions, and potential losses. * **Legal and enforcement risk**: enforcing security interests and contracts across multiple jurisdictions, including emerging markets, can be complex, time-consuming, and uncertain. * **Settlement, shipping, and logistics risk**: delays, disruptions, sanctions events, or failures in transport and logistics chains can adversely affect trade execution and recoveries. Any of these risks, if crystallized, may result in partial or total loss of deposited capital. See [Commodity Yield collateral & transaction structure](/products/institutional-yield/commodities/collateral) for the collateral and security framework around each transaction. ### Digital Assets Yield **Collateral price risk**: an extreme and rapid decline in collateral price, combined with delayed liquidation, could leave a loan under-covered. The 60% maximum LTV provides the buffer against this scenario. **Custodian risk**: collateral protection relies on the integrity and proper functioning of qualified custodians. While custodied assets are bankruptcy remote, the process of recovering assets from an insolvent custodian could take time. See [Digital Assets Yield collateral & custody](/products/institutional-yield/digital-assets/collateral) for the full collateral framework. # Legal Structure Source: https://docs.kamino.com/products/institutional-yield/structure The SPV and lending operations behind Institutional Yield Institutional Yield operates through a multi-entity legal structure that separates on-chain deposits from off-chain institutional lending. The structure is the same for every vault in the product family. What changes per vault is the lending operation the capital is deployed to, its regulator, and the collateral backing the underlying loans. *** ## How the entities connect ``` Depositor (on-chain) │ │ Signs Loan Agreement │ Deposits stablecoins into a Kamino Institutional Yield vault │ Receives vault share tokens ▼ Kamino Institutional Yield Vault │ │ Capital flows to the lending operation via the SPV ▼ Regulated Lending Operation (vault-specific) │ │ Originates fully collateralized loans ▼ Institutional Borrowers │ │ Loans backed by vault-specific collateral │ (physical commodities, escrowed cash, or digital assets at qualified custodians) ``` *** ## The SPV The SPV is the legal entity that sits between depositors and the lending operations. It is set up specifically for this product: a standalone, single-purpose structure with no mixing of funds from any other activity. Depositor funds flow through the SPV into the lending operation, and interest and principal repayments flow back through the SPV to the Kamino vault. *** ## The lending operations Each vault deploys to a dedicated lending operation: the entity that originates and manages loans to institutional borrowers. Every lending operation in the product family is approved and supervised by a financial regulator: | Vault | Lending operation | Regulator | | - | - | - | | [Commodity Yield](/products/institutional-yield/commodities) | An approved fund originating loans to commodity borrowers and traders | Cayman Islands Monetary Authority (CIMA) | | [Digital Assets Yield](/products/institutional-yield/digital-assets) | A licensed lending operation originating loans against digital asset collateral | Financial Market Authority (FMA), Liechtenstein | **Key characteristics common to every lending operation:** * Approved by its regulator and subject to ongoing supervision, including reporting of loan positions and collateral status * Monthly attestation by an independent accounting firm * Per-loan data piped from its loan management and risk systems to the Kamino vault UI **What the lending operation does with depositor capital:** 1. Receives capital from the SPV 2. Originates fully collateralized loans to institutional borrowers 3. Ensures every loan is backed by collateral under the vault's collateral framework; see [Commodity Yield collateral](/products/institutional-yield/commodities/collateral) and [Digital Assets Yield collateral](/products/institutional-yield/digital-assets/collateral) 4. Manages the loan portfolio: monitoring collateral coverage, processing interest payments, handling maturities and rollovers 5. Returns principal and interest to the SPV > [!NOTE] > > The depositor's economic exposure spans the entire structure, from the SPV through the lending operation to the underlying collateralized loans. The quality of the depositor's position depends on the operational integrity of every entity in the structure. # Benchmark Rate Source: https://docs.kamino.com/products/lending-vaults/benchmark-rate An objective DeFi baseline for measuring stablecoin vault performance The Benchmark Rate is a deposit-weighted average of USD stablecoin lending yields across the largest DeFi protocols. It provides an objective reference point for evaluating whether a stablecoin vault is generating genuine outperformance or simply tracking a market-wide rate environment. In traditional finance, government bond yields serve as a baseline for comparing dollar-denominated products. DeFi has no equivalent — there is no single risk-free rate. The Benchmark Rate fills this gap by aggregating real supply rates from the most established stablecoin lending venues. ## What it tracks The benchmark pulls real-time supply rates from three protocols covering approximately \$14B in supplied stablecoin liquidity: | Protocol | Tracked supply | Assets | | - | - | - | | Aave v3 | \~\$11.5B | USDC, USDT, DAI, USDS | | Maker Savings Rates (sDAI / sUSDS) | \~\$2.2B | DAI, USDS | | Morpho | \~\$600M | USDC, USDT, DAI, USDS | **Protocol inclusion criteria:** * Over \$1B in total stablecoin deposits * Live for over 1 year * Over \$100M in stablecoin deposits specifically **Stablecoin inclusion criteria:** Only those exceeding \$2B in circulating supply — currently USDC, USDT, DAI, and USDS. ## How it's calculated The rate is a deposit-weighted average — larger pools carry more weight than smaller pools. This means the benchmark reflects where the majority of stablecoin capital actually sits, rather than giving equal weight to shallow or illiquid venues. Kamino's own Earn Vaults are intentionally excluded from the benchmark calculation. Including them would introduce circularity — comparing a vault's performance against a benchmark that contains that same vault's yields. The exclusion preserves the benchmark's value as an independent reference point. ## How to use it The Benchmark Rate is displayed on every stablecoin vault in Kamino Earn. When a vault's yield exceeds the benchmark, the spread represents genuine outperformance relative to what passive stablecoin lending earns across the largest DeFi venues. When the yield is below the benchmark, the vault is underperforming that baseline. The benchmark is one input into vault evaluation — not the only one. Yield composition (base interest vs. emissions), reserve concentration, and collateral quality all matter when [comparing yields across vaults](/products/lending-vaults/concepts#comparing-yields-across-vaults). The benchmark adds a single quantitative reference to that analysis. > [!NOTE] > > The Benchmark Rate methodology was developed in partnership with [Allez Labs](https://allez.xyz). Full methodology details and historical data are available on their platform. # Concepts Source: https://docs.kamino.com/products/lending-vaults/concepts Reserves, utilization, auto-compounding, curators, and bad debt — how Lending Vaults work under the hood ## What is a lending reserve A reserve is a single-asset pool within a lending market. Capital deposited into a reserve is lent to borrowers; the interest borrowers pay is the source of all lender yield. There is no separate yield source — if borrowers aren't paying interest, lenders aren't earning. Each asset has its own reserve because different assets carry different risk profiles and warrant different rates. USDC in the SOL/BTC Market is a different reserve from USDC in the JLP Market — different borrowers, different collateral, different rates. Reserves exist for both lending models: * **Variable-rate reserves** — one reserve per asset per market; rate fluctuates with utilization * **Fixed-rate reserves** — one reserve per rate/duration pair (USDC at 5.0%/3-month is a separate reserve from USDC at 5.5%/6-month) The reserve is the fundamental unit of both models. *** ## Utilization Utilization is the fraction of a reserve's deposits currently borrowed: ``` Utilization = Borrowed / Total Deposited ``` This is the signal that drives variable borrow rates — and the key determinant of lender yield. **Lender yield formula:** ``` Supply APY ≈ Borrow Rate × Utilization × (1 − Protocol Spread) ``` **Worked example:** \$1M pool, \$750k borrowed (75% utilization), 10% borrow rate, 15% protocol spread: ``` Interest generated: $750,000 × 10% = $75,000/year After protocol spread: $75,000 × 0.85 = $63,750 Supply APY (distributed over $1M): 63,750 / 1,000,000 = 6.375% ``` The idle \$250k earns nothing but sits in the denominator — this is why supply APY is always materially lower than the borrow rate. **Why high utilization benefits lenders:** More of your capital is working. At 75% utilization you earn \~6.4%; at 50% utilization on the same pool and rates, you'd earn \~4.25%. **Why extreme utilization is a problem:** At 95%+, very little capital is available for withdrawal. Kamino's rate curves are designed to prevent this — borrow rates escalate sharply above the kink point, pushing borrowers to repay and attracting new deposits. *** ## What a vault does A Lending Vault is a capital allocator, not a lending pool itself. It holds your deposit and deploys that capital across multiple reserves according to the curator's strategy. You interact only with the vault; the vault handles everything underneath: * Which reserves to allocate to and in what proportion * When to rebalance (e.g., if a reserve's utilization drops sharply) * When to pull back from a reserve showing stress One deposit. One share balance. One blended yield. Allocation decisions happen entirely at the vault layer. *** ## Share price and auto-compounding When you deposit, you receive vault shares. Your position is tracked by share count, not a fixed token balance. ``` Share Price = Total Vault Assets / Total Shares Outstanding ``` As interest accrues in the underlying reserves, total vault assets grow while shares outstanding stay fixed — so share price rises. Your share count never changes between deposit and withdrawal; what changes is what each share is worth. This is auto-compounding. You don't receive periodic interest payments and manually reinvest them — your shares silently appreciate. Reinvestment is continuous and requires no action. **Example:** | Event | Share price | Your shares | Value | | - | - | - | - | | Deposit 1,000 USDC | \$1.00 | 1,000 | \$1,000 | | 6 months at 9% APY | \$1.044 | 1,000 | \$1,044 | | 12 months at 9% APY | \$1.090 | 1,000 | \$1,090 | Withdrawing at any point redeems your shares at the current share price. *** ## Blended APY Vault yield is the weighted average of the APYs earned across all active reserve allocations: ``` Vault APY = Σ (Reserve APY_i × Allocation_i) ``` **Example — a USDC vault with three allocations:** | Reserve | Allocation | APY | | - | - | - | | USDC SOL/BTC Market | 60% | 8% | | USDC JLP Market | 30% | 12% | | Fixed Rate (3-month) | 10% | 6% | ``` Blended APY = (60% × 8%) + (30% × 12%) + (10% × 6%) = 9.0% ``` **What makes the blended APY move:** * Utilization shifts in any underlying reserve * Curator rebalancing capital between reserves * Emission programs starting or ending * Large new deposits or withdrawals **What the displayed APY includes:** Base interest from borrowers + KMNO emissions when active. **What it typically does NOT include:** Farm rewards (displayed separately), external partner incentives, points programs. A 9% APY with 3% from KMNO emissions is not the same as 9% paid entirely in USDC interest — the first embeds token price risk in the headline figure. **APY vs. APR:** APY accounts for compounding; APR does not. Lending Vaults auto-compound, so the displayed figure is APY. At 2% per month, APR = 24% and APY = 26.8%. Always confirm which metric a platform displays before comparing. *** ## What curators do The curator is the vault's active manager. They set and update allocation targets — which reserves to use, what proportion for each, when to rebalance. This requires ongoing monitoring and judgment, not a one-time configuration. Active curators: * Monitor utilization rates across reserves * Move capital toward higher-yielding reserves as conditions change * Pull back from reserves approaching extreme utilization or showing stress * Adjust fixed-rate allocations based on available rate/duration opportunities **[Insurance Pool](/products/lending-vaults/insurance-pool):** Curators can lock their own capital into the vault via a dedicated Insurance Pool with a cooldown period (typically 30 days). This capital gives the curator direct financial exposure to their own allocation decisions — if the vault takes losses, the curator's locked position is at risk alongside depositors, and the cooldown prevents them from exiting before depositors can react. A curator with meaningful capital locked in the Insurance Pool for 30+ days has direct financial skin in the game. This is the strongest alignment signal available. *** ## Bad debt Bad debt occurs when a borrower's position is liquidated but the collateral proceeds are insufficient to cover the full debt. The shortfall is absorbed proportionally by lenders in that reserve — their share price is reduced to reflect the loss. **Example:** A reserve has \$10M in deposits. A liquidation produces \$500k in bad debt. A lender with 5% of the reserve loses \$25k of effective value via share price reduction. Kamino's track record: **\$0 bad debt across all protocol markets since launch.** This reflects conservative parameter-setting, the dynamic liquidation penalty design (which incentivizes early liquidation before positions go deeply underwater), and active monitoring. > [!NOTE] > > Vaults where the curator has locked capital in an [Insurance Pool](/products/lending-vaults/insurance-pool) provide a buffer: the curator has direct financial exposure to the vault's performance and cannot exit during the cooldown window. *** ## Variable vs. fixed reserves A vault can allocate to both variable and fixed-rate reserves simultaneously. | | Variable reserves | Fixed-rate reserves | | - | - | - | | Rate | Fluctuates with utilization | Locked for the term duration | | When yield is earned | Continuous | Variable while waiting; fixed once matched to a borrower | | Withdrawal | Anytime (subject to utilization) | Capital may be committed for the term | | Best for | Flexible allocation, capturing rate spikes | Predictable yield on a portion of the portfolio | The blended vault APY reflects both types. A vault with partial fixed allocation has more predictable yield on that portion. This mix is one tool curators use to manage yield volatility. *** ## Comparing yields across vaults Headline APY numbers are not directly comparable without decomposing what they contain: 1. **Yield sources** — base interest vs. emissions vs. farm rewards. Emissions carry token price risk. 2. **Reserve concentration** — a vault heavy in one high-APY reserve takes more allocation risk than a distributed vault. 3. **Collateral in underlying reserves** — yield in markets accepting riskier collateral (e.g., JLP) is higher because the lending market accepts more risk. Higher yield reflects accepted risk, not a free lunch. 4. **Curator track record** — allocation decisions drive how the vault responds to rate changes and market conditions. A 10% APY in organic USDC interest from a broadly distributed vault is a materially different product from a 12% APY concentrated in one high-utilization reserve with token emissions. For stablecoin vaults specifically, the [Benchmark Rate](/products/lending-vaults/benchmark-rate) provides an objective baseline to compare against — a deposit-weighted average of yields across the largest DeFi lending protocols. # Curators & Fees Source: https://docs.kamino.com/products/lending-vaults/curators Vault curators, fee structures, and trust features ## What curators do Curators are the risk managers of a vault. Each vault has a single curator responsible for setting and updating allocation targets across Kamino's lending markets and reserves. A curator's core function is portfolio construction: deciding how much of the vault's capital goes to each reserve, which markets to enter or exit, and how to balance yield against concentration and utilization risk. Active curators monitor reserve [utilization](/products/lending-vaults/concepts#utilization) rates, adjust allocations when yield opportunities shift, and respond to changing risk conditions across markets. A vault with an attentive curator can capture higher weighted yields than a static allocation by rotating capital toward higher-utilization reserves and away from reserves where borrowing demand has dropped. No governance process governs individual allocation decisions. Curators act with discretion within the vault's parameters — depositors are extending trust to the curator's judgment. ## Trust features Kamino vaults support two on-chain trust features that give depositors stronger guarantees about how their capital is managed and protected. > [card] [Insurance Pool](/products/lending-vaults/insurance-pool) > > Curators can lock their own capital into the vault with a cooldown period, giving them direct financial exposure to their own allocation decisions. The lockup prevents curators from exiting before depositors can react to adverse conditions. > [card] [Whitelisted Reserves](/products/lending-vaults/whitelisted-reserves) > > Vaults can be permanently restricted to only allocate into Kamino-approved reserves. This protocol-level constraint blocks allocation into fraudulent markets, even if the curator's admin key is compromised. ## Fee structure Curator fees compensate the curator for active management. There are no fees charged at deposit. | Fee type | Recipient | Based on | Purpose | | - | - | - | - | | Performance fee | Curator | Percentage of vault profits | Aligns curator with yield generation | | AUM fee | Curator | Annual % of total vault assets | Compensates ongoing management | | Withdrawal penalty | Vault (not curator) | Small % of withdrawn amount | Returned to vault to prevent deposit-yield-claim-withdraw exploits | Performance fees are deducted from earned yield, not principal — you do not pay a performance fee on a loss. AUM fees are accrued continuously from total assets. The withdrawal penalty, unlike the other two, is not revenue for the curator; it is credited back to remaining depositors to disincentivize mercenary capital strategies. ## Multiple curators, one token Multiple independent curators can create vaults for the same deposit token. A user depositing USDC may choose between several USDC vaults — each with a different curator, a different allocation strategy, different reserve exposure, a different fee structure, and different trust features. Selecting a vault is selecting a curator and their strategy. Factors to compare across USDC vaults: trailing APY net of fees, [Insurance Pool](/products/lending-vaults/insurance-pool) commitment and lockup, [Whitelisted Reserves](/products/lending-vaults/whitelisted-reserves) status, allocation concentration across markets, and the curator's track record and public reputation. # How It Works Source: https://docs.kamino.com/products/lending-vaults/how-it-works Vault shares, yield mechanics, allocation, and withdrawals ## Vault shares Every vault has a [share price](/products/lending-vaults/concepts#share-price-and-auto-compounding) — the net asset value (NAV) per share — which starts at a base value and increases over time as interest accrues. When you deposit, shares are minted at the current share price. When you withdraw, shares are redeemed at the current (higher) share price. Your share count never changes between deposit and withdrawal; what changes is what each share is worth. Worked example: you deposit 1,000 USDC when the vault share price is \$1.00, receiving 1,000 kvUSDC shares. The vault deploys your capital across its target reserves. Over a period of time, the weighted yield across those reserves compounds into the vault's total assets. When the share price reaches \$1.06, your 1,000 shares redeem for 1,060 USDC. Vault shares are standard fungible tokens and are visible in your wallet as a distinct token (e.g., kvUSDC-prime). They can be held, transferred, and used in other protocols that accept them as collateral. ## How yield is calculated Vault yield is the weighted average of the APYs earned across all active reserve allocations: ``` Vault APY ≈ Σ (Reserve APY × Allocation Weight) ``` Each [reserve](/products/lending-vaults/concepts#what-is-a-lending-reserve) earns based on its [utilization](/products/lending-vaults/concepts#utilization) rate and the borrow rate curve set for that market. A reserve at 80% utilization earning 8% APY contributes proportionally to the vault's total yield based on how much of the vault's capital is deployed there. Allocation weights sum to 100% across all active reserves. Because underlying borrow rates and utilization levels change continuously, vault APY fluctuates. Quoted APYs are trailing averages and are not guaranteed forward-looking rates. Both variable-rate and fixed-rate reserves can be part of a vault's allocation, and the yield model applies uniformly across both types. ## Allocation [Curators](/products/lending-vaults/concepts#what-curators-do) set target allocation weights across reserves within Kamino's lending markets — SOL/BTC Market, JLP Market, Altcoin Market, Prime, and others. A typical USDC vault might target 60% in SOL/BTC Market USDC variable, 30% in JLP Market USDC, and 10% in fixed-rate reserves. The vault rebalances automatically toward these targets as capital flows in and out. Individual depositors do not choose which reserves their capital enters. The vault aggregates all depositor capital and deploys it as a single pool according to the curator's allocation. This means your effective exposure is the blended risk and yield of the vault's full portfolio — not any single reserve. Curators can update allocation targets at any time. Changes are executed on-chain and are transparent. Depositors bear the risk of future allocation decisions made by the curator after they deposit. ## Variable vs. fixed-rate allocation Vaults can include both types of reserves in their allocation: * **[Variable-rate reserves](/products/lending-vaults/concepts#variable-vs-fixed-reserves)** — capital is always deployed and earns the prevailing borrow rate, which moves with utilization. * **[Fixed-rate reserves](/products/lending-vaults/concepts#variable-vs-fixed-reserves)** — capital is held in a conditional liquidity position. It earns the variable rate while waiting, and transitions to a fixed rate when a matched borrower requests the capital. This allows vaults to earn fixed yields on a portion of their portfolio without sacrificing liquidity. See [Fixed Rates](/products/borrow/fixed-rates) for a full description of how conditional liquidity and fixed-rate matching work. ## Withdrawals Vaults maintain an unallocated buffer — typically 5–10% of total vault assets — held as liquid capital not deployed to any reserve. Withdrawals within this buffer are processed instantly. For withdrawals larger than the buffer, the vault must recall capital from the underlying reserves. In normal market conditions, reserves have sufficient undeployed liquidity to accommodate recall requests promptly, and this process is seamless from the user's perspective. > [!NOTE] > > Withdrawals are available as long as the underlying reserves have liquid capital. Kamino's interest rate curves are designed to prevent full depletion of reserve liquidity by increasing borrow rates sharply as utilization approaches 100%, creating economic pressure for borrowers to repay. In high-utilization scenarios where reserve liquidity is constrained, a withdrawal may be delayed until borrowers repay and liquidity is restored. This is a temporary condition tied to market activity rather than a vault-specific mechanism. Vault depositors who require guaranteed same-block liquidity should size their position relative to the vault's available buffer. # Lending Vaults Source: https://docs.kamino.com/products/lending-vaults/index Single-token managed yield aggregation across Kamino's lending markets Lending Vaults are single-token yield aggregators where a curator allocates your deposited capital across Kamino's lending markets and reserves. Deposit one token — USDC, SOL, JLP — and receive vault shares that passively appreciate in value as interest accrues across the vault's active allocations. You earn yield without selecting markets, managing utilization exposure, or monitoring individual positions. > [card] [How It Works](/products/lending-vaults/how-it-works) > > Vault shares, yield mechanics, and how curators allocate capital across reserves > [card] [Curators & Fees](/products/lending-vaults/curators) > > Who manages vaults, fee structures, and trust features > [card] [Risks](/products/lending-vaults/risks) > > Allocation risk, liquidity constraints, and what protects depositors > [card] [Concepts](/products/lending-vaults/concepts) > > Reserves, utilization, share price, curators, and bad debt explained ## How shares work When you deposit into a vault, shares are minted at the vault's current share price (net asset value per share). The number of shares you hold remains constant. As the vault earns interest from its allocations, the underlying assets per share increase — meaning the share price rises. When you withdraw, you redeem your shares at the current share price, receiving more of the deposit token than you put in. Example: you deposit 1,000 USDC when the vault's share price is \$1.00, receiving 1,000 kvUSDC shares. After some time, accumulated interest has pushed the share price to \$1.06. Your 1,000 shares are now worth 1,060 USDC — a 6% gain with no action required on your part. The share price is a direct function of the vault's total assets divided by total shares outstanding, updated continuously as interest accrues from the underlying lending reserves. > [!NOTE] > > This is [auto-compounding](/products/lending-vaults/concepts#share-price-and-auto-compounding) — earned interest is reinvested continuously without any action on your part. Your shares appreciate in value rather than distributing periodic payments. # Insurance Pool Source: https://docs.kamino.com/products/lending-vaults/insurance-pool Curator-backed loss backstop that compensates depositors after vault losses ## What is the Insurance Pool? The Insurance Pool is a mechanism where a vault curator locks their own capital into the vault as a **loss backstop**. If the vault incurs bad debt and losses are socialized, the curator's locked capital is used to make depositors whole — compensating them for the losses they incurred. In simple terms: the curator puts their own money on the line. When things go wrong, depositors are compensated from the Insurance Pool after the fact. ## How it works A curator deposits capital into the vault and receives vault shares (kTokens), just like any depositor. These shares are then staked into a dedicated Insurance Pool with a mandatory 30-day cooldown — during which the curator cannot withdraw. **1. Curator deposits** The curator deposits capital (e.g. USDC) into their own vault and receives vault shares. **2. Shares are locked** The shares are staked into the Insurance Pool with a mandatory 30-day cooldown. **3. Capital serves as a backstop** If the vault incurs bad debt, losses are socialized across the vault. The curator's Insurance Pool capital is then used to compensate affected depositors. **4. Cooldown enforces commitment** The curator cannot withdraw during the cooldown window, ensuring their capital remains available through adverse conditions. ## Why it matters **Skin in the game with a real backstop.** The Insurance Pool financially aligns the curator with depositors: * If the vault incurs bad debt, the curator's locked capital is used to compensate depositors after losses are socialized * If the curator makes poor allocation decisions, **their capital is on the line** * The cooldown prevents the curator from quietly exiting before depositors can react * Accountability is enforced by code, not just promised ## What depositors see Depositors can verify the following on-chain: | Detail | Why it matters | | - | - | | Whether the vault has an Insurance Pool | Indicates the curator has committed capital as a loss backstop | | How much capital is locked | A larger pool means more capacity to compensate depositors after a loss event | | The cooldown period | The mandatory 30-day cooldown prevents the curator from exiting before depositors can react | # Risks Source: https://docs.kamino.com/products/lending-vaults/risks Understanding the risks of depositing into Lending Vaults > [!WARNING] > > Vault deposits are subject to curator allocation decisions and underlying lending market risks. Past vault performance does not guarantee future returns. ## Curator allocation risk Curators manage vault allocations with discretion — no governance approval is required for allocation changes. A curator may deploy capital to reserves that underperform, become highly concentrated in a single market, or react slowly to deteriorating conditions. Depositors bear the risk of every allocation decision made after their deposit. Before depositing, evaluate the curator's track record, their [Insurance Pool](/products/lending-vaults/insurance-pool) commitment and lockup duration, and any public documentation of their strategy. Vaults with transparent on-chain histories and meaningful Insurance Pool commitments provide stronger signals than vaults with neither. ## Lending market risk Vaults allocate to Kamino's lending markets. If a borrower defaults and creates [bad debt](/products/lending-vaults/concepts#bad-debt) in a reserve, lenders — including the vault — absorb losses proportional to their share of that reserve. A vault allocated 40% to an affected reserve would absorb 40% of the losses attributable to the vault's share of that reserve. Kamino's smart contracts have undergone 20 external security reviews and have no bad debt history to date. This track record provides meaningful evidence of contract security, but cannot guarantee that no future loss occurs. Lending protocols carry irreducible smart contract and market risk. > [!NOTE] > > Vaults where the curator has locked capital in an [Insurance Pool](/products/lending-vaults/insurance-pool) provide stronger alignment — the curator has direct financial exposure to their own allocation decisions and cannot exit during the lockup window. ## Liquidity risk Capital deployed to lending reserves is not always immediately available for recall. If the reserves in a vault's allocation are at high [utilization](/products/lending-vaults/concepts#utilization) — meaning most of the deposited capital has been borrowed — the vault cannot immediately return that capital to a withdrawing depositor. In this scenario, the withdrawal waits until borrowers repay and liquidity is restored to the reserve. Kamino's interest rate curves are designed to prevent full utilization: borrow rates increase sharply as utilization approaches 100%, creating strong economic incentives for borrowers to repay. In practice, temporary high utilization is possible during periods of elevated borrowing demand, and a short withdrawal delay may result. Vaults maintain a 5–10% unallocated buffer for instant withdrawals. Withdrawals within this buffer are unaffected by reserve utilization conditions. ## Fee drag Performance fees and AUM fees are deducted from vault yield and assets respectively. The vault APY displayed on the interface reflects net yield after fees. When comparing vaults or comparing a vault against direct lending, use net APY figures — gross reserve yields do not reflect what depositors actually earn. ## Insurance Pool as protection > [!TIP] > > Prioritize vaults where the curator has locked capital in an [Insurance Pool](/products/lending-vaults/insurance-pool) with a cooldown period of 30 days or longer. The lockup is what prevents a curator from quietly withdrawing their own capital before an adverse event becomes public. The Insurance Pool is curator capital locked in the vault with a cooldown period. A vault where the curator has locked meaningful capital relative to the vault's TVL provides a stronger alignment signal — the curator has direct financial skin in the game and cannot exit before depositors can react. Verify the Insurance Pool amount and cooldown duration on-chain before committing significant capital to any vault. # Whitelisted Reserves Source: https://docs.kamino.com/products/lending-vaults/whitelisted-reserves Protocol-level restriction on which reserves a vault can allocate to ## What are Whitelisted Reserves? Whitelisted Reserves is a smart contract-level restriction that ensures a vault's funds can only be allocated into reserves that Kamino has explicitly verified. Any attempt to allocate into a non-whitelisted reserve is rejected by the smart contract, regardless of who signs the transaction. All vaults on Kamino's UI have Whitelisted Reserves enabled, and this is a requirement for any vault to be featured on the Kamino interface. ## How it works Whitelisted Reserves enforces two independent on-chain restrictions: | Restriction | What it does | | - | - | | **Allocation control** | A curator cannot create or increase allocations to any reserve outside the whitelist | | **Investment control** | Depositor funds cannot flow into any unvetted reserve via the vault | Both restrictions are enforced at the smart contract level. Both are **irreversible** once activated — they cannot be turned off by the curator or anyone else. Kamino maintains the whitelist at the protocol level. Curators can activate Whitelisted Reserves on their vault and manage allocations within it, but they have no control over the whitelist itself. ## What it protects against In a scenario where a curator's keys are compromised, the attacker could gain operational control of the vault. Without whitelisting, the attacker could redirect funds to a malicious or unvetted market and drain the vault's liquidity. With Whitelisted Reserves, that attack path is closed. The smart contract rejects any allocation or investment into a reserve that Kamino has not explicitly whitelisted — even with full admin access, there is no path to drain funds into a fraudulent market. This is **protocol-level security**, not operational security. The constraint is enforced by the smart contract itself, independent of the curator's key management practices or multisig configuration. ## Withdrawals Withdrawals are always permitted, regardless of whitelist status. Curators can de-allocate from any reserve at any time. Depositors are free to enter or exit vaults at any time, subject to available liquidity. ## What depositors see All vaults on Kamino's UI have Whitelisted Reserves enabled. This means: | Guarantee | Description | | - | - | | Restricted allocation | The vault can only deploy capital into Kamino-verified reserves | | Immutable setting | The restriction cannot be reversed, even by the vault admin | | Protocol enforcement | The constraint is enforced at the smart contract level, not by policy | > [!NOTE] > > Whitelisted Reserves is a security feature, not a guarantee of returns. A vault with whitelisting enabled is protected against allocation into fraudulent markets, but the whitelisted reserves themselves still carry normal lending risks (utilization, bad debt, liquidity). ## Vault security Kamino's Vaults smart contract has undergone extensive security review since its launch in early 2025, including 6 external audits, formal verification, and on-chain verification. All reports are available on the [Security](/security) page. Whitelisted Reserves is a significant step beyond smart contract security — it adds a layered risk mitigation that protects depositors even in scenarios where operational keys are compromised. Every vault on Kamino's frontend has Whitelisted Reserves activated today, including all major curators — Sentora, Gauntlet, Steakhouse, Allez, Rockaway, and more. # Concepts Source: https://docs.kamino.com/products/liquidity/concepts AMMs, concentrated liquidity, impermanent loss, and how Kamino's vault strategies manage LP positions ## Traditional AMMs and the capital efficiency problem An automated market maker (AMM) is a liquidity pool where price is determined by the ratio of two tokens. The constant product formula: ``` x × y = k ``` Where `x` and `y` are the token balances and `k` is a constant. Price at any moment is `y / x`. When a trader buys token X, they add Y and remove X, changing the ratio and moving the price. **The capital inefficiency problem:** The constant product formula distributes capital uniformly across ALL possible prices — from 0 to infinity. At any given moment, only a small fraction of that capital is near the current market price and actually useful for trades. A \$10M pool might have only \$200k of capital earning fees at any given time. The remaining \$9.8M is deployed at prices the market may never reach. *** ## Concentrated liquidity Concentrated Liquidity Market Makers (CLMMs) let LPs choose a specific price range for their capital. Instead of spreading across all prices, capital is deployed only where trades actually happen — the range where the current market price sits. **When price is within your range:** * Your capital earns trading fees proportional to your share of total in-range liquidity * Capital is split between both tokens according to the pool's current ratio **When price is outside your range:** * Your position earns zero fees * Your capital is 100% in whichever asset the price moved toward (fully converted at the range boundary) This makes capital exponentially more efficient: a \$1M concentrated position can provide the same depth as a \$10M+ traditional AMM position when positioned correctly. Kamino's Liquidity Vaults use Raydium CLMM as the underlying DEX. *** ## Price ranges and "in range" The LP specifies a lower bound and upper bound (e.g., 100–200 SOL/USDC). The position behaves differently depending on where the market price sits: | Market price | Position status | Fee income | | - | - | - | | Within the range | In range | Earns fees proportional to share of in-range liquidity | | Below lower bound | Out of range | Zero fees; position is 100% in the quote token | | Above upper bound | Out of range | Zero fees; position is 100% in the base token | **Tighter range = higher capital efficiency when in-range.** A narrower range means a larger share of the active liquidity (earning more fees per dollar) but exits range more often, requiring more rebalances. *** ## Impermanent loss Impermanent loss (IL) is the difference in value between holding two assets vs. providing them as liquidity in an AMM. **Why it happens:** As market price moves, the AMM automatically rebalances the position — always selling the appreciating asset and buying the depreciating one. The LP ends up holding less of the asset that went up and more of the one that went down compared to simply holding. **In CLMMs, IL is amplified.** Because capital is concentrated, each unit of price movement rebalances more capital than a traditional AMM would. The amplification is proportional to the concentration factor — the same reason concentrated liquidity earns more fees per dollar also means it incurs more IL per dollar of price movement. **"Impermanent" vs. realized:** IL is impermanent while the price might return to entry. It becomes realized (permanent) when you withdraw. At that point, it's simply the performance difference between LP vs. hold. **The trade-off:** IL is the cost of earning trading fees. If fee income over the period exceeds IL, the LP position is net profitable relative to holding. If fees don't cover IL — common in low-volume, high-volatility pairs — the LP would have been better off holding. > [!WARNING] > > Impermanent loss is not a fee or a transaction cost — it is a structural consequence of providing liquidity. It affects all LP positions and can be significant in concentrated liquidity positions with narrow ranges during periods of high volatility. Always evaluate expected fee income against expected IL for your target price range before entering a position. *** ## Trading fees Every swap through a pool pays a fee (e.g., 0.01%, 0.05%, 0.3% depending on pool tier). This fee is split among all LPs who have active liquidity at the price of the swap — in-range positions only. **What makes fees higher for your position:** * High trading volume through the pool * A narrow price range (larger share of active in-range liquidity per dollar) **What makes fees lower:** * Low trading volume * Wide price range (smaller share of active liquidity) * Price outside your range (zero fees) Kamino auto-compounds all earned fees: rather than distributing fee tokens separately, fees are reinvested back into the LP position, increasing the kToken exchange rate over time. *** ## The range width trade-off Every liquidity position involves a trade-off between capital efficiency and range stability: **Narrow range:** * Higher capital efficiency → earns more fees per dollar when in-range * Exits range more frequently → requires more rebalancing * Each rebalancing event incurs swap costs (slippage + fees on the rebalance transaction) **Wide range:** * Lower capital efficiency → earns fewer fees per dollar * Stays in range longer → fewer rebalancing events → lower rebalance costs * Less sensitive to short-term price moves Neither extreme is optimal. The best width depends on the pair's volatility, the pool's fee tier, and expected trading volume. Kamino's vault strategies automate this trade-off: the vault manager chooses and adjusts ranges based on current volatility and fee data, targeting the combination that maximizes net return (fees minus rebalance costs minus IL). *** ## kTokens When you deposit into a Kamino Liquidity Vault, you receive kTokens as a receipt. kTokens represent your proportional share of the vault's total LP position. The kToken exchange rate appreciates as trading fees compound into the vault — similar to how Lending Vault share prices rise as interest accrues. # Features Source: https://docs.kamino.com/products/liquidity/features How Kamino automates concentrated liquidity management: auto-swap, auto-compound, and auto-rebalance Kamino Liquidity Vaults automate the three main tasks that make [concentrated liquidity](/products/liquidity/concepts#concentrated-liquidity) management burdensome: single-token deposits and withdrawals (auto-swap), fee reinvestment (auto-compound), and range adjustment (auto-rebalance). ## Auto-Swap Concentrated liquidity positions require assets in a specific ratio matching the pool's composition. When a user deposits a single token, Kamino automatically swaps the portion needed to create the correct ratio before deploying capital. The same process applies on withdrawal — users can receive the full position value in a single token rather than being forced to handle both assets separately. * No manual token management required for single-sided deposits or withdrawals * Swap costs (slippage, DEX fees) apply — visible before confirmation * Powered by Kamino Swap for best execution ## Auto-Compound CLMM positions accumulate [trading fees](/products/liquidity/concepts#trading-fees) and reward tokens continuously. Manually harvesting and redepositing these would require frequent transactions and actively managed timing. Kamino auto-compounds all earned fees and rewards back into the position at regular intervals. Compounding: * Increases the total capital deployed in the vault * Directly increases the [kToken](/products/liquidity/concepts#ktokens) exchange rate over time (more underlying assets per kToken) * Eliminates the need for manual harvest transactions and their associated gas costs ## Auto-Rebalance When the market price moves outside a vault's current range, the position earns no fees. Kamino monitors positions continuously and rebalances when the price exits the configured range — moving the position to a new range centered around the current price. Rebalancing events: * Trigger when price exits the vault's range * Involve closing the current position and reopening at a new range * May incur a small cost from slippage on the conversion between assets at the rebalance ratio * Are executed by Kamino's automated bots — no user action required > [!NOTE] > > The frequency and cost of rebalancing depends on price volatility and [range width](/products/liquidity/concepts#the-range-width-trade-off). Tighter ranges earn higher fees when in-range but rebalance more often; wider ranges rebalance less frequently at the cost of lower capital efficiency. # Liquidity Source: https://docs.kamino.com/products/liquidity/index Automated concentrated liquidity vaults for Solana DEX pools Automated liquidity vaults were Kamino's first product, launched in August 2022, and remain the leading LP primitive on Solana. > [!WARNING] > > Providing liquidity involves [impermanent loss](/products/liquidity/concepts#impermanent-loss) — the difference in value between holding assets vs. providing them as liquidity. This is a structural consequence of how AMMs work and affects all LP positions. See [Concepts](/products/liquidity/concepts) for a full explanation before depositing. > [card] [Features](/products/liquidity/features) > > How auto-swap, auto-compound, and auto-rebalance work > [card] [Concepts](/products/liquidity/concepts) > > AMMs, concentrated liquidity, impermanent loss, and kTokens explained ## How yield is earned When a Kamino Liquidity Vault deploys capital into a CLMM pool, it earns trading fees proportional to its share of pool liquidity within the active price range. Any trade that passes through the pool incurs a fee distributed to liquidity providers. Additionally, many pools distribute reward tokens to liquidity providers — Kamino collects and compounds these automatically. Yield depends on trading volume in the pool and whether the vault's position is in range. An out-of-range position earns no fees until it is rebalanced. ## kTokens [kTokens](/products/liquidity/concepts#ktokens) are the fungible SPL token receipts issued when depositing into a Kamino liquidity vault. The exchange rate between kTokens and the underlying assets increases as fees and rewards are compounded back into the position. ## Concentrated liquidity [Concentrated liquidity](/products/liquidity/concepts#concentrated-liquidity) allows liquidity providers to concentrate capital within a specific price range rather than spreading it uniformly across all prices. This makes capital far more efficient — earning more fees per dollar deployed — but requires active management to keep positions in range as prices move. Kamino's automation solves this management burden. # Concepts Source: https://docs.kamino.com/products/multiply/concepts Flash loans, looping, Net APY, and the three categories of Multiply strategies — LSTs, JLP, and RWAs ## Flash loans A flash loan is an uncollateralized loan that is borrowed and fully repaid within the same transaction block. If repayment fails for any reason — slippage, insufficient liquidity, contract error — the entire transaction reverts as if it never happened. The protocol carries zero risk from the loan itself: state changes only commit if repayment succeeds. The fee is **0.001% per transaction** — applied when opening, adjusting, or closing a Multiply position. Flash loans are the enabling technology behind atomic looping. Without them, building a leveraged position requires 8–10 separate transactions across multiple blocks, each exposed to price movement and execution risk. With a flash loan, the entire sequence executes atomically in a single transaction. *** ## Looping — how leverage is built Looping is the process of repeatedly depositing a yield-bearing asset, borrowing against it, and reinvesting the borrowed amount to amplify yield exposure. The leverage is built through this cycle. **Without flash loans**, manual looping looks like this: 1. Deposit JitoSOL as collateral 2. Borrow SOL against it 3. Swap SOL to JitoSOL 4. Re-deposit — repeat across 8–10 transactions Each step carries price exposure, slippage, and execution risk. Rates or prices can move between steps. **With flash loans**, the entire sequence is atomic. For a JitoSOL/SOL position: 1. Take a flash loan of SOL 2. Swap SOL to JitoSOL 3. Deposit JitoSOL as collateral into Kamino Lend 4. Borrow SOL against the deposited collateral 5. Repay the flash loan with the borrowed SOL 6. Net result: JitoSOL collateral on deposit, SOL debt outstanding, levered position established The protocol handles all steps. The user selects a target leverage multiplier and clicks once. Either the full position opens at that leverage, or nothing executes. *** ## The leverage ratio ``` Leverage = Total collateral value / Net equity Net equity = Total collateral value − Total debt value ``` With \$8,000 JitoSOL collateral and \$7,000 SOL debt: * Net equity = \$1,000 * Leverage = 8x The maximum achievable leverage is bounded by Max LTV: ``` Max leverage = 1 / (1 − Max LTV) ``` | Max LTV | Max leverage | | - | - | | 75% | 4x | | 87% (eMode) | \~7.7x | | 90% (eMode Jito) | 10x | Operating at the maximum puts Current LTV exactly at the liquidation threshold. Real positions always require a buffer below the limit. *** ## Net APY — the fundamental equation Net APY is the primary metric for evaluating any Multiply position. It captures the amplified yield minus the amplified borrow cost. ``` Net APY = (Collateral Yield × Leverage) − (Borrow Rate × (Leverage − 1)) ``` Equivalently, using **Yield Spread = Collateral Yield − Borrow Rate**: ``` Net APY = Collateral Yield + Yield Spread × (Leverage − 1) ``` A positive spread grows with leverage. A negative spread grows more negative with leverage. There is no floor. **LST example — JitoSOL/SOL at 8x, 7% staking yield, 6% SOL borrow rate:** ``` Net APY = 7% + (7% − 6%) × (8 − 1) = 7% + 7% = 14% ``` **RWA example — PRIME/PYUSD at 4x, 8% base yield, 5% PYUSD borrow rate:** ``` Net APY = 8% + (8% − 5%) × (4 − 1) = 8% + 9% = 17% ``` **Negative spread example — 3x leverage, 6% collateral yield, 8% borrow rate:** ``` Net APY = 6% + (6% − 8%) × (3 − 1) = 6% − 4% = 2% ``` Unlevered return would have been 6%. Adding 3x leverage reduced it to 2%. Higher leverage makes it worse. > [!WARNING] > > Borrow rates on Kamino Lend are variable and adjust based on market utilization. A positive yield spread today can flip negative during high-utilization periods without any action on your part. Monitor the spread continuously — not just the headline APY shown at position open. *** ## Liquid staking tokens (LSTs) **Staking** is the process of locking SOL with a validator to help secure the Solana network. Validators earn rewards each epoch, which are distributed to stakers. A **liquid staking token** (LST) represents a claim on staked SOL. Instead of locking SOL directly, you deposit into a staking pool and receive an LST in return. The LST earns yield not through periodic distributions but through exchange rate appreciation: as staking rewards accrue into the pool, each LST becomes redeemable for more SOL. ``` LST exchange rate = SOL_staked / LST_minted ``` This ratio increases monotonically each epoch. Supported LSTs on Multiply: JitoSOL, mSOL, bSOL, JupSOL. **Why LSTs are well-suited for leverage:** The yield source is structural — validator rewards accrue on every epoch regardless of market conditions or protocol usage. The staking yield exists whether or not anyone is using Multiply. This is distinct from fee-driven yield (like JLP) or credit market yield (like RWAs), both of which can compress or disappear. *** ## JLP — what it is and why the risk profile differs JLP (Jupiter Liquidity Provider token) is a basket token issued by Jupiter's perpetuals exchange. Its composition is approximately: * \~65% crypto-native assets (SOL, ETH, BTC) * \~35% stablecoins (USDC, USDT) JLP earns yield from trading fees and funding payments generated by Jupiter's perpetuals platform. Unlike LSTs, JLP is **market-price denominated** — its USD value rises and falls with SOL, ETH, and BTC prices. **Key difference for leverage:** In a JLP/USDC Multiply position, the collateral (JLP) can decline in USD terms while the debt (USDC) stays flat. This raises the LTV directly, independent of any borrow rate dynamics. Liquidation can be triggered by price action alone. JLP and USDC are not correlated, so eMode does not apply. This limits JLP Multiply to a maximum of \~3.2x leverage, compared to up to 10x for LST/SOL eMode pairs. The \~35% stablecoin component in JLP provides a partial downside buffer but does not eliminate price liquidation risk. *** ## RWA tokens — real-world yield on leverage Real-world asset (RWA) tokens represent on-chain claims on off-chain financial instruments. Their yield comes from real-world cash flows — loan interest, insurance premiums, credit market returns — that are structurally uncorrelated to crypto market performance. Multiply supports three RWA tokens: **PRIME** (\~8% base yield) Tokenized US home equity loans (HELOCs) originated by Figure Finance. Maintains an approximate \$1 USD peg. Borrowed against PYUSD at up to \~8.3x leverage (88% LTV). Yield is generated by interest payments from HELOC borrowers. **ONyc** (\~16% base yield) Reinsurance-backed yield from OnRe Finance, combining \~8% insurance premiums and \~8% stablecoin yield. NAV is verified on-chain via a Chainlink oracle. Borrowed against stablecoins. **SyrupUSDC** (\~5–6% base yield) Maple Finance institutional credit market yield, delivered via Chainlink CCIP bridge. Borrowed against stablecoins at 4–5x leverage. The looping mechanism for RWA tokens is identical to LSTs — the same flash loan structure, the same Net APY formula. What differs is the yield source and the nature of the risk. > [!NOTE] > > Supported RWA strategies change as new issuers integrate with Kamino. Check the Multiply interface for current available vaults and live APY data. *** ## The dollar-denominated advantage (RWA looping) For PRIME/PYUSD, ONyc/USDC, and SyrupUSDC/USDC positions: both sides of the position are dollar-denominated. Collateral holds a stable USD value; debt is a USD-denominated stablecoin. If SOL, ETH, or BTC prices move, neither side of the position is affected. Price-driven liquidation is structurally absent. **What CAN cause liquidation in RWA positions:** * Borrow rates exceeding RWA yield — the spread turns negative and LTV drifts upward over time * Issuer-specific events that cause NAV deterioration (e.g., HELOC default rates rising) **RWA-specific risks with no LST equivalent:** * **Counterparty risk** — dependence on Figure Finance, OnRe Finance, and Maple Finance to perform as expected * **Underlying credit default** — HELOC borrowers defaulting on home equity loans; catastrophic reinsurance losses exceeding premiums collected * **Redemption liquidity** — RWA collateral may not liquidate as rapidly as liquid on-chain assets in a stress scenario; protocol liquidators may face delays in converting RWA collateral * **NAV drawdown** — for ONyc specifically, catastrophic reinsurance claims exceeding premiums can reduce NAV directly, causing collateral value to fall independent of market prices > [!WARNING] > > RWA tokens introduce off-chain credit risk and counterparty risk that crypto-native assets do not carry. Evaluate the credit quality of the underlying issuer and the terms of the underlying instrument before entering a leveraged RWA position. These risks cannot be assessed from on-chain data alone. *** ## The SOL-denominated advantage (LST looping) For JitoSOL/SOL, mSOL/SOL, bSOL/SOL, and JupSOL/SOL positions: both collateral and debt are denominated in SOL. When the SOL price changes, both sides of the position move proportionally. The LTV ratio stays flat regardless of SOL's USD price. This is why zero SOL LST Multiply positions have been liquidated due to market price moves in Kamino's history — not across any market event, including the April 2025 correction and the February 2026 crash. The only spread risk that matters is the interest rate differential: staking yield minus SOL borrow rate. If that spread stays positive, the position is healthy. If it turns negative and stays there, LTV drifts upward over time. > [!NOTE] > > SOL-denomination neutrality does not protect against smart contract exploits in the underlying staking protocol. If the staking protocol is compromised and actual SOL_staked value declines, the exchange rate falls and LTV deteriorates. Independently evaluate the smart contract risk of each LST issuer (Jito, Marinade, Blaze, Jupiter, etc.). *** ## Stake-rate oracle protection For SOL LST positions, Kamino prices the LST collateral using the **stake pool exchange rate**, not the spot market price: ``` LST Price = SOL_staked / LST_minted ``` This ratio increases monotonically each epoch as staking rewards accrue. It does not track the secondary market price of the LST. **Why this matters:** LSTs occasionally trade at a market discount — during stress events, JitoSOL might trade at 0.95 SOL instead of its theoretical 1.05 SOL exchange rate value. In a system using spot price oracles, this discount raises the reported LTV and can push healthy positions into liquidation. In Kamino, the LTV calculation uses the exchange rate. The market discount is invisible to the position. This is the primary reason temporary market depegs have never triggered Kamino LST liquidations. Across DeFi history, temporary depeg cascades have been the dominant source of unexpected LST liquidations — the stake-rate oracle eliminates this failure mode. **What it does NOT protect against:** An exploit or insolvency event in the underlying staking protocol that actually reduces the SOL_staked balance. In that case, the exchange rate itself falls and the LTV calculation reflects the deterioration. Stake-rate oracle protection is specifically about market mispricing, not fundamental protocol failure. *** ## eMode in Multiply eMode (Elevation Mode) is a Kamino Lend feature that raises the permitted Max LTV for designated correlated asset pairs. Standard lending markets limit LTV to protect against price divergence between collateral and debt — but when the two assets track each other closely, that divergence risk is minimal. eMode reflects this by permitting higher LTV, which translates directly into higher maximum leverage. | Mode | Example pair | Max LTV | Max leverage | | - | - | - | - | | Standard | SOL / USDC | 75% | 4x | | eMode Main | mSOL, bSOL, JupSOL / SOL | \~87% | \~7.7x | | eMode Jito | JitoSOL / SOL | 90% | 10x | | No eMode | JLP / USDC | 67% | \~3.2x | eMode only applies between designated correlated pairs. JLP/USDC has no eMode because JLP's value is not correlated with USDC. Full eMode parameters for all lending markets are documented in [Borrow Concepts](/products/borrow/concepts). Higher Max LTV from eMode means a narrower gap between operating LTV and the liquidation threshold. Operating near maximum eMode leverage requires closer monitoring of the yield spread — a small adverse move in borrow rates has a proportionally larger effect on position health at high leverage. **RWA/stablecoin pairs achieve high leverage through a parallel mechanism:** PRIME/PYUSD and similar pairs are dollar-denominated on both sides, so price divergence risk is near-zero by construction. This allows high LTV (88% for PRIME/PYUSD) without eMode designation — the same underlying logic applies, but in the stablecoin domain rather than the SOL domain. # How It Works Source: https://docs.kamino.com/products/multiply/how-it-works The mechanics behind Multiply — flash loans, eMode, and yield amplification > [!WARNING] > > Multiply positions carry liquidation risk. The higher the leverage, the smaller the buffer between your current LTV and the liquidation threshold. Borrow rates are variable — if they exceed collateral yield for a sustained period, your debt grows relative to your collateral. Multiply opens, adjusts, and closes leveraged positions in a single atomic transaction. The mechanism relies on a [flash loan](/products/multiply/concepts#flash-loans): an uncollateralized borrow that is borrowed and repaid within the same transaction block, with no exposure beyond that block. If the transaction cannot repay the flash loan — due to slippage, insufficient liquidity, or any other failure — the entire transaction reverts and no position is created. The flash loan fee is **0.001% per transaction**, applied at open, adjustment, and close. **A Multiply position opens in seven steps:** 1. User specifies deposit amount and target leverage multiplier 2. Protocol borrows the required additional amount via flash loan 3. Flash-borrowed funds and user deposit are swapped into the target asset (e.g., SOL → JitoSOL) via Kamino Swap 4. The full target asset amount is deposited into Kamino Lend as collateral 5. The underlying asset (e.g., SOL) is borrowed against the deposited collateral 6. Borrowed funds repay the flash loan 7. Position is established at target leverage with collateral and debt recorded on Kamino Lend Closing a position reverses this flow: flash loan borrows enough to repay the debt, collateral is withdrawn, a portion is swapped back to repay the flash loan, and the remainder is returned to the user. ## Elevation Mode (eMode) [eMode](/products/multiply/concepts#emode-in-multiply) groups correlated asset pairs under elevated LTV ratios. Standard lending markets limit LTV to protect against price divergence between collateral and debt assets — but when collateral and debt are closely correlated (e.g., JitoSOL and SOL), that divergence risk is minimal. eMode reflects this by raising the maximum permitted LTV. | Mode | Example Pair | Max LTV | Max Leverage | | - | - | - | - | | Standard | SOL collateral / USDC debt | 75% | \~4x | | eMode — SOL/BTC Market | mSOL, bSOL, JupSOL vs SOL | \~87% | \~7.5x | | eMode — Jito Market | JitoSOL vs SOL | 90% | 10x | | No eMode | JLP vs USDC | 67% | \~3.2x | > [!NOTE] > > eMode only applies between designated correlated pairs. JLP/USDC has no eMode because JLP's value is not pegged to USDC — it tracks a basket of perpetuals market assets and fluctuates independently. Higher LTV ratios from eMode shrink the gap between your operating LTV and the liquidation threshold. Operating near maximum leverage in an eMode pair means small adverse moves in the yield spread can have a significant effect on position health. ## Net APY Mechanics Multiply is profitable when collateral yield exceeds the borrow rate. Leverage amplifies both the gain and the loss symmetrically. See [Net APY — the fundamental equation](/products/multiply/concepts#net-apy--the-fundamental-equation) for the full breakdown across all strategy types. ``` Net APY = (Collateral Yield × Leverage) − (Borrow Rate × (Leverage − 1)) ``` Equivalently: `Net APY = Collateral Yield + Yield Spread × (Leverage − 1)` Where **[Yield Spread](/products/multiply/concepts#net-apy--the-fundamental-equation) = Collateral Yield − Borrow Rate**. A positive spread grows larger with leverage. A negative spread grows more negative with leverage. There is no floor. **Worked example — 8x JitoSOL/SOL position:** | Metric | Value | | - | - | | Initial deposit | 1,000 SOL | | Leverage | 8x | | Total SOL exposure | 8,000 SOL | | Total SOL debt | 7,000 SOL | | LTV | 87.5% | | JitoSOL APY | 7% | | SOL borrow rate | 6% | | Staking yield earned | 560 SOL | | Borrow cost | 420 SOL | | Net SOL earned | 140 SOL | | Net APY on initial deposit | **14%** | > [!WARNING] > > Borrow rates on Kamino Lend are variable and adjust based on market utilization. If SOL borrow rate rises from 6% to 7.5% in this example while JitoSOL APY remains at 7%, the yield spread inverts and Net APY goes negative. Monitor the spread, not just the headline APY shown at position open. ## Stake-Rate Oracle Protection [SOL LST](/products/multiply/concepts#liquid-staking-tokens-lsts) Multiply positions use the **stake pool exchange rate** to price the LST collateral, not the spot market price. The exchange rate is derived from the underlying staking protocol: ``` LST Price = SOL_staked / LST_minted ``` This ratio increases monotonically each epoch as staking rewards accrue into the pool. It does not track the market price of the LST on secondary markets. **Why this matters:** If JitoSOL trades at a temporary market discount — say, 0.95 SOL instead of the theoretical 1.05 SOL — the LTV calculation on your Multiply position uses 1.05 SOL. The market dislocation does not affect your position health. This is the primary reason zero SOL LST Multiply positions have been liquidated: temporary market depegs, which have historically been the main source of unexpected LST liquidations across DeFi, do not trigger liquidation in Kamino. > [!WARNING] > > Stake-rate oracle protection does not cover smart contract exploits in the underlying staking protocol. If the staking protocol itself is compromised and the actual SOL_staked value declines, the exchange rate falls and LTV deteriorates accordingly. This is an unmitigated risk in any LST position. ## Fixed-Rate Borrow Integration Variable borrow rates introduce uncertainty into the yield spread. [Fixed-rate borrowing](/products/borrow/fixed-rates) via Kamino's fixed-rate market allows locking the borrow cost for the full term of a position, converting a variable-spread strategy into a predictable one. This eliminates borrow rate risk at the cost of typically paying a small premium over the variable rate at time of entry. # Multiply Source: https://docs.kamino.com/products/multiply/index Leveraged yield strategies — amplify staking, LP, and RWA returns in a single transaction Multiply automates the leveraged yield [looping](/products/multiply/concepts#looping--how-leverage-is-built) process — supply, borrow, swap, re-supply — into a single atomic transaction using [flash loans](/products/multiply/concepts#flash-loans). What previously required 10+ manual steps and multiple transactions executes in one click, opening a fully leveraged position against Kamino's lending markets. Multiply amplifies returns from SOL liquid staking tokens, JLP, stablecoins, real-world assets, and tokenized equities, with over \$1B deployed and zero bad debt history across more than three years of operation. > [!NOTE] > > A **flash loan** is an uncollateralized borrow that must be repaid within the same transaction block — if repayment fails, the entire transaction reverts. **Looping** is the strategy of repeatedly depositing a yield-bearing asset, borrowing against it, and reinvesting to build a leveraged position. Multiply executes both atomically so you only see the net result. See [Concepts](/products/multiply/concepts) for a full explanation. > [card] [How It Works](/products/multiply/how-it-works) > > Flash loans, eMode, and the looping mechanics that power Multiply > [card] [Strategies](/products/multiply/strategies) > > SOL LSTs, JLP, stablecoins, RWAs, and xStocks > [card] [Risks](/products/multiply/risks) > > Understanding liquidation, borrow rate, and strategy-specific risks before opening a position ## Overview Manual looping to amplify yield on a staking token requires borrowing, swapping, re-depositing, and borrowing again — repeating this cycle across multiple transactions, each with its own slippage exposure and execution risk. Multiply collapses this into one atomic transaction. Either the entire position opens at the target leverage, or nothing executes. **[Net APY](/products/multiply/concepts#net-apy--the-fundamental-equation) is determined by the spread between collateral yield and borrow rate, amplified by leverage:** ``` Net APY = (Collateral Asset Yield × Leverage) − (Borrow Rate × (Leverage − 1)) ``` A positive spread amplified by higher leverage produces outsized returns. A negative spread — where borrow rates exceed collateral yield — produces losses at the same amplification. Monitoring the spread is the primary ongoing responsibility of a Multiply user. **Three features differentiate Multiply from manual looping:** * **[eMode](/products/multiply/concepts#emode-in-multiply)** — Kamino Lend's Elevation Mode groups correlated asset pairs (e.g., JitoSOL/SOL) under elevated LTV ratios, enabling up to 10x leverage that would be impossible against uncorrelated collateral. This is what makes high-leverage LST strategies viable. * **[Stake-rate oracle](/products/multiply/concepts#stake-rate-oracle-protection)** — SOL LST positions are priced using the stake pool exchange rate, not the market price. Temporary LST market depegs do not affect LTV calculations, eliminating a major source of unfair liquidations. * **Zero bad debt history** — No SOL LST Multiply position has ever been liquidated. The liquidation penalty is approximately 0.1%, among the lowest in DeFi. The flash loan fee is 0.001% per transaction. This applies when opening, adjusting, or closing a position. # Risks Source: https://docs.kamino.com/products/multiply/risks Understanding liquidation, borrow rate, and strategy-specific risks in Multiply > [!WARNING] > > Multiply uses leverage. Leveraged positions amplify both gains and losses. Understand the risks specific to your strategy before opening a position — the risk profile of a SOL LST strategy differs fundamentally from a JLP or xStocks strategy. ## Borrow rate risk Borrow rate risk is universal across all Multiply strategies. Every Multiply position borrows at a variable rate. If that rate rises above the yield the collateral generates, [Net APY](/products/multiply/concepts#net-apy--the-fundamental-equation) turns negative and the debt balance grows faster than the collateral earns. ``` Net APY turns negative when: Borrow Rate > Collateral Asset Yield ``` For SOL LST strategies, this is the **only** meaningful risk vector — there is no price liquidation risk. For all other strategies, borrow rate risk compounds on top of price risk. High utilization in the borrowing pool drives rates up. The Jito Market (SOL) includes an interest rate cap mechanism that bounds rate spikes for JitoSOL/SOL strategies — this is a deliberate design choice to limit the primary risk for the highest-leverage LST product on the platform. *** ## Liquidation mechanics Liquidation is triggered when a position's Current [LTV](/products/multiply/concepts#the-leverage-ratio) exceeds its Liquidation LTV threshold. The threshold is strategy and market specific — for example, 80% on JLP Market, higher under [eMode](/products/multiply/concepts#emode-in-multiply) for LST strategies. At liquidation: * **Close factor:** Up to 10% of the position is liquidated per transaction * **Liquidation penalty:** \~0.1% (reduced 90% from \~1% in September 2025) * **Multiple rounds:** If LTV remains above threshold after the first liquidation, additional rounds follow automatically until the position is healthy > [!NOTE] > > The 0.1% liquidation penalty was intentionally set low to reduce the severity of each liquidation event. Positions do not lose large chunks of value in a single liquidation — but multiple rounds can still accumulate meaningful losses if the underlying condition (falling price or negative carry) is not resolved. *** ## Strategy-specific liquidation risk | Strategy | What triggers liquidation | Price risk | | - | - | - | | SOL LST | Borrow rate sustained above staking yield for an extended period | None — denominated in SOL on both sides | | JLP | JLP price decline relative to USD | High — crypto basket exposure | | xStocks | Underlying equity price decline | High — leveraged equity | | Stablecoin / RWA | Borrow rate exceeds RWA yield; RWA default or redemption freeze | Low — near-USD collateral | | Stable loops | Borrow rate spread inverts | None — both sides USD-pegged | *** ## Stake-rate oracle > [!NOTE] > > For [SOL LST](/products/multiply/concepts#liquid-staking-tokens-lsts) strategies, Kamino prices the LST collateral using the [stake pool exchange rate](/products/multiply/concepts#stake-rate-oracle-protection) — not the secondary market price. A temporary market depeg, where JitoSOL trades below its theoretical value, does not affect your LTV calculation. The oracle ignores market mispricing. This eliminates the historical failure mode for LST leverage strategies: a temporary depeg cascade that forces healthy positions into liquidation. It is a core protection mechanism for SOL LST Multiply. **Limitation:** The stake-rate oracle protects against market mispricing, not against fundamental failures. An exploit or insolvency in the underlying staking protocol would affect the exchange rate itself and would therefore be reflected in the LTV calculation. Users must independently evaluate the safety of LST issuers (Jito, Marinade, Blaze, etc.). *** ## Auto-deleveraging In extreme protocol stress scenarios, Kamino's Risk Council can initiate auto-deleveraging — a systematic reduction of the largest leveraged positions to protect overall solvency. > [!WARNING] > > Before auto-deleveraging is executed, affected positions receive a **72-hour warning**. Auto-deleveraging has not been triggered in Kamino's history. It is a last-resort mechanism, not a routine operation. Auto-deleveraging is distinct from normal liquidation. It is not triggered by individual position health — it is triggered by systemic risk to the lending protocol as a whole. *** ## Historical liquidation events | Date | Event | Collateral Seized | Bad Debt | | - | - | - | - | | April 6–7, 2025 | Broad market correction | \$16M | \$0 | | February 5–6, 2026 | SOL -18%, ETH -15% crash | \$19.4M | \$0 | SOL LST Multiply positions accounted for a negligible share of liquidations in both events. JLP Multiply positions were among those liquidated in both. The protocol produced zero bad debt in both cases — liquidations executed before positions became insolvent. *** ## Liquidation analysis tools Kamino provides a Liquidation Analysis Suite accessible from the Multiply interface. It allows you to model position health before and after opening leverage. * Simulate time-to-liquidation under different market conditions and borrow rate scenarios * Adjust leverage and theoretical yield to see break-even thresholds * Run historical backtests on strategy performance across past market events Use these tools before entering any leveraged position, particularly for JLP and xStocks strategies where price risk is the dominant variable. *** ## Risk summary | Strategy | SOL Price Risk | Depeg Risk | Borrow Rate Risk | RWA / Counterparty Risk | | - | - | - | - | - | | SOL LST | None | Eliminated (stake oracle) | Primary risk | None | | JLP | High | N/A | Moderate | None | | xStocks | High (equity) | N/A | Moderate | None | | Stablecoin / RWA | Low | N/A | Moderate | Varies by issuer | | Stable loops | None | N/A | Primary risk | None | # Strategies Source: https://docs.kamino.com/products/multiply/strategies SOL LSTs, JLP, stablecoins, RWAs, and tokenized stocks — Multiply strategy types and their mechanics Multiply supports four distinct strategy categories, each with different yield sources, leverage limits, and risk profiles. The right strategy depends on your yield target, risk tolerance, and market view. ## SOL LST strategies > [!NOTE] > > [SOL LST](/products/multiply/concepts#liquid-staking-tokens-lsts) strategies are the only Multiply strategies where SOL price movements have zero impact on position health. Both collateral and debt are denominated in SOL — the position gains or loses based entirely on the spread between staking yield and borrow rate. See [The SOL-denominated advantage](/products/multiply/concepts#the-sol-denominated-advantage-lst-looping) for the full explanation. **Collateral assets:** JitoSOL, mSOL, bSOL, JupSOL, dfdvSOL, adraSOL\ **Debt asset:** SOL\ **Yield source:** Liquid staking rewards (Solana Proof-of-Stake yield) Because both sides of the position are denominated in SOL, SOL price volatility does not affect the LTV ratio or liquidation risk. You hold an LST against SOL debt — if SOL falls 50%, both your collateral value and your debt value fall by the same amount. | Market | Assets | Max Leverage | Notes | | - | - | - | - | | Jito Market | JitoSOL | 10x | Isolated market, 90% LTV eMode, SOL IR cap | | SOL/BTC Market | mSOL, bSOL, JupSOL, dfdvSOL, adraSOL | 7.5x | eMode elevation groups | Zero liquidations have occurred on SOL LST Multiply positions as of March 2026. See [How It Works](/products/multiply/how-it-works) for stake-rate oracle details. **Primary risk:** Sustained high SOL borrow rates exceeding LST staking yield. When `Borrow Rate > Staking Yield`, [Net APY](/products/multiply/concepts#net-apy--the-fundamental-equation) turns negative and debt grows relative to collateral. This is the only meaningful risk vector for these strategies under normal conditions. *** ## JLP strategies **Collateral:** [JLP](/products/multiply/concepts#jlp--what-it-is-and-why-the-risk-profile-differs) (Jupiter Liquidity Provider token)\ **Debt asset:** USDC, PYUSD, or USDG\ **Yield source:** Trading fees from Jupiter perpetuals platform\ **Max leverage:** \~3.2x (JLP Market, 67% LTV, Liquidation LTV 80%) JLP is a basket token holding SOL, ETH, BTC, USDC, and USDT — approximately 65% crypto-native assets and 35% stablecoins. Leverage amplifies both the fee yield and the directional exposure to crypto prices. Unlike SOL LST strategies, JLP Multiply carries direct market risk: if JLP falls in USD terms, the position approaches liquidation. > [!WARNING] > > JLP Multiply positions were among those liquidated in both the April 2025 and February 2026 market corrections. JLP is not price-pegged — treat this as a leveraged crypto position that also earns trading fees, not a yield-only strategy. The \~35% stablecoin component provides partial downside buffer. [eMode](/products/multiply/concepts#emode-in-multiply) is not applied — JLP does not qualify as a correlated asset against USDC debt. **Available vaults:** JLP/USDC, JLP/PYUSD, JLP/USDG *** ## Stablecoin and RWA strategies These strategies loop a yield-bearing stablecoin or real-world asset token against stablecoin debt. The goal is leveraged yield with minimal directional exposure to crypto prices. | Strategy | Yield Source | Approx Base APY | Max Leverage | | - | - | - | - | | [SyrupUSDC](/products/multiply/concepts#rwa-tokens--real-world-yield-on-leverage) / USDC | Maple Finance institutional credit | \~5–6% | 4–5x | | [PRIME](/products/multiply/concepts#rwa-tokens--real-world-yield-on-leverage) / PYUSD | US home equity loans (Figure Finance) | \~8% | 8.3x | | [ONyc](/products/multiply/concepts#rwa-tokens--real-world-yield-on-leverage) | Reinsurance-backed yield (OnRe) | \~16% | Varies | > [!NOTE] > > RWA strategies carry risks that are absent from crypto-native strategies: counterparty risk, default risk on the underlying loan pool, and redemption liquidity constraints. The collateral may not be liquidatable as rapidly as on-chain assets in a stress scenario. Borrow rate risk applies here as with all Multiply strategies — if the cost to borrow USDC exceeds the RWA yield, the net position is negative-carry. These strategies are not immune to liquidation if borrow rates spike sharply. *** ## xStocks strategies **Collateral:** Tokenized stocks (xStocks)\ **Debt asset:** USDC\ **Available assets:** APPLx, GOOGLx, HOODx, MSTRx, NVDAx, QQQx, SPYx, TSLAx\ **Max leverage:** Up to 3.7x xStocks Multiply provides leveraged exposure to tokenized equity prices settled on-chain. This is a purely directional strategy — if the underlying stock price falls, the position can be liquidated. There is no yield-bearing component offsetting the borrow cost; the entire thesis is price appreciation of the underlying equity. > [!WARNING] > > xStocks strategies carry equity market risk amplified by leverage, plus USDC borrow rate risk as an ongoing cost. These positions are not appropriate if you are seeking yield — they are a leveraged long on individual equities or indices. *** ## Stable loops Stablecoin-to-stablecoin looping strategies pair a yield-bearing stablecoin as collateral against a standard stablecoin as debt. When both sides are pegged to USD, leverage multiplies the yield spread with minimal directional price risk. **Example:** CASH/PYUSD — up to 10x leverage on the spread between CASH yield and PYUSD borrow rate. > [!TIP] > > Stable loops offer the highest available leverage multiples on Multiply precisely because the correlated collateral and debt eliminate price liquidation risk. The primary and often only risk is borrow rate volatility compressing or inverting the yield spread. *** ## Strategy comparison | Strategy | SOL Price Risk | Market Liquidation Risk | Primary Risk | Max Leverage | | - | - | - | - | - | | SOL LST | None | None | Borrow rate | 10x | | JLP | High | Yes | Price + borrow rate | \~3.2x | | Stablecoin / RWA | Low | Low | Borrow rate + RWA default | 8.3x | | xStocks | High (equity) | Yes | Price + borrow rate | 3.7x | | Stable loops | None | None | Borrow rate spread | 10x | # Swap Source: https://docs.kamino.com/products/swap/index How Kamino Swap routes trades across 15+ venues based on your specified parameters Kamino Swap is a meta-aggregator that queries multiple routing engines in parallel and returns the highest output quote across all integrated routing engines for any token pair. It charges no platform fees. The same routing layer powers swaps across the full Kamino product suite — Multiply leverage, Repay with Collateral, and single-asset deposits on Lending Vaults. > [card] [Limit Orders](/products/swap/limit-orders) > > Standing orders that execute when the market reaches your price, with zero slippage and zero fees. ## How routing works When a swap is initiated, Kamino queries 15+ routing engines concurrently. Each returns a quote and a ready-to-execute transaction. Kamino compares all quotes and selects the highest output. Integrations include: Jupiter/Metis, DFlow, OKX, Settler (0x), LI.FI, OpenOcean, Titan, Kinetic, Raydium, Hashflow, Cabana Wave (Spur), and others. Route selection varies by pair and size — DFlow, Jupiter/Metis, and OKX handle the majority of volume, but any router can win when it returns a higher output quote. ## Active Simulation Standard DEX interfaces display optimistic quotes that don't account for real-time on-chain conditions. Kamino's Active Simulation Mechanism (ASM) runs the transaction through an on-chain simulation before presenting the quote, verifying the actual output rather than relying on the routing engine's estimate. Active simulation runs in three phases: * **Refresh simulation** — instant accuracy check when quotes are first fetched * **Mid-quote simulation** — after 2.5 seconds, outdated routes are filtered out * **On-swap simulation** — final verification at the moment of execution This produces a `simulatedAmountOut` rather than an optimistic `quotedAmountOut`. Measured over 370,000+ transactions, ASM achieves 99.944% mean accuracy between expected and actual output. Active Simulation can be toggled on or off on the swap interface. ## Price impact vs. slippage These two terms affect your output in different ways and are commonly confused. **Price impact** is the effect your trade has on the market price. When you buy a large quantity of a token, you consume liquidity from pools at progressively worse rates — the larger the trade relative to available liquidity, the higher the impact. Price impact is calculated before execution and displayed as a percentage. Kamino shows a warning at ≥1% and an error at ≥5%. **Slippage** is the difference between the quoted price and the actual execution price, caused by market movement between the moment you receive your quote and the moment your transaction lands. It is unpredictable. Max slippage tolerance is a safety net: if the price moves beyond your configured tolerance before the transaction executes, the transaction reverts. Setting slippage too low causes more transaction failures in volatile markets. Setting it too high means accepting potentially worse prices. The minimum output shown on the swap interface accounts for both — it is the quoted output after price impact minus the max slippage tolerance. > [!NOTE] > > **Worked example: Swap 10,000 USDC → SOL at \~\$150/SOL** > > * **Price impact: 0.5%** — your trade moves the pool, giving you \~66.33 SOL instead of 66.67 > * **Max slippage: 50 bps (0.5%)** — protects against further price movement during execution > * **Minimum output: \~66.00 SOL** — if execution would return less than this, the transaction reverts ## No platform fees Kamino Swap charges no platform fees. Costs are limited to on-chain transaction fees (SOL gas) and any spread embedded in the route by the underlying DEXes or aggregators — these are third-party costs outside Kamino's control and are not charged by Kamino. For comparison: Jupiter's "Ultra" mode charges 0.1% on most pairs — Kamino charges zero. ## Integration across Kamino Kamino Swap is also the execution layer for: * **Multiply** — all flash loan swaps for opening, adjusting, and closing leveraged positions * **Repay with Collateral** — collateral → debt asset conversion on Kamino Lend * **Lending Vaults** — single-asset deposits/withdrawals (converts to the required pair) *** ## Disclaimer Use of Kamino Swap is subject to Kamino's Terms and Conditions and geo-blocking policy, which restrict access for users in the United States, the United Kingdom, and other restricted jurisdictions. By accessing or using Kamino Swap, you confirm that you are not located in a restricted jurisdiction and that your use complies with all laws and regulations applicable to you. Kamino Swap is a non-custodial interface that prepares and broadcasts transactions based solely on the parameters you set. Kamino does not place orders on your behalf, exercise any discretion over your transactions, or hold your assets at any point. This documentation does not constitute financial, investment, legal, or tax advice. # Limit Orders Source: https://docs.kamino.com/products/swap/limit-orders Place standing orders that execute at your target price — zero slippage, zero fees Kamino Limit Orders (LIMO) are standing orders that execute when the market reaches a target price. Unlike market swaps, limit orders guarantee execution at your specified rate — there is no slippage on fill. They charge no platform fees. ## How limit orders work **1. Select tokens** Choose the input token and output token for your order. **2. Set the rate** Enter the minimum output amount per input token. By default, orders are placed at ±0.1% from mid-price for efficient fills. You can set any price: below the current market rate or above it, depending on your intended execution parameters. **3. Place the order** Confirm the transaction. The input token is escrowed on-chain until the order fills or is cancelled. **4. Order fills** When the market reaches your rate, the order executes. Partial fills are possible — an order can fill incrementally as liquidity becomes available. **5. Claim the output** Filled tokens and any tips accumulate until you claim. Open the order and select "Close Order & Claim Tip" to receive your output. ## Tips and surplus Two benefits unique to Kamino Limit Orders: * **Tips** — SOL payments made directly to you when your order fills. They are generated by searchers competing to fill your order via auction: the winning searcher pays a tip to you as part of the execution. * **Surplus** — If execution produces more output than your specified minimum rate, the surplus goes directly to you. Orders fill at the available execution price, which may exceed your specified minimum rate. Cumulative tips and surplus returned to traders: nearly \$98.5K across the first \$200M in limit order volume. ## Order statuses | Status | Description | | - | - | | In Progress | Unfilled or partially filled; waiting for execution | | Cancelled | Manually closed before any fills | | Filled | Fully filled, or closed after a partial fill | ## Order management Open orders appear in the My Overview dashboard and can be cancelled at any time before filling. Cancelling an unfilled order returns the escrowed input tokens to your wallet. Partially filled orders that are closed return the remaining unfilled input tokens and release the filled output. Tips accumulate per order and are claimed via "Close Order & Claim Tip" once the order is complete. ## Comparison to market swaps | | Market Swap | Limit Order | | - | - | - | | Execution | Immediate, at the execution price determined by the routing auction | When market reaches your target price | | Slippage | Possible (set max tolerance) | None — fills at your rate or better | | Price impact | Applies to large trades | Does not apply | | Platform fee | None | None | | Tips/surplus | No | Yes | Limit orders can be used in conjunction with other Kamino products. Output tokens from a filled limit order can be deployed across the Kamino product suite, including Multiply and Lending. > [!TIP] > > Limit orders pair well with Multiply positions. If you want to open a leveraged position only when a token reaches a certain price, place a limit order first and use the proceeds to open your Multiply position. *** ## Disclaimer Use of Kamino Limit Orders is subject to Kamino's Terms and Conditions and geo-blocking policy, which restrict access for users in the United States, the United Kingdom, and other restricted jurisdictions. By accessing or using Kamino Limit Orders, you confirm that you are not located in a restricted jurisdiction and that your use complies with all laws and regulations applicable to you. Kamino Limit Orders is a non-custodial interface that prepares and broadcasts transactions based solely on the parameters you set. Kamino does not place orders on your behalf, exercise any discretion over your transactions, or hold your assets at any point. This documentation does not constitute financial, investment, legal, or tax advice. # Brand Resources Source: https://docs.kamino.com/resources/brand/index Official Kamino brand assets for partners, press, and collaborators. Download logos, wordmarks, icons, and brand guidelines to represent Kamino consistently across any medium. # Brand Resources Official assets for partners, press, and collaborators. Use these resources to represent Kamino consistently across any medium. V1.1 ## Wordmark Wordmark Black ![Kamino Wordmark Black](https://mintcdn.com/kamino-3d73a151/2usMx_FT_aSvQ2zr/images/resources/brand/wordmark-black.svg?fit=max\&auto=format\&n=2usMx_FT_aSvQ2zr\&q=85\&s=54c6b52827829218e386109b1abf09a8) Copy SVG Copy PNG Wordmark White ![Kamino Wordmark White](https://mintcdn.com/kamino-3d73a151/2usMx_FT_aSvQ2zr/images/resources/brand/wordmark-white.svg?fit=max\&auto=format\&n=2usMx_FT_aSvQ2zr\&q=85\&s=b2f8ef7ebac442c47dc20a6582580850) Copy SVG Copy PNG ## Mark / Icon Icon Black ![Kamino Icon Black](https://mintcdn.com/kamino-3d73a151/2usMx_FT_aSvQ2zr/images/resources/brand/icon-black.svg?fit=max\&auto=format\&n=2usMx_FT_aSvQ2zr\&q=85\&s=5e7523238c64383b3eda1af130303022) Copy SVG Copy PNG Icon White ![Kamino Icon White](https://mintcdn.com/kamino-3d73a151/2usMx_FT_aSvQ2zr/images/resources/brand/icon-white.svg?fit=max\&auto=format\&n=2usMx_FT_aSvQ2zr\&q=85\&s=9a1642f1a68c0f40f2c234467c476e85) Copy SVG Copy PNG ## Token Icon KMNO Token / Primary ![KMNO Token Primary](https://mintcdn.com/kamino-3d73a151/2usMx_FT_aSvQ2zr/images/resources/brand/token-primary.svg?fit=max\&auto=format\&n=2usMx_FT_aSvQ2zr\&q=85\&s=3ead989bb9c7748d6ef51e032ae1ea15) Copy SVG Copy PNG Light Version ![KMNO Token Light](https://mintcdn.com/kamino-3d73a151/2usMx_FT_aSvQ2zr/images/resources/brand/token-light.svg?fit=max\&auto=format\&n=2usMx_FT_aSvQ2zr\&q=85\&s=dee4db2ab8db4a6ee4fa7d7e4e8d3bf4) Copy SVG Copy PNG ## Color Palette ### Paper Backgrounds `#FCFCFC` Copy HEX ### Kamino Blue Backgrounds / Highlights `#C6F4FF` Copy HEX ### Black Backgrounds / Text `#000000` Copy HEX ![Kamino](https://mintcdn.com/kamino-3d73a151/2usMx_FT_aSvQ2zr/images/resources/brand/wordmark-black.svg?fit=max\&auto=format\&n=2usMx_FT_aSvQ2zr\&q=85\&s=54c6b52827829218e386109b1abf09a8) The content on this website is provided "as-is" and should not be considered legal, tax, investment, financial, or other professional advice. Users assume all risk in relying on this information, and Kamino disclaims all liability for any loss or damage resulting from such reliance. Kamino makes no representations or warranties regarding the accuracy, completeness, or reliability of the content and reserves the right to update or modify it at any time. © 2026 Kamino Finance. All rights reserved. # Counterparty Risk Source: https://docs.kamino.com/risk/asset-risk/counterparty How governance decentralization, holder concentration, and trust assumptions are evaluated Counterparty risk is a qualitative governance evaluation — it asks how much trust is required in the entities that control a token's protocol, and what happens if that trust is violated. A fully decentralized protocol with no admin keys requires zero trust in any single entity. A token controlled by a single company with a single-signer upgrade authority requires maximum trust. Most tokens fall somewhere in between. The counterparty risk assessment maps this spectrum to protocol parameters. ## Why Counterparty Risk Matters A token's value can go to zero if the entity controlling it acts maliciously, becomes insolvent, or makes a catastrophic governance decision. Unlike smart contract risk (where the threat is a code bug) or market risk (where the threat is price volatility), counterparty risk is about human decisions and organizational integrity. Historical examples: * **Algorithmic stablecoin failures:** UST/LUNA collapsed in May 2022 when the algorithmic peg mechanism failed and governance could not respond quickly enough — erasing \$40B in value. * **Centralized token rugs:** Tokens where a single entity controls minting or upgrade authority have been exploited when that entity acts maliciously or is compromised. * **Governance attacks:** Protocols with concentrated token holdings have experienced hostile governance proposals that redirect treasury funds or modify critical parameters. For a lending protocol, counterparty risk translates directly to collateral risk. If Kamino accepts a token as collateral and the governing entity behind that token acts in a way that destroys its value, every loan backed by that collateral is at risk of bad debt. ## Evaluation Dimensions ### Degree of Decentralization The assessment maps each token's governance on a centralization spectrum: | Level | Structure | Trust Required | | - | - | - | | **Fully decentralized** | No admin keys, immutable contracts, on-chain governance only | None | | **DAO-governed** | Multisig or on-chain voting controls upgrades, timelock delays | Low — trust the governance process | | **Multisig-controlled** | Small group (e.g., 3-of-5) holds upgrade/mint authority | Medium — trust the signers | | **Single entity** | One company or individual controls key functions | High — trust that entity completely | The key question is: *who can change the rules, and how quickly?* A 7-of-12 multisig with a 72-hour timelock provides meaningful protection — even if the multisig holders are compromised, the timelock gives the community time to react. A single-signer authority with no delay provides no protection at all. ### Number of Controlling Parties Beyond the governance structure, the assessment considers how many independent parties participate in governance decisions. A 3-of-5 multisig where all 5 signers work at the same company is effectively single-entity control. A 3-of-5 multisig with signers from independent organizations is genuinely distributed. ### Token Holder Distribution Concentrated token holdings create manipulation and dump risk: * **Whale concentration:** If a small number of wallets hold a large percentage of the token supply, those wallets can influence price through large sales, or control governance through voting power. * **Vesting and unlock schedules:** Large upcoming token unlocks can create selling pressure. The assessment considers how much of the total supply is locked, when unlocks occur, and whether unlock events could meaningfully affect liquidity. * **Team and investor allocations:** What percentage of the supply is held by the founding team and early investors? Are there lockup restrictions? A token where the top 10 wallets hold 80% of the circulating supply has fundamentally different counterparty risk than one where the top 10 wallets hold 15%. ### Entity Track Record The assessment evaluates the reputation, track record, and regulatory standing of the entity or community governing the token: * **Operating history:** How long has the entity been operating? Has it honored commitments? * **Transparency:** Does it publish regular reports? Are its operations verifiable? * **Regulatory standing:** Is the entity operating within applicable regulatory frameworks? Has it faced enforcement actions? * **Incident response:** If past issues occurred, how were they handled? Prompt, transparent response builds confidence; silence or obfuscation reduces it. ## The Centralization Spectrum — Examples ### Low Counterparty Risk A native blockchain token like SOL has minimal counterparty risk in the governance sense — there is no single entity that can mint new SOL, freeze accounts, or modify the token's behavior. Governance of the Solana network is distributed across thousands of validators. While the Solana Foundation has influence, it does not have unilateral control over the token. Similarly, well-established stablecoins from regulated entities with public reserve attestations, multisig governance, and long operating histories score well on counterparty risk — the required trust is backed by institutional accountability. ### Medium Counterparty Risk A liquid staking token from an established DeFi protocol with a well-structured multisig, public team, and 12+ months of operation represents moderate counterparty risk. The protocol team controls upgrades, but the multisig structure, timelock, and public accountability provide meaningful safeguards. ### High Counterparty Risk A new token from an anonymous team with a single-signer upgrade authority, concentrated holdings, and no operating history represents high counterparty risk. Even if the smart contract is audited and the market liquidity is adequate, the governance structure means a single point of failure exists. ## How Counterparty Risk Maps to Parameters Tokens with higher counterparty risk receive: * **Lower Max LTV:** Larger buffer between collateral value and liquidation threshold, accounting for the possibility of sudden governance-related value loss * **Higher Borrow Factors:** The protocol treats debt in high-counterparty-risk tokens as riskier than its face value * **Supply and borrow caps:** Limit total protocol exposure to any single token with elevated counterparty risk * **Potential isolation mode:** Tokens with the highest counterparty risk may be restricted to [isolated collateral](/risk/asset-risk#isolated-collateral) or [isolated debt](/risk/asset-risk#isolated-debt) mode, ring-fencing them from affecting other positions ## Ongoing Assessment Counterparty risk is inherently dynamic. Governance structures change, team members leave, regulatory environments shift, and token distributions evolve over time. The risk framework monitors: * Governance proposals and execution (particularly those affecting upgrade authority or minting) * Changes in token holder distribution (whale accumulation or distribution events) * Regulatory developments affecting listed token issuers * Team and organizational changes at token-governing entities Material changes trigger reassessment and potential parameter adjustments. A token that was low-risk at listing may become higher-risk if its governance becomes more centralized, or vice versa. # Depeg Risk Source: https://docs.kamino.com/risk/asset-risk/depeg How depegging risk is evaluated for stablecoins, liquid staking tokens, and wrapped assets A depeg event occurs when a pegged asset's price becomes substantially detached from its intended peg. A stablecoin that should trade at \$1.00 drops to \$0.90. A liquid staking token that should track the SOL stake rate trades at a persistent discount. A wrapped token that should be redeemable 1:1 for the underlying asset loses that guarantee. Depeg risk is particularly consequential for Kamino because of how the protocol handles pegged asset pairs. ## Why Depeg Risk is Elevated on Kamino Kamino's [E-Mode mechanism](/risk/safeguards/e-mode-caps) allows higher loan-to-value ratios for pegged asset pairs. For example, a position borrowing USDT against USDC collateral can achieve a much higher LTV than a position borrowing USDC against SOL — because two USD stablecoins are expected to maintain their pegs and therefore have minimal relative price movement. This design is economically efficient under normal conditions. But if a depeg occurs, these high-LTV positions are at elevated liquidation risk. The margin between collateral value and liquidation threshold is thin by design — a depeg erodes that margin quickly. A 5% depeg on a standard cross-margin position with 75% LTV leaves substantial buffer. The same 5% depeg on an E-Mode position with 95% LTV may immediately breach the liquidation threshold. ## Asset Types Affected ### USD Stablecoins Stablecoins like USDC, USDT, and PYUSD maintain their peg through reserve backing — each token is redeemable for \$1.00 worth of reserves (cash, treasuries, or equivalent). Depeg risk arises when: * **Reserve adequacy is questioned.** If the market suspects that reserves are insufficient to redeem all outstanding tokens, confidence drops and the token trades below \$1.00. * **Counterparty failure.** If the entity holding reserves experiences financial distress — as when USDC depegged to \$0.90 in March 2023 after Silicon Valley Bank's collapse exposed \$3.3B of Circle's reserves — the token can depeg rapidly. * **Regulatory action.** Freezing or seizing reserves can impair redeemability. ### Liquid Staking Tokens LSTs like JitoSOL, mSOL, and bSOL are pegged to SOL via the stake rate — the ratio of SOL staked to LST tokens minted. Depeg can occur from: * **Market liquidity imbalances.** Large sell orders on DEXes can temporarily push the market price below the theoretical stake-rate price. This is a market depeg — the underlying backing is intact. * **Smart contract exploits.** If the staking vault is compromised and SOL is drained, the stake rate itself drops. This is a fundamental depeg — the backing is genuinely impaired. * **Unstaking delays.** Solana staking has epoch-based delays (\~2 days). During volatile periods, the inability to instantly redeem LSTs for SOL can cause market price dislocations. Kamino mitigates market depegs for LSTs through [stake-rate oracle pricing](/security/oracles/lst-oracles) — the protocol values LSTs at their stake rate, not their market price. This eliminates liquidations triggered by temporary market noise but does not protect against fundamental depegs caused by smart contract exploits. ### Wrapped and Bridged Tokens Wrapped tokens (e.g., bridged assets from Ethereum) maintain their peg through the bridge contract — each wrapped token is backed by a locked token on the source chain. Bridge exploits (e.g., Wormhole's \$320M exploit in 2022) can break this peg entirely, as wrapped tokens become unbacked. ## Causes of Depeg Events | Cause | Mechanism | Severity | | - | - | - | | **Reserve depletion** | Issuer's reserves are insufficient to honor redemptions | High — can be permanent | | **Smart contract exploit** | Backing assets drained from vault or bridge | Critical — instant and total | | **Counterparty insolvency** | Entity managing reserves fails | High — recovery uncertain | | **Confidence crisis** | Market participants sell preemptively, even if reserves are adequate | Medium — typically temporary | | **Liquidity imbalance** | Large sell order in thin DEX pool | Low — temporary, arbitrageurs restore | ## How Kamino Evaluates Depeg Risk The assessment considers: ### Reserve Backing Quality For stablecoins: What are the reserves composed of? Cash and short-duration treasuries are lower risk than commercial paper, crypto-backed reserves, or algorithmic mechanisms. How frequently are reserves attested? Are attestations from independent third parties? For LSTs: What is the stake pool structure? How many validators? Is the smart contract audited and battle-tested? ### Smart Contract Exposure Does the peg mechanism depend on a smart contract? Has that contract been audited? How much value has it secured? A stablecoin backed by reserves in a traditional bank has different (lower) smart contract risk than an LST backed by a Solana staking vault, which in turn has different risk than an algorithmic stablecoin backed entirely by code. ### Historical Stability Has the asset depegged before? How severe was the depeg? How quickly did it recover? USDC's March 2023 depeg to \$0.90 — caused by external banking sector stress, not a protocol failure — recovered within 48 hours after the Fed backstopped SVB. This suggests robust recovery mechanisms. An asset that has experienced a fundamental depeg (backing drained) and not fully recovered presents much higher ongoing risk. ### Arbitrage and Redemption Mechanisms How quickly can the peg be restored? Direct redemption mechanisms (e.g., redeeming USDC for \$1.00 from Circle) provide a hard floor. LSTs can be unstaked for SOL at the stake rate, providing an arbitrage mechanism. Tokens without direct redemption mechanisms rely entirely on market forces to maintain the peg — which may fail under stress. ## How Depeg Risk Maps to Parameters | Depeg Risk | Protocol Response | | - | - | | **Low** (strong reserves, audited, battle-tested, direct redemption) | E-Mode eligible, higher LTV for pegged pairs | | **Medium** (adequate reserves, limited history, indirect redemption) | Lower E-Mode LTV, tighter caps | | **High** (unproven reserves, new contract, no direct redemption) | No E-Mode eligibility, standard LTV, potential isolation | ## Mitigation Mechanisms * **[LST stake-rate oracles](/security/oracles/lst-oracles):** Remove market depeg liquidation risk for liquid staking tokens * **[Price bands](/security/oracles/price-protection#price-bands):** Reject stablecoin prices outside expected range, preventing flash-crash exploits * **[E-Mode caps](/risk/safeguards/e-mode-caps):** Limit total exposure in high-LTV pegged-pair positions * **Supply caps:** Bound total protocol exposure to any single pegged asset * **Active monitoring:** Continuous tracking of peg stability, reserve attestations, and on-chain redemption activity Depeg risk is reassessed whenever a material event occurs — a reserve attestation reveals composition changes, a smart contract exploit affects a related protocol, or market conditions produce sustained price deviation from the peg. # Assessment Framework Source: https://docs.kamino.com/risk/asset-risk/index The 5-dimension asset risk assessment used for token onboarding and ongoing risk review Before any token can be listed on Kamino — whether as collateral, as a borrowable asset, or both — it undergoes a structured risk assessment across five dimensions. This framework is used at the onboarding stage and applied on an ongoing basis as market conditions evolve. The purpose is straightforward: determine how much risk each asset introduces to the protocol, and set parameters accordingly. ## The Five Risk Dimensions Each dimension evaluates a distinct axis of risk. Together, they provide a comprehensive picture of whether an asset can be safely integrated into the lending protocol. | Dimension | Core Question | Detail | | - | - | - | | [Oracle Pricing Risk](/risk/asset-risk/oracle-pricing) | How reliable is the price feed? | Number and quality of oracle sources, uptime, staleness | | [Smart Contract Risk](/risk/asset-risk/smart-contract) | How robust is the token's underlying code? | Audit history, maturity, battle-testing, bug bounty | | [Depeg Risk](/risk/asset-risk/depeg) | Could this pegged asset lose its peg? | Reserve backing, smart contract exposure, historical stability | | [Counterparty Risk](/risk/asset-risk/counterparty) | Who controls this token and how much trust is required? | Governance decentralization, holder concentration, entity track record | | [Market Risk](/risk/market-risk) | Can liquidations execute profitably? | Volatility, liquidity, price impact, trading volumes | ## Asset Tiering The assessment maps directly to how each asset can be used on the protocol. Every token is classified into one of three tiers: ### General Asset The token passes all five dimensions at acceptable thresholds. It can be used as collateral and borrowed in cross-margin mode, with standard LTV limits. Most major tokens (SOL, USDC, USDT, JitoSOL) fall into this tier. ### Isolated Collateral The token has elevated risk in one or more dimensions — perhaps limited oracle coverage, a newer smart contract without extensive battle-testing, or thin market liquidity. It can be used as collateral, but only in isolated mode: the user's position with this collateral is ring-fenced from their other positions. This prevents a problem with a high-risk collateral token from cascading into other positions. ### Isolated Debt The token has elevated borrowing risk — perhaps high volatility, limited liquidity for liquidators, or a new and unproven market. It can be borrowed, but only in isolated mode with strict caps. ## Parameter Derivation The assessment directly determines two key protocol parameters for each asset: ### Collateral Max LTV The maximum loan-to-value ratio allowed when using this token as collateral. A token assessed as low-risk across all dimensions might receive a Max LTV of 80–85%. A higher-risk token might receive 50–65%, or be restricted to isolated mode entirely. Max LTV is calibrated conservatively — it must leave enough margin for the collateral value to decline before reaching the liquidation threshold, accounting for the asset's measured volatility and the time needed for liquidators to execute. ### Borrow Factor A risk weight applied to the debt side. A Borrow Factor above 1.0 means the protocol treats the debt as riskier than its face value — effectively requiring more collateral to borrow that asset. Volatile or illiquid tokens receive higher Borrow Factors, while stablecoins and well-established tokens receive factors close to 1.0. ## Ongoing Reassessment Onboarding is not a one-time gate. The framework is applied continuously: * **Market-driven reassessment:** If an asset's liquidity drops significantly, its volatility spikes, or its oracle coverage narrows, the risk profile changes. Parameters are adjusted accordingly — LTV limits may be lowered, caps may be reduced, or the asset may be moved to isolated mode. * **Event-driven reassessment:** A smart contract exploit on a listed token's underlying protocol, a governance incident, or a depeg event triggers immediate review and potential parameter changes. * **Periodic review:** The Risk Council reviews all listed assets periodically, incorporating the latest [KRAF dashboard](/risk/kraf-dashboard) data, monthly risk reports, and market conditions. The goal is to ensure that the parameters governing each asset always reflect its current risk profile, not its risk profile at the time of onboarding. # Oracle Pricing Risk Source: https://docs.kamino.com/risk/asset-risk/oracle-pricing How oracle quality and reliability are evaluated as part of the asset risk framework Oracle pricing risk is the risk that the price feed used for a given asset on Kamino is inaccurate, stale, or manipulable. Since every lending decision — collateral valuation, liquidation triggering, interest rate calculation — depends on oracle prices, the quality of the price feed is foundational to protocol safety. An asset with a single, low-frequency price feed from one provider carries fundamentally more oracle risk than an asset with multiple high-frequency feeds from independent providers. The oracle pricing risk assessment quantifies this difference and maps it directly to protocol parameters. ## Multi-Price Oracle System Kamino's most significant oracle architecture upgrade — the **Multi-Price Oracle System** — represents a fundamental shift in how the protocol sources and validates price data. Rather than selecting a single "best" price from one provider at any moment, the system aggregates pricing from all available high-quality oracle sources and continuously cross-validates them against each other in real time. > [card] No Single Point of Failure > > Complete elimination of dependence on any individual data provider > [card] Dynamic Price Selection > > Automatically selects the freshest valid price across all providers at the moment of each transaction > [card] Self-Healing > > Automatic fallback during provider downtime or price deviation — no manual intervention required The system was double-audited by **Certora** and **Offside Labs** before deployment. ### Chainlink Data Streams A key component of the Multi-Price Oracle System is the integration of **Chainlink Data Streams** — a pull-based, low-latency data delivery model from the industry's most established oracle network. Unlike traditional push-based oracle feeds that update on fixed heartbeat intervals (and may be stale between heartbeats), Chainlink Data Streams deliver high-frequency market data that can be requested on-demand. This means the protocol can access the freshest available price at the exact moment it needs it — during liquidation checks, collateral valuations, and position adjustments. Chainlink serves as Kamino's primary oracle provider for Real World Asset (RWA) data, delivering the high uptime and reliability required for continuous 24/7 operations. Before deployment, Chainlink Data Streams underwent extensive testing in Kamino's mainnet testing environment for multiple weeks, running against existing price feeds. The testing demonstrated consistently strong results in both accuracy and latency, providing confidence for full production integration. > [!NOTE] > > For a detailed look at how Scope aggregates and validates prices from all providers including Chainlink Data Streams, see [Scope Aggregator](/security/oracles). ## Evaluation Dimensions ### Number of Price Sources Independent, cross-validated price feeds reduce oracle risk: if one feed goes stale, deviates, or is manipulated, the other continues to provide an accurate price and Scope flags the divergence. Kamino's [Scope oracle aggregator](/security/oracles) cross-validates Chainlink and Pyth Pro, but coverage varies by asset. Major assets like SOL and USDC are covered by both Chainlink and Pyth Pro, with deep liquidity and full cross-validation. A newer or less liquid token may be supported by only one feed, or by feeds with thinner underlying liquidity. Less coverage means less cross-validation and higher oracle pricing risk. ### Types of Price Sources Not all oracle feeds are equal. The assessment distinguishes between: * **Decentralized oracle networks** (Chainlink, Pyth Pro): many independent data providers aggregate prices, making manipulation extremely difficult. These are the highest-quality feeds. * **Derived on-chain prices** (AMM-derived, LST exchange rates): computed from on-chain data. Generally reliable, but can be affected by on-chain liquidity dynamics. * **Centralized feeds**: prices from a single provider or a small number of sources. Higher trust assumptions, higher risk. An asset priced exclusively through centralized feeds receives a lower oracle quality score than one priced through multiple decentralized networks. ### Uptime and Freshness Oracle feeds must update frequently enough that the price used by the protocol reflects current market conditions. A stale price — one that hasn't updated for minutes during a volatile market — can cause the protocol to value collateral at an outdated price, delaying necessary liquidations. The assessment evaluates: * **Update frequency:** Both Chainlink Data Streams and Pyth Pro are pull-based, delivering sub-second prices on demand rather than on fixed heartbeat intervals. * **Historical uptime:** Has the feed experienced outages? How long were they? What was the market impact? * **Staleness thresholds:** Scope enforces staleness checks — if a feed hasn't updated within a configured interval, it's flagged and alternatives are used. ### Historical Accuracy The assessment reviews whether the oracle has historically reported prices that align with actual market conditions. Persistent deviation between oracle-reported prices and verifiable market prices indicates feed quality issues. Cross-provider deviation is particularly informative: if Provider A consistently reports prices 0.5% different from Providers B and C, that pattern indicates a systematic issue with Provider A's data sources or aggregation methodology. ## How Kamino Mitigates Oracle Pricing Risk Beyond the assessment, Kamino's oracle infrastructure applies several layers of protection to every price feed: ### Heuristic Validation Rules Scope applies pre-validation rules before accepting any price update. These rules check for obvious anomalies — prices that are orders of magnitude different from the previous update, negative prices, or updates that arrive out of sequence. ### TWAP and EWMA Smoothing [Time Weighted Average Price and Exponentially Weighted Moving Average](/security/oracles/price-protection) smoothing filters out short-term manipulation. Even if a single price update is manipulated (e.g., via a flash loan), the smoothed price barely moves because the manipulated datapoint is diluted across the time window. ### Price Bands for Pegged Assets Stable and pegged assets have [price bands](/security/oracles/price-protection#price-bands) — if the reported price falls outside the expected range (e.g., USDC outside ±1% of \$1.00), it is rejected outright. This prevents flash crash exploits and feed malfunctions from affecting protocol operations. ### Multi-Provider Cross-Referencing Scope cross-references Chainlink and Pyth Pro for each asset. If one provider reports a price that deviates significantly from the other, the anomalous feed is deprioritized and the protocol uses the validated price. ## How Oracle Risk Maps to Parameters Assets with higher oracle pricing risk receive more conservative protocol parameters: | Oracle Quality | Typical Parameters | | - | - | | **High** (both Chainlink and Pyth Pro, sub-second freshness, deep liquidity) | Higher Max LTV, lower borrow factor, general asset eligibility | | **Medium** (single premium feed, or thinner underlying liquidity) | Moderate Max LTV, moderate borrow factor | | **Low** (derived or centralized feed only, limited history) | Lower Max LTV, higher borrow factor, potential isolation mode | An asset that cannot achieve acceptable oracle quality — for example, a token with no reliable oracle feed — cannot be listed on Kamino at all, regardless of how it scores on other dimensions. ## Ongoing Monitoring Oracle quality is not static. Providers add and remove feeds, update frequencies change, and new providers enter the market. The risk framework continuously monitors: * Provider availability per asset (are all expected feeds active?) * Feed freshness (are updates arriving on schedule?) * Cross-provider deviation (are providers in agreement?) * Staleness events (how often do feeds go stale, and for how long?) Changes in oracle quality trigger reassessment. If a provider drops support for a token's feed, reducing the number of independent sources, the asset's oracle risk score increases and parameters may be tightened accordingly. The [KRAF Dashboard](/risk/kraf-dashboard) provides real-time visibility into oracle health metrics for all listed assets. # Smart Contract Risk Source: https://docs.kamino.com/risk/asset-risk/smart-contract How the code quality and security posture of listed tokens' underlying contracts are evaluated Many tokens listed on Kamino derive their value from an underlying smart contract. A liquid staking token like JitoSOL depends on the Jito staking vault contract. A wrapped token depends on the bridge contract. A vault token depends on the vault's accounting logic. If that underlying contract is exploited, the token's value can drop to zero — regardless of market conditions. Smart contract risk evaluates the probability and potential impact of such an exploit. It is one of the most consequential dimensions of the [asset risk framework](/risk/asset-risk), because a smart contract failure can cause total loss of value — not a gradual decline, but an immediate collapse. ## Why This Matters for a Lending Protocol When Kamino accepts a token as collateral, it is implicitly trusting the smart contract that backs that token. If the contract is exploited and the token's value drops to zero, every loan collateralized by that token becomes undercollateralized instantly. Liquidators cannot execute profitably because there is no market for a worthless token. The result is bad debt — socialized among lenders. This is not theoretical. Smart contract exploits have caused billions in losses across DeFi: * **Euler Finance (2023):** \$197M drained via a flash loan exploit in the lending contract itself * **Mango Markets (2022):** \$114M drained via oracle manipulation combined with thin liquidity * **Wormhole (2022):** \$320M drained from the bridge contract, affecting all wrapped tokens Each of these events would have caused catastrophic bad debt on any lending protocol that listed the affected tokens as collateral without adequate risk controls. ## Evaluation Criteria ### Audit History Has the token's underlying contract been audited? How many times? By which firms? The assessment distinguishes between: * **Multiple audits by reputable firms:** Highest confidence. Different auditors catch different classes of bugs. Multiple independent reviews significantly reduce the probability of undetected critical vulnerabilities. * **Single audit by a reputable firm:** Good baseline, but a single auditor may have blind spots. * **No audit or audit by unknown firms:** Significantly elevated risk. The contract may contain undiscovered vulnerabilities. The assessment also considers the scope of the audit — a full-scope audit of the entire codebase is more valuable than a narrow review of a single module. ### Open Source Is the contract's source code publicly verifiable? Open-source contracts benefit from community review — thousands of developers and security researchers can inspect the code, report issues, and contribute to security. Closed-source contracts require trusting the development team exclusively. For tokens that depend on verified on-chain bytecode, the assessment checks whether the deployed bytecode matches the published source code (verifiable builds). ### Immutability vs. Upgradability * **Immutable contracts** cannot be changed after deployment. Once audited, the security properties are permanent — but bugs cannot be fixed either. * **Upgradable contracts** (via proxy patterns or multisig authority) can be modified. This allows bug fixes, but also introduces risk: the upgrade authority can change the contract's behavior, potentially draining funds. The assessment evaluates the upgrade mechanism: Who holds the upgrade authority? Is it a multisig? How many signers are required? Is there a timelock? A 5-of-9 multisig with a 48-hour timelock is substantially lower risk than a single-signer upgrade authority with no delay. ### Battle-Testing How long has the contract been live on mainnet? How much value has it secured over that period? A contract that has held \$500M for two years without incident provides stronger evidence of security than one deployed last month, even if both have been audited. Battle-testing is not a substitute for auditing — it is complementary. Audits catch bugs before deployment; battle-testing reveals whether any bugs were missed in production conditions. The longer a contract operates under real economic conditions without exploit, the higher the confidence in its security. ### Bug Bounty Does the project operate an active bug bounty program? Bug bounties create an ongoing economic incentive for white-hat security researchers to find and report vulnerabilities rather than exploit them. The assessment considers: * **Bounty size:** A \$1M bounty attracts more research attention than a \$10K bounty * **Scope:** Does the bounty cover the specific contracts that back the token? * **Program maturity:** How long has the bounty been active? Has it paid out? ## Risk Mitigation for High-Risk Tokens Tokens that score poorly on smart contract risk are not necessarily excluded from Kamino. They can still be listed, but with strict risk controls: ### Supply Caps Total protocol exposure to any single token is limited by supply caps. If a token's underlying contract is exploited, losses are bounded by the cap amount — not the total protocol TVL. ### Isolation Modes High smart contract risk tokens can be restricted to [isolated collateral](/risk/asset-risk#isolated-collateral) mode. A position using isolated collateral is ring-fenced: problems with that token's contract cannot cascade into other positions or affect the broader protocol. ### Conservative LTV Tokens with elevated smart contract risk receive lower Max LTV limits. This creates a larger buffer between the collateral value and the liquidation threshold, providing more time and margin for liquidations to execute if the token's value begins to decline due to a partial exploit or loss of confidence. ## The Assessment in Practice A well-established token like SOL scores highly on smart contract risk: the Solana runtime is battle-tested across years, the token is native (no underlying contract dependency), and the validator ecosystem is mature. A newer liquid staking token might score moderately: it has been audited by one or two firms, it is open source, but it has only been live for six months and has a relatively small bug bounty. This token would likely receive a moderate Max LTV with supply caps, or be placed in isolated mode until its battle-testing track record improves. A vault token from an unaudited protocol with a single-signer upgrade authority would score poorly: the underlying contract risk is unacceptably high. This token would either not be listed or be restricted to isolated mode with very conservative parameters. Smart contract risk is reassessed when material events occur — if a listed token's underlying protocol suffers an exploit on another chain, or if audit findings on a related codebase raise concerns, the assessment is updated and parameters may be tightened. # Framework & Track Record Source: https://docs.kamino.com/risk/index How Kamino manages risk across its lending protocol, and the empirical track record under real market stress Risk in a lending protocol comes down to one question: can every lender get their tokens back? Two things can prevent this: **insolvency** (bad debt from loans that couldn't be liquidated) and **illiquidity** (all tokens are borrowed and no one is repaying). Kamino's risk framework is designed to prevent both. ## Risk Dimensions ### Insolvency Risk Insolvency occurs when a borrower's position becomes unhealthy (LTV exceeds the liquidation threshold) and the liquidation cannot be profitably executed — typically because the collateral token lacks sufficient market liquidity to be sold without excessive slippage. The resulting bad debt is socialized among lenders. Kamino mitigates insolvency risk through: * Rigorous [asset risk assessment](/risk/asset-risk) before onboarding any token * Continuous [market risk monitoring](/risk/market-risk) of volatility, liquidity, and price impact * Conservative LTV and borrow factor parameters calibrated to market conditions * [Protocol safeguards](/risk/safeguards/auto-deleverage) that can unwind risky positions before bad debt materializes ### Liquidity Risk Liquidity risk arises when borrowing demand exhausts the available supply in a reserve, reaching 100% utilization. Lenders cannot withdraw until borrowers repay or new supply arrives. This does not cause financial loss — in fact, it produces exceptionally high interest rates for lenders — but it temporarily restricts withdrawals. Kamino mitigates liquidity risk through: * [Interest rate curves](/risk/safeguards/interest-rates) calibrated to spike when utilization exceeds target levels, creating economic pressure for repayment * [Daily caps](/risk/safeguards/daily-caps) that limit the rate at which borrows can accumulate * Real-time utilization monitoring with alerting ### Systemic Risk Systemic risk emerges when multiple assets on the protocol are correlated — a broad market downturn triggers liquidations across many positions simultaneously, potentially overwhelming liquidation infrastructure or liquidity. Kamino monitors [token correlations and systemic exposure](/risk/market-risk/correlations) and uses E-Mode caps and supply caps to limit concentrated exposure. ## Token Onboarding Every asset listed on Kamino undergoes a 5-dimension risk assessment before it can be used as collateral or borrowed: 1. **[Oracle Pricing Risk](/risk/asset-risk/oracle-pricing)** — reliability and redundancy of the asset's price feeds 2. **[Smart Contract Risk](/risk/asset-risk/smart-contract)** — audit history, maturity, and battle-testing of the token's underlying contracts 3. **[Depeg Risk](/risk/asset-risk/depeg)** — for pegged assets, the probability and impact of losing the peg 4. **[Counterparty Risk](/risk/asset-risk/counterparty)** — governance decentralization, holder concentration, and trust assumptions 5. **[Market Risk](/risk/market-risk)** — volatility, liquidity, and price impact dynamics Based on this assessment, each asset is classified into one of three tiers: | Tier | Description | Implications | | - | - | - | | **General Asset** | Meets all risk criteria | Full cross-margin eligibility, higher LTV limits | | **Isolated Collateral** | Elevated risk in one or more dimensions | Can only be used as collateral in isolated mode | | **Isolated Debt** | Elevated borrowing risk | Can only be borrowed in isolated mode | The assessment directly determines the asset's **Collateral Max LTV** (how much can be borrowed against it) and **Borrow Factor** (the risk weight applied to the debt). Higher-risk assets receive more conservative parameters. Onboarding is not a one-time event. The risk framework continuously reassesses listed assets. Market conditions change — an asset that was low-risk at onboarding may become high-risk if its liquidity drops, its oracle coverage narrows, or its smart contract is compromised. Parameter adjustments follow reassessment. ## Battle-Tested Track Record Kamino has operated since November 2023 with **\$0 bad debt** across every market condition — including 5 significant stress events that tested the liquidation infrastructure and risk parameters under real-world conditions. | Event | Date | Collateral Seized | Bad Debt | | - | - | - | - | | Flash Analysis | Feb 16–18, 2025 | \$4.1M | **\$0** | | Market Correction | Feb 24 – Mar 2, 2025 | \$22.1M | **\$0** | | SOL/ETH Crash | April 6–7, 2025 | \$16M | **\$0** | | October Correction | Oct 10, 2025 | \$20M | **\$0** | | SOL -18% Crash | Feb 5–6, 2026 | \$19.36M | **\$0** | ### February 2026 Stress Event — Case Study The most severe test of Kamino's risk framework occurred on February 5–6, 2026, when SOL dropped 18% (from \$92 to \$76), ETH fell \~15% (from \$2,148 to \$1,832), and JLP declined \~10% (from \$3.83 to \$3.43) over 48 hours. **Scale of liquidations:** * 55,649 individual liquidation events * 30,030 wallets affected * \$19.36M in collateral seized * **\$0 bad debt generated** **Market breakdown:** | Market | Liquidation Events | Collateral Seized | | - | - | - | | Main | 44,665 | \$12.79M | | JLP | 10,560 | \$6.47M | | Bitcoin | 214 | \$20K | | Fartcoin | 67 | \$47K | | JTO | 4 | \$12.6K | **Key finding:** 99.6% of liquidations came from uncorrelated positions (e.g., SOL collateral / USDC debt). Correlated positions (e.g., JitoSOL/SOL) were barely affected, validating the [LST oracle](/security/oracles/lst-oracles) design that uses stake rates instead of market prices. **Flight to quality:** During the event, deposits flowed from higher-risk markets to safer ones. The Prime market grew by +\$55M in supply (+13.5%), and the Superstate market saw +56% supply growth — reflecting depositor preference for markets with tighter risk parameters during volatility. **Post-event protocol health:** The protocol continued operating normally throughout the event with no degradation in service. Detailed analysis: [Risk Event Analysis — February 5–6, 2026](https://gov.kamino.finance/t/kamino-risk-event-analysis-feb-5-6-2026/868) ## Monthly Risk Reports Since early 2025, [Allez Labs](https://www.allezlabs.xyz/) has published comprehensive monthly risk reports to the [Kamino governance forum](https://gov.kamino.finance) — over 14 reports to date. These reports cover: * **Protocol-level metrics:** Total supply, debt, TVL, transaction volumes, liquidation counts * **Market-by-market analysis:** Supply, borrow, and utilization trends across all markets * **Stablecoin and SOL market analysis:** Composition shifts, rate dynamics, LST trends * **Vault performance:** TVL, curator activity, user flows across Earn Vaults * **Stress testing scenarios:** Instantaneous price shock modeling at -10%, -20%, -30%, -40%, -60% levels * **User behavior analysis:** Wallet activity, transaction patterns, concentration metrics The reports provide a public, auditable record of Kamino's risk posture over time. Anyone can review the historical data and methodology. [View all risk reports on the governance forum →](https://gov.kamino.finance/c/risk/7) ## Continuous Monitoring Risk management is not a periodic activity — it runs continuously. The following metrics are tracked in real-time: * Utilization rates per reserve (approaching 100% triggers interest rate escalation) * LTV distributions across all active positions (clustering near liquidation thresholds indicates elevated risk) * Oracle staleness and cross-provider deviation (signals potential oracle issues) * Cap utilization (supply, borrow, and daily caps approaching limits) * Liquidation-at-risk metrics (what percentage of positions would be liquidated at various price shock levels) * Vault allocation changes (unusual curator behavior) Anomalies in any of these metrics trigger review. The response escalation path ranges from parameter adjustments to emergency measures like [auto-deleverage](/risk/safeguards/auto-deleverage). ## Insurance Fund Kamino Lend does not operate a protocol-level insurance fund. No bad debt has ever been incurred — the \$0 bad debt track record reflects the effectiveness of the risk framework and protocol safeguards rather than a backstop fund. At the product level, [Lending Vaults](/products/lending-vaults/insurance-pool) offer first-loss capital (insurance pools) where curators lock their own capital as a buffer. This is a vault-level feature managed by individual curators, not a protocol-wide mechanism. # KRAF Dashboard Source: https://docs.kamino.com/risk/kraf-dashboard Guide to the live Kamino Risk Assessment Framework dashboard at risk.kamino.finance The **Kamino Risk Assessment Framework (KRAF)** dashboard is a public, real-time risk monitoring tool available at [risk.kamino.finance](https://risk.kamino.finance). It provides complete visibility into the protocol's risk posture — every metric referenced in the risk framework documentation is available live on this dashboard. The dashboard is maintained by [Allez Labs](https://www.allezlabs.xyz/), Kamino's risk management partner, and is updated continuously with on-chain data. ## Risk Overview The main view provides a summary of protocol-wide risk metrics: * **Deposits, borrows, and rates** for every listed asset across all Kamino markets * **Utilization rates** — how close each reserve is to full utilization * **Global caps** — supply caps, borrow caps, and their current utilization * **Liquidation-at-risk** — the dollar value of positions that would be liquidated at various price shock levels (e.g., -10%, -20%, -30%) * **Deposit and borrow distribution** — composition of the protocol's total TVL by asset * **Interest rate curves** — the current rate curve parameters and actual rates for each token This view answers the question: *what does the protocol look like right now, and where are the pressure points?* ## Loans Analysis A filterable, tabular view of every active loan on the protocol: | Field | Description | | - | - | | **Current LTV** | The loan's current loan-to-value ratio | | **Max LTV** | The maximum LTV allowed for this loan's collateral mix | | **Liquidation LTV** | The threshold at which the loan becomes liquidatable | | **Total Deposits** | Dollar value of all collateral in the position | | **Total Borrows** | Dollar value of all debt in the position | | **Net Value** | Deposits minus borrows — the borrower's equity | Each loan can be expanded to show a detailed per-loan visualization — how the LTV has changed over time, which assets compose the collateral and debt, and how close the position is to liquidation. ### Token Decompositions For each loan, the dashboard breaks down: * **Deposit composition** — which tokens make up the collateral, in what proportions * **Borrow composition** — which tokens are borrowed, in what proportions This reveals concentration risk at the individual loan level — a loan that is 100% JitoSOL collateral / 100% USDC debt has a very different risk profile than a diversified position across multiple collateral tokens. ## Volatility Risk The volatility tab provides: * **Token price time series** — historical price charts for all listed assets * **Parkinson's realized volatility** — rolling [Parkinson's volatility](/risk/market-risk/volatility) time series, showing how each asset's volatility has evolved over short, medium, and long-term windows This allows direct comparison of volatility regimes across assets and over time. A sudden spike in an asset's Parkinson's volatility may signal the need for parameter review. ## Liquidity Risk The liquidity tab provides real-world, on-chain liquidation cost data: * **Percentage price impact** for buy and sell Jupiter swaps at various USD sizes (\$10K, \$50K, \$100K, \$500K, \$1M+) * **Impact comparison across assets** — which assets can absorb large trades, and which cannot * **Historical price impact trends** — whether liquidity is improving or deteriorating for each asset This data directly answers the core market risk question: *at the current supply cap, could a max-size position be liquidated profitably?* If the price impact at cap-implied max position size exceeds the liquidation bonus, the cap may need to be lowered. ## Price Shock Analysis The most sophisticated section of the dashboard. It models four types of stress scenarios: ### Uniform Shock All token prices drop by the same percentage simultaneously (e.g., -20% across the board). This models a broad market crash and shows: * How many positions become liquidatable * Total dollar value at risk * Expected bad debt (if any positions would cross the insolvency threshold) ### Individual Token Shock A single token drops by a specified percentage while all others remain stable. This models an idiosyncratic event (e.g., a smart contract exploit, a depeg) and reveals: * Protocol exposure to that specific token * Which loans are affected * Whether isolation mechanisms contain the damage ### Correlation-Based Shock Correlated groups of tokens decline together (e.g., SOL + all LSTs drop 25%, while stablecoins hold). This is the most realistic stress model, as it reflects how markets actually behave during downturns — correlated assets move together. ### Historic Event Replay Replays actual historical events (e.g., the February 2026 crash, the April 2025 SOL/ETH crash) against the current protocol state. This answers: *if that event happened today, with today's positions and parameters, what would the impact be?* ## Stress Testing Data The monthly risk reports published by Allez Labs include detailed stress testing at standard shock levels. Representative data from the November 2025 report: | Shock Level | Liquidation Volume | Estimated Bad Debt | | - | - | - | | **-10%** | \~\$50M | \$0 | | **-20%** | \~\$137M | \~\$2.3M | | **-30%** | \~\$275M | \~\$11.6M | | **-40%** | \~\$419M | \~\$32.6M | | **-60%** | \~\$845M | \~\$119M | These stress tests calibrate the protocol's resilience envelope. A -10% shock produces zero bad debt. A -20% shock produces minimal bad debt. Beyond -30%, the numbers grow — but these are instantaneous, uniform shocks (all prices drop simultaneously with no time for liquidators to act), representing an extreme worst case. In practice, even the February 2026 event — SOL -18% over 48 hours — produced \$0 bad debt, because liquidators had time to act and the price decline was not instantaneous. ## Risk Reduction Modeling The risk reduction tab models the impact of proposed parameter changes before they are implemented: * **Cap reductions** — if supply cap for Asset X is reduced from \$50M to \$30M, how does the risk profile change? * **Auto-deleverage scenarios** — if positions above a certain LTV are deleveraged, what is the net effect on protocol risk? * **LTV adjustments** — if Max LTV for Asset Y is lowered from 75% to 65%, how many positions are affected and what is the change in liquidation-at-risk? This allows the Risk Council to quantify the impact of proposed interventions before executing them — ensuring that parameter changes achieve the intended risk reduction without unnecessary disruption to users. ## Monthly Risk Reports Since early 2025, Allez Labs has published comprehensive monthly risk reports to the [Kamino governance forum](https://gov.kamino.finance/c/risk/7). Over 14 reports have been published to date. These reports provide: * **Protocol-level metrics:** Total supply, debt, TVL, transaction volumes, liquidation counts * **Market-by-market analysis:** Supply, borrow, and utilization trends across all Kamino markets * **Stablecoin and SOL market analysis:** Composition shifts, rate dynamics, LST trends * **Vault performance:** TVL, curator activity, user flows across Earn Vaults * **Stress testing scenarios:** Instantaneous price shock modeling at multiple severity levels * **User behavior analysis:** Wallet activity, transaction patterns, concentration metrics These reports create a public, auditable record of Kamino's risk posture over time. Anyone can review the historical data, methodology, and track record. [View all risk reports on the governance forum →](https://gov.kamino.finance/c/risk/7) # Correlations & Systemic Risk Source: https://docs.kamino.com/risk/market-risk/correlations How token relationships, market capitalization, and systemic exposure are evaluated Individual asset risk analysis — volatility, liquidity, price impact — treats each token in isolation. But in a lending protocol with dozens of listed assets, the portfolio matters. Correlations between tokens determine whether a market downturn triggers isolated liquidations or a protocol-wide cascade. ## Token Correlation When Kamino onboards a new token, the risk framework evaluates its relationship with tokens already listed on the protocol. This matters because correlated assets amplify systemic exposure. ### The SOL LST Example Consider a lending protocol that lists SOL, JitoSOL, mSOL, and bSOL as collateral. Each LST's price is fundamentally tied to SOL — they all represent staked SOL plus accumulated rewards. If SOL drops 20%, all four assets decline simultaneously. The effective collateral exposure to SOL across the protocol is not just the SOL deposits — it is the sum of SOL, JitoSOL, mSOL, and bSOL deposits. This means: * **Liquidation demand compounds.** A SOL crash triggers liquidations across all four assets simultaneously, requiring the market to absorb significantly more selling pressure than any single-asset analysis would suggest. * **Idiosyncratic risks stack.** Each LST introduces its own smart contract risk, depeg risk, and liquidity characteristics — on top of the shared SOL price risk. * **Liquidity is shared.** Liquidating JitoSOL and mSOL simultaneously competes for the same underlying SOL liquidity. The cumulative price impact may be far worse than liquidating either alone. ### Empirical Validation — February 2026 The [February 2026 stress event](/risk#february-2026-stress-event--case-study) provided real-world data on correlation dynamics: * **99.6% of liquidations** came from uncorrelated positions (e.g., SOL collateral / USDC debt) — where the collateral and debt prices moved in opposite directions (or debt was stable while collateral dropped). * **Correlated positions** (e.g., JitoSOL collateral / SOL debt) were barely affected — because both collateral and debt moved together, the LTV ratio remained stable. This validates two design decisions: 1. [LST stake-rate oracles](/security/oracles/lst-oracles) effectively eliminate market-noise liquidations for correlated pairs 2. E-Mode for correlated pairs (higher LTV for JitoSOL/SOL) is well-calibrated — the Feb 2026 event did not produce bad debt in these positions ### Correlation Monitoring The framework continuously tracks: * **Price correlation matrices** across all listed assets — rolling 30-day and 90-day windows * **Stress correlation** — correlations tend to increase during market downturns (assets that appear uncorrelated during calm markets become correlated during crashes). The framework uses stress-period correlations, not calm-period correlations, for conservative parameter setting. * **New listing impact** — before onboarding a new asset, the analysis models how the protocol's effective exposure changes if the new asset's correlation with existing assets approaches 1.0 during stress ## Market Capitalization Market capitalization provides context for interpreting other risk metrics. A token with \$10B market cap and adequate current liquidity is structurally different from a token with \$50M market cap and the same current liquidity — the larger token has deeper potential buyer interest, more diverse holder base, and more market-making infrastructure. ### Circulating vs. Fully Diluted The framework emphasizes **circulating market capitalization** over fully diluted valuation (FDV). A token with \$100M circulating cap and \$5B FDV has 98% of its supply still locked — future unlocks will create selling pressure that current liquidity metrics do not reflect. ### Token Emissions and Unlocks Large upcoming token unlocks directly affect liquidity risk: * **Sell pressure:** Newly unlocked tokens may be sold by early investors or team members, depressing the price and potentially triggering liquidations * **Dilution:** Increased circulating supply reduces the effective market cap per token, all else equal * **Uncertainty:** The market often prices in unlock events in advance, increasing volatility as the date approaches The risk framework considers unlock schedules when setting parameters. A token with a cliff unlock of 20% of circulating supply in the next quarter faces elevated volatility risk that current Parkinson's readings may not yet reflect. ### Low-Cap Considerations Tokens with small market capitalization present specific challenges: * **Liquidity fragility.** A \$30M market cap token may have adequate DEX liquidity today, but that liquidity can evaporate quickly if sentiment shifts. Large-cap tokens have deeper, more resilient liquidity. * **Whale influence.** A single large holder of a low-cap token can move the price significantly. This creates manipulation risk that is difficult to capture through standard volatility measures. * **Limited trading history.** Newer, smaller tokens have less price history for volatility analysis, making parameter calibration less reliable. Low-cap tokens typically receive more conservative parameters — lower Max LTV, lower supply caps, and potential isolation mode — reflecting these structural vulnerabilities. ## Systemic Risk Considerations Systemic risk emerges when the protocol's aggregate exposure to correlated assets exceeds what the market can absorb during a stress event. ### Concentration Analysis The framework tracks how much of the protocol's total collateral and debt is concentrated in correlated asset groups: * **SOL-correlated assets** (SOL + all LSTs): What is the total protocol exposure? If SOL drops 30%, how much collateral is at risk simultaneously? * **Stablecoin concentration:** If one stablecoin represents 60% of all debt, a depeg event on that stablecoin affects 60% of all loans * **Single-market concentration:** How much TVL is in each Kamino market? A single market with outsized exposure is a concentration risk ### Broad Downturn vs. Idiosyncratic Event The framework models two stress scenarios: 1. **Broad market downturn:** All crypto assets decline simultaneously (as in Feb 2026). In this scenario, correlations approach 1.0 — nearly everything drops together. The total liquidation demand is the sum across all assets. 2. **Idiosyncratic event:** A single asset experiences a shock (smart contract exploit, depeg, governance failure) while the rest of the market is unaffected. In this scenario, damage is concentrated but exposure is limited to that asset's caps and isolation constraints. Parameter setting must account for both scenarios. Supply caps limit idiosyncratic damage; systemic risk limits (total exposure across correlated groups) limit broad-downturn damage. ### How Caps Control Systemic Risk * **[E-Mode caps](/risk/safeguards/e-mode-caps):** Limit exposure per collateral/debt pairing — preventing outsized positions in any single correlated pair * **Supply caps:** Limit total deposits of each asset — bounding the maximum collateral at risk from any single asset * **[Daily caps](/risk/safeguards/daily-caps):** Limit how quickly exposure can build — preventing rapid accumulation of correlated risk * **Market-level caps:** Each Kamino market has its own exposure limits, preventing systemic concentration in a single market Together, these mechanisms ensure that the protocol's total exposure to any correlated group remains within what the market can absorb during a stress event — as validated by the [\$0 bad debt track record](/risk#battle-tested-track-record) across five documented stress events. The [KRAF Dashboard](/risk/kraf-dashboard) provides price shock analysis that models the impact of correlated downturns at various severity levels (-10%, -20%, -30%, -40%, -60%) across the entire protocol. # Market Risk Overview Source: https://docs.kamino.com/risk/market-risk/index How token volatility, liquidity, and price dynamics determine whether liquidations can execute profitably Market risk in a lending protocol comes down to one question: **can liquidators profitably liquidate unhealthy loans when required?** When a borrower's position becomes unhealthy — their loan-to-value ratio exceeds the liquidation threshold — a liquidator must step in. The liquidator acquires the debt token, provides it to the protocol, receives the collateral token at a small discount (the liquidation bonus), and then sells the collateral on the open market. For this process to work, the collateral must be liquid enough to sell without excessive price impact, and the liquidation must complete before the position deteriorates further. If liquidators cannot execute profitably — because the collateral is too illiquid, the price is moving too fast, or the price impact of selling exceeds the liquidation bonus — the position becomes bad debt. Bad debt is socialized among lenders in the affected reserve. Market risk analysis determines how likely this failure mode is for each listed asset. ## The Two Axes of Market Risk ### Asset Volatility [Volatility](/risk/market-risk/volatility) measures how fast and how far an asset's price can move. High volatility means a position can go from healthy to deeply underwater quickly — potentially faster than liquidators can respond. Volatility directly determines how much buffer is needed between the Max LTV (the maximum borrowing limit) and the Liquidation LTV (the threshold at which liquidation is triggered). For a volatile asset, the gap must be wider — there needs to be enough room for the collateral to decline in value without the position crossing into bad debt territory before liquidators can execute. ### Asset Liquidity [Liquidity](/risk/market-risk/liquidity) measures whether the collateral can actually be sold at a reasonable price. An asset might have moderate volatility, but if there is no market depth — if selling \$500K of collateral would cause a 15% price impact — then liquidators cannot execute profitably for large positions. Liquidity determines the upper bound on position sizes that can be safely liquidated. This directly informs supply caps, borrow caps, and E-Mode caps for each asset. ## The Seven Metrics Market risk is quantified through seven metrics, each analyzed using hourly price data across short-term, medium-term, and long-term windows. Cryptocurrency markets are highly dynamic — a metric that was acceptable last month may be inadequate today. | Metric | What It Measures | Where It's Covered | | - | - | - | | **Volatility** | How fast and far prices move (Parkinson's measure) | [Volatility Analysis](/risk/market-risk/volatility) | | **Token Liquidity** | Overall ability to convert large positions to cash | [Liquidity & Price Impact](/risk/market-risk/liquidity) | | **Trading Volumes** | Market activity and ease of execution | [Liquidity & Price Impact](/risk/market-risk/liquidity) | | **Price Impact** | Cost of executing swaps at various sizes | [Liquidity & Price Impact](/risk/market-risk/liquidity) | | **Price Resilience** | Market recovery speed after large trades | [Liquidity & Price Impact](/risk/market-risk/liquidity) | | **Market Capitalization** | Overall market size and token emission dynamics | [Correlations & Systemic Risk](/risk/market-risk/correlations) | | **Token Correlation** | Relationship with other listed assets | [Correlations & Systemic Risk](/risk/market-risk/correlations) | ## How Liquidation Works — From a Risk Perspective Understanding market risk requires understanding the mechanics of liquidation: 1. **Detection:** A liquidator bot monitors all active positions on the protocol. When a position's LTV exceeds the liquidation threshold, it becomes eligible for liquidation. 2. **Execution:** The liquidator submits a transaction that repays some or all of the borrower's debt. In return, the liquidator receives the borrower's collateral at a discount (the liquidation bonus — typically 3-10% depending on the asset). 3. **Collateral sale:** The liquidator sells the received collateral on the open market (typically through DEX aggregators like Jupiter). The profit is the liquidation bonus minus transaction costs and price impact. 4. **Flash loan option:** Liquidators can use flash loans to execute without holding capital — borrow the debt token, liquidate, receive collateral, sell collateral, repay the flash loan, pocket the difference. This makes liquidation capital-efficient and competitive. The risk failure mode is step 3: if the price impact of selling the collateral exceeds the liquidation bonus, the liquidation is unprofitable. No rational liquidator will execute it. The position continues to deteriorate, and if the collateral value drops below the debt value, bad debt results. ## Dynamic Calibration Cryptocurrency markets change rapidly. An asset that was highly liquid last quarter may have lost significant market depth. A token that was stable may have entered a volatile regime. Market risk analysis is not a one-time onboarding exercise — it runs continuously. The Risk Council reviews market risk metrics at regular intervals and after significant market events. When conditions change materially, parameters are adjusted: * **Volatility spike:** Max LTV may be lowered to create a wider liquidation buffer * **Liquidity decline:** Supply and borrow caps may be reduced to limit position sizes that would be difficult to liquidate * **Volume collapse:** Isolation mode may be imposed on assets that previously qualified for cross-margin * **Correlation shift:** E-Mode caps may be adjusted if the relationship between pegged assets changes All market risk metrics are available in real-time on the [KRAF Dashboard](/risk/kraf-dashboard), which provides price impact analysis, volatility measurements, and stress testing scenarios for every listed asset. ## How Market Risk Informs Parameters The market risk assessment directly determines several protocol parameters: | Parameter | What Market Risk Determines | | - | - | | **Max LTV** | Wider volatility → lower Max LTV (more buffer before liquidation) | | **Liquidation LTV** | The threshold at which liquidation is triggered — must be set high enough that liquidators can execute profitably given the asset's volatility and liquidity | | **Borrow Factor** | Less liquid / more volatile assets receive higher borrow factors, requiring more collateral per unit of debt | | **Supply Cap** | Maximum protocol exposure, bounded by how much collateral could be liquidated without excessive price impact | | **Borrow Cap** | Maximum outstanding debt, bounded by debt token liquidity | | **E-Mode Cap** | Per-pair limits that account for the specific liquidity and correlation dynamics of each collateral/debt pairing | | **Liquidation Bonus** | Must exceed expected price impact at the cap-implied maximum position size, otherwise liquidations become unprofitable | These parameters are interconnected. Changing one often requires adjusting others to maintain a consistent risk posture. The risk framework considers them holistically rather than in isolation. # Liquidity & Price Impact Source: https://docs.kamino.com/risk/market-risk/liquidity How token liquidity, trading volumes, price impact, and price resilience determine liquidation feasibility Liquidity is the single most critical metric for protocol solvency. A token can pass every other risk dimension — reliable oracles, audited smart contracts, decentralized governance, stable peg — but if it cannot be sold in meaningful size without crashing the price, liquidations will fail and bad debt will result. This page covers four tightly related aspects of market liquidity: overall token liquidity, trading volumes, price impact analysis, and price resilience. ## Token Liquidity Token liquidity measures the ability to convert large positions into cash (or another asset) at a reasonable price. For a lending protocol, "reasonable" means that the price impact of selling liquidated collateral does not exceed the liquidation bonus — otherwise, liquidators lose money and stop participating. ### Sources of Liquidity Liquidity for a given token can come from multiple sources: * **Native Solana DEX liquidity.** AMM pools (Orca, Raydium, Meteora) and order books (Phoenix, OpenBook) on Solana. This is the most directly accessible liquidity for on-chain liquidations. * **Cross-chain liquidity.** For tokens that exist on multiple chains (e.g., ETH, USDC), liquidity on Ethereum or other chains can be accessed via bridges or cross-chain solvers. This is slower and more complex but expands the available depth. * **Centralized exchange liquidity.** CEXes often have the deepest order books. Sophisticated liquidators can route through CEXes — sell collateral on a CEX and settle on-chain. This adds latency but access to significantly more depth. The risk framework considers all three sources, with the heaviest weight on native Solana liquidity — because it is the most accessible and fastest during stress events when speed matters most. ### What Makes Liquidity Fragile Liquidity can evaporate precisely when it is needed most. During market stress: * AMM liquidity providers withdraw to avoid impermanent loss * Order book market makers widen spreads or pull orders * DEX pool rebalancing creates directional pressure A token that shows adequate liquidity during calm markets may have dramatically reduced liquidity during a crash — exactly when liquidations are most needed. The risk framework accounts for this by stress-testing liquidity at elevated volatility levels, not just current conditions. ## Trading Volumes Trading volume measures overall market activity. High volumes indicate: * **Substantial liquidity:** Active markets have many participants willing to buy and sell * **Narrow bid-ask spreads:** Competition among market makers tightens spreads, reducing execution costs * **Reduced slippage:** More depth at each price level means less price impact per trade * **Continuous trading:** The asset can be traded at any time without waiting for counterparties Volumes are analyzed using hourly data across multiple time windows. The framework adjusts for **wash trading** — inflated volume figures from entities trading with themselves to create the appearance of activity. Raw volume numbers in cryptocurrency markets are notoriously unreliable; the assessment applies heuristic filters to identify and discount wash trading patterns. Low or declining volumes are a leading indicator of liquidity deterioration. A token whose volumes have dropped 80% over the past month may no longer support the liquidation sizes implied by its current supply cap — triggering a parameter review. ## Price Impact Analysis Price impact is the core quantitative measure of liquidation feasibility: how much does the price move when you sell a given amount of an asset? ### How It's Measured The framework measures price impact using **on-chain data** — actual swap execution costs through Jupiter (Solana's leading DEX aggregator). For each listed asset, the analysis captures: | Trade Size | What It Tells You | | - | - | | **\$10K** | Retail-scale. Should have negligible impact for any listed asset. | | **\$100K** | Moderate position. Impact should be under 1% for most assets. | | **\$500K** | Large position. Impact varies significantly by asset — from 0.1% for SOL to potentially 5%+ for thin tokens. | | **\$1M+** | Institutional-scale. Only the most liquid assets can absorb this in a single transaction. | ### Single-Transaction vs. Optimal Execution Two execution models are analyzed: 1. **Single-transaction execution:** Constrained by Solana's compute unit limit per transaction. This represents the worst case — a liquidator must sell the entire position in one shot. Price impact is highest. 2. **Multi-transaction optimal execution:** The collateral is sold across multiple transactions, potentially using multiple routes and DEX venues. This is more realistic for large liquidations — sophisticated liquidators split orders to minimize impact. Models draw from optimal execution literature (Almgren-Chriss framework) to estimate the achievable improvement over single-transaction execution. The gap between single-transaction and optimal-execution impact directly informs how conservative the parameters need to be. If optimal execution only marginally improves on single-transaction impact, the asset's liquidity is thin across all execution strategies. ### Liquidation Bonus Threshold Price impact must be compared against the liquidation bonus. If selling \$500K of collateral causes 4% price impact, but the liquidation bonus is only 3%, the liquidation is unprofitable at that size. This directly implies that position sizes above a certain threshold cannot be safely liquidated — and that supply caps must be set accordingly. ## Price Resilience Price resilience measures how quickly the market recovers after a large trade. Two dimensions are analyzed: ### Recovery Speed After a large sell order pushes the price down, how quickly does it return to pre-trade levels? Fast recovery indicates robust market-making infrastructure — limit orders are replenished, arbitrageurs close the gap, and new liquidity flows in. Slow recovery suggests the market absorbed a lasting shock. This matters for cascading liquidations. During a market downturn, multiple positions may become liquidatable simultaneously. If the first liquidation pushes the price down and the market does not recover before the next liquidation, the cumulative impact compounds — each subsequent liquidation executes at a worse price. ### Cumulative Impact The framework analyzes the cumulative impact of multiple large trades in sequence. If three \$200K sells each cause 1% impact individually but the cumulative impact of all three is 5% (rather than 3%), the market is exhibiting poor resilience — each trade is deepening the impact rather than being absorbed. ### Order Book Replenishment For assets traded on limit order books (Phoenix, OpenBook), the framework measures how quickly the order book refills after a large market order sweeps through price levels. LOBs tend to be more reactive than AMMs — market makers can replenish orders within seconds — but this depends on the specific asset and market conditions. ### Almgren-Chriss Framework Price resilience analysis draws on the Almgren-Chriss optimal execution model, which formalizes the tradeoff between execution speed and price impact. The model considers: * **Temporary impact:** The immediate price displacement caused by a trade, which partially recovers * **Permanent impact:** The lasting price change, reflecting genuine information content * **Volatility risk:** The risk that the price moves unfavorably while splitting a large order across time This framework provides a principled way to estimate the cost of liquidating large positions over realistic time horizons, rather than assuming instantaneous execution. ## How Liquidity Metrics Map to Parameters | Metric | Parameter Affected | | - | - | | **Price impact at cap-implied max position size** | Supply and borrow caps — must be set so that max position is liquidatable without exceeding the liquidation bonus | | **Trading volumes** | General asset eligibility — assets with insufficient volumes may be restricted to isolation mode | | **Price resilience** | E-Mode caps — for pairs where cascading liquidations are possible, resilience determines how much total exposure is safe | | **Cross-chain liquidity** | Borrow factor — assets with deep cross-chain liquidity but thin on-chain liquidity receive moderate borrow factors (liquidators can route off-chain, but at higher cost) | All liquidity metrics are available in real-time on the [KRAF Dashboard](/risk/kraf-dashboard), which provides percentage price impact charts for buy and sell swaps at various USD sizes for every listed asset. # Volatility Analysis Source: https://docs.kamino.com/risk/market-risk/volatility How Kamino measures token volatility using Parkinson's measure and how it informs LTV calibration Volatility is the rate at which an asset's price changes over time. In a lending protocol, volatility directly determines the risk of a healthy loan becoming liquidatable — and how quickly that transition can happen. A loan at 75% LTV with SOL collateral and USDC debt will be liquidated if the SOL price drops enough to push the LTV above the liquidation threshold (e.g., 85%). How likely is that 10% move? How quickly could it happen? These questions are answered by volatility analysis. ## Why Volatility Matters for LTV Calibration The gap between a token's Max LTV and its Liquidation LTV is the safety buffer. This buffer must be wide enough to account for how far the collateral price can drop — and how fast — before liquidators execute. If the buffer is too narrow, prices can gap through the liquidation threshold, leaving positions deeply underwater before liquidators can act. Consider two tokens: * **Token A** has annualized volatility of 40%. On an average day, its price moves 2-3%. A 10% safety buffer provides several days of runway before liquidation. * **Token B** has annualized volatility of 150%. On a volatile day, its price can move 10-15%. A 10% safety buffer could be consumed in hours. Token B requires a wider safety buffer — which means a lower Max LTV. Setting the same LTV parameters for both tokens would expose lenders to unacceptable risk on Token B. ## Parkinson's Volatility Measure Kamino uses **Parkinson's Volatility** rather than simple close-to-close volatility. Standard volatility measures — like the standard deviation of daily returns — only capture the price at two points (open and close). If a token's price drops 20% intraday and then recovers, standard volatility might show a calm day. But that 20% intraday drop could have triggered liquidations. Parkinson's measure captures the **intra-period range** — the highest and lowest prices within each time window: ``` σ = √( (1/4N·ln2) · Σᵢ [ln(Hᵢ/Lᵢ)]² ) ``` Where: * `Hᵢ` = highest price in period `i` * `Lᵢ` = lowest price in period `i` * `N` = number of periods * `ln` = natural logarithm By using the high-low range rather than open-close returns, Parkinson's measure captures volatility that intraday-recovering price movements would otherwise hide. This is particularly important for cryptocurrency markets, which are: * **24/7:** No market close means there are no overnight gaps. Parkinson's measure works especially well when there are no gaps between periods, because the high-low range fully captures the price action. * **Flash-crash prone:** Brief but severe price dislocations occur regularly on crypto markets. These are invisible to close-to-close measures but captured by Parkinson's. * **Liquidation-relevant:** What matters for liquidation risk is the maximum intraday drawdown, not whether the price recovered by close. Parkinson's measures exactly this. ## Calculation Methodology Volatility is calculated using **hourly price data** across multiple time windows: | Window | Purpose | | - | - | | **Short-term** (7 days) | Captures current market regime — is the asset in a volatile or calm period? | | **Medium-term** (30 days) | Smooths out short-term noise while still reflecting recent conditions | | **Long-term** (90+ days) | Establishes the baseline volatility regime for the asset | All three windows are considered together. A token might show low short-term volatility during a calm market, but its long-term window reveals periodic spikes. LTV calibration must account for the spikes, not just the calm. ## Monitoring and Response Volatility is not static — it clusters. Calm periods are followed by volatile periods, and volatile periods tend to persist. When volatility shifts, protocol parameters must respond: ### Gradual Volatility Increase If an asset's rolling volatility increases over days or weeks — perhaps due to shifting market sentiment, approaching token unlocks, or increased speculation — the Risk Council may proactively lower Max LTV or reduce supply caps before the volatility manifests as liquidation events. ### Sudden Volatility Spike Abrupt onset of extreme volatility — such as the February 2026 event when SOL dropped 18% in 48 hours — tests whether existing parameters were set conservatively enough. In that event, Kamino's LTV parameters held: 55,649 liquidations executed profitably with [\$0 bad debt](/risk#battle-tested-track-record). Post-spike, the Risk Council reviews whether the event was within expected parameters or whether recalibration is needed. ### Volatility Compression When an asset's volatility compresses over an extended period, there may be room to increase Max LTV — giving borrowers more capital efficiency. This is done cautiously, with the understanding that low-volatility periods often precede high-volatility events. ## Volatility Across Asset Classes Different asset classes on Kamino exhibit structurally different volatility profiles: | Asset Class | Typical Volatility Profile | LTV Implication | | - | - | - | | **USD Stablecoins** (USDC, USDT) | Very low (\~1-2% annualized) | Highest LTV, E-Mode eligible for stablecoin pairs | | **SOL** | Moderate-high (60-100% annualized) | Standard LTV (70-80%), primary collateral asset | | **SOL LSTs** (JitoSOL, mSOL) | Low relative to SOL (stake-rate priced) | E-Mode eligible for SOL pairs, higher LTV | | **ETH, BTC** | Moderate (50-80% annualized) | Standard LTV, similar to SOL | | **Newer tokens** | High (100-200%+ annualized) | Lower LTV, potential isolation mode | Note that LST volatility is measured relative to SOL when priced via [stake-rate oracles](/security/oracles/lst-oracles) — the stake rate increases monotonically, so LST/SOL volatility is near zero. This enables E-Mode with higher LTV for LST/SOL positions. ## Relationship to Other Market Risk Metrics Volatility analysis does not operate in isolation. A token could have moderate volatility but extremely thin liquidity — meaning that even moderate price moves make liquidation difficult because selling the collateral causes massive price impact. Conversely, a token could be highly volatile but deeply liquid — meaning liquidators can execute quickly at reasonable cost even during price swings. The [Liquidity & Price Impact](/risk/market-risk/liquidity) analysis is the complementary dimension: volatility tells you how fast prices can move; liquidity tells you whether liquidators can execute when they do. The [KRAF Dashboard](/risk/kraf-dashboard) provides real-time Parkinson's volatility time series for all listed assets, enabling continuous monitoring and comparison across tokens and time periods. # Auto-Deleverage Source: https://docs.kamino.com/risk/safeguards/auto-deleverage Kamino's novel mechanism for orderly unwinding of risky positions before bad debt materializes Lenders are the most important participants in the Kamino Lend protocol. Every aspect of the risk engine is designed to ensure lenders get their tokens back. Auto-deleveraging is a protocol-level mechanism — introduced by Kamino Lend contributors — that can facilitate an orderly, protocol-wide unwinding of any asset whose continued presence is deemed to pose a risk to lenders according to the risk framework. ## Why Auto-Deleverage Exists Auto-deleverage addresses two distinct categories of risk to lenders. The first is positions that cannot be safely liquidated through normal channels. The second is assets whose continued presence in the protocol creates ongoing risk to lenders, independent of any specific liquidation event. Both situations can lead to bad debt if left unaddressed, so the protocol needs a defined mechanism to handle them. ### Liquidity Collapse Consider a scenario where an asset listed as collateral on Kamino experiences a sudden collapse in market liquidity. There are \$50M of loans backed by this collateral, but the market can only absorb \$5M of sell pressure without catastrophic price impact. If those loans become liquidatable, liquidators cannot execute profitably — the price impact of selling the collateral exceeds the liquidation bonus. The result: bad debt, socialized among lenders. Auto-deleverage addresses this by facilitating an orderly unwinding of the asset *before* bad debt materializes. The protocol proactively reduces exposure to the risky asset while market conditions still allow liquidations to execute cleanly, well ahead of the point at which liquidator failure would force losses onto lenders. This category was the original motivation, in response to historical DeFi incidents: * **Aave CRV incident:** A whale accumulated a massive CRV-collateralized position. When CRV liquidity dried up, the position could not be liquidated without cascading the price further. The protocol eventually incurred bad debt. * **Solend whale incident:** A single large position threatened protocol solvency due to insufficient market liquidity to absorb a potential liquidation. In both cases, a pre-specified protocol mechanism with clear rules and timelines would have allowed for orderly action under crisis conditions. ### Asset Risk Deterioration Auto-deleverage also gives Kamino a defined way to wind down exposure to assets whose risk profile has materially deteriorated. This covers situations such as a token whose underlying contracts have been compromised, a stablecoin that loses its backing, an asset that becomes vulnerable to oracle manipulation, or a token whose issuer has introduced changes that make continued listing imprudent. In these cases the protocol may not face an immediate liquidity shortfall, but ongoing exposure still creates real risk to lenders. The same auto-deleverage mechanism applies, including the 72-hour margin call window for borrowers to act on their own terms before any forced action begins. Auto-deleverage serves a single goal in either category: keeping the protocol solvent and ensuring lenders get their tokens back. Every design choice in the mechanism flows from that goal — the 72-hour grace period with no penalty, the LTV-based eligibility ordering, and the penalty cap at the position's lowest liquidation penalty all exist to make the unwinding orderly and minimally disruptive for borrowers. ## Scope of Authority > [!NOTE] > > Kamino reserves the right to initiate auto-deleverage against any asset whose continued presence in the protocol is judged to pose a material risk to lenders or to overall protocol solvency. This authority applies regardless of the source of the risk, including market liquidity, asset quality, oracle integrity, smart contract integrity, regulatory exposure, and any other factor identified by the Risk Council or the [KRAF dashboard](/risk/kraf-dashboard). The 72-hour margin call window described below is the default timeline for any deleverage event, and the penalty schedule is calibrated to make voluntary action during that window the lowest-cost path for borrowers. The Risk Council retains the discretion to compress or waive this window where prompt action is required to address excessive risk to lenders — see [The 72-Hour Margin Call](#the-72-hour-margin-call) below for further detail. ## How It Works ### Triggering Auto-deleverage is triggered by the Risk Council through a multisig vote. When the [KRAF dashboard](/risk/kraf-dashboard) indicates that a cap change is prudent for a specific asset — due to liquidity deterioration, volatility spikes, or other risk signals — the Risk Council can initiate the deleverage process. The mechanism can also be automated in the future by taking into account various on-chain signals within the protocol. ### The 72-Hour Margin Call Once the multisig vote passes, all affected users are notified of the deleverage event and given a **72-hour margin call period** to take action. During this window: * No penalty is applied * Users can voluntarily reduce their exposure (repay debt, withdraw collateral, restructure positions) * If enough borrowers act voluntarily and bring exposure below the new caps, the process ends without any forced deleveraging This margin call period is a critical design choice: it gives borrowers the opportunity to manage their own risk first, before the protocol intervenes. > [!WARNING] > > The 72-hour window is the default timeline for any deleverage event. The Risk Council retains the authority to compress or waive this window when conditions warrant prompt action against excessive risk to lenders. This covers situations such as the removal of assets whose continued listing has become unsafe (for example, assets that have been deprecated or whose risk profile has materially shifted), responses to fast-moving threats to solvency, and any condition where the standard notice period would itself amplify harm or delay necessary risk mitigation. ### What Happens After the Margin Call A new, reduced cap is set for the target asset. The difference between the current amount and the new cap is the amount that will be auto-deleveraged. Users subject to deleveraging see a proportional reduction in the target asset, along with corresponding tokens in their position. Deleveraging generally results in a healthier (lower) LTV ratio for the affected position. **Lenders are never affected by auto-deleveraging — only borrowers.** ## Collateral Deleverage Collateral deleveraging is triggered when there is too much of an asset backing loans as collateral than can be successfully liquidated. The market liquidity for the collateral token has deteriorated to the point where liquidation would incur losses. **Example:** Token A deposit caps are lowered from \$100M to \$80M. 20% of Token A collateral must leave the system. All users with Token A supplied as collateral are notified. If a user is deleveraged: 1. Some or all of their Token A collateral is sold on the market 2. The proceeds repay their debt proportionally 3. A deleverage penalty is paid to the liquidator who executes the deleverage Supply deleverage for an asset often coincides with borrow deleverage on the same asset, since the triggers — typically an abrupt loss of market liquidity — affect both supply and borrow viability. ## Debt Deleverage Debt deleveraging is the reverse scenario. If there is too much debt in a specific token and prices were to rise, liquidators would need to buy the debt token off the market to close positions — but if the market buy would incur slippage exceeding the debt amount, liquidation is unviable. **Example:** Token B borrow caps are lowered from \$100M to \$80M. 20% of Token B debt must leave the system. When a user is deleveraged: 1. A portion of their collateral is sold 2. The proceeds are used to repay their Token B debt 3. This continues until the total Token B debt across the protocol reaches the new cap The penalty structure is designed to incentivize borrowers to take early action — ideally during the 72-hour margin call period when no penalty applies. ## Deleverage Penalty Deleveraged loans incur a minimum liquidation penalty of **50 basis points (0.5%)**. The penalty is calculated as a percentage of the deleverage amount. **Example:** If the penalty is 0.5% and the deleverage amount is 20% of the user's position: ``` Penalty impact = 0.2 × 0.005 = 0.001 = 0.1% ``` Instead of losing exactly 20% of their collateral, the user loses 20.1%. ### Penalty Escalation The penalty continually increases until either: * The **maximum penalty threshold** is reached, or * The **target asset deleverage cap** is achieved (all excess exposure has been unwound) The rate of increase is a function of the user's LTV and the time elapsed since deleveraging was initiated: ``` penalty = min_penalty + (current_ltv × days_since_initiation) ``` **Worked example:** | Parameter | Value | | - | - | | Minimum penalty | 50 bps (0.5%) | | Current LTV | 80% | | Days since initiation | 3.4 days | ``` penalty = 0.005 + (0.80 × 3.4) = 2.725% ``` ### Penalty Cap The maximum penalty is capped at the **lowest liquidation penalty** of the assets in the user's position. For example, if a position contains SOL, USDC, and WETH with liquidation penalties of 6%, 8%, and 10% respectively, the deleverage penalty is capped at 6%. This ensures the penalty never exceeds what a standard liquidation would cost. ## Who Gets Deleveraged? Once auto-deleveraging begins, a position is eligible for deleverage if: 1. It **contains the target asset**, AND 2. It has a **current LTV that exceeds the deleverage liquidation LTV** When deleveraging begins, the target asset's liquidation LTV is adopted as the initial `deleverage_liquidation_LTV`. Deleveraging starts with the highest-LTV positions and works downward. ### LTV Threshold Decrease Over time, the `deleverage_liquidation_LTV` decreases automatically, expanding the pool of eligible positions: ``` deleverage_ltv = liquidation_ltv − (0.0001 × slots_since_initiation / slots_per_bps) ``` **Example** (at 1 bps per hour = 7,200 slots per bps): ``` deleverage_ltv = 0.80 − (0.0001 × 345,600 / 7,200) = 79.52% ``` This declining threshold creates urgency: users whose LTV is currently safe will eventually become eligible for deleveraging if they do not act. The mechanism encourages borrowers to voluntarily reduce their LTV — ideally during the 72-hour margin call — rather than waiting to be deleveraged at an escalating penalty. ## Key Design Properties * **Lenders are never affected.** Only borrower positions are deleveraged. * **Orderly, not chaotic.** Unlike a mass liquidation event, auto-deleverage proceeds methodically from highest-risk positions to lowest, with escalating incentives for voluntary action. * **Not routine.** Auto-deleverage is a last-resort mechanism for situations where standard liquidation cannot function. It has not been activated to date — Kamino's [track record](/risk#battle-tested-track-record) shows \$0 bad debt across all market events without needing this mechanism. * **Preventive, not reactive.** The mechanism intervenes before bad debt materializes, not after. The goal is to never reach the point where liquidation failure occurs. > [!NOTE] > > Some of the parameters referenced above, such as the minimum liquidation penalty and the margin call duration, are indicative defaults and are configurable per market. Curators and the Risk Council can set different values where the market's risk profile or asset composition calls for it. # Daily Caps Source: https://docs.kamino.com/risk/safeguards/daily-caps How daily flow limits prevent outsized position buildup and bound potential damage from exploits Daily caps limit the rate at which assets can flow in and out of the protocol within a 24-hour window. They serve two critical purposes: bounding the potential damage from oracle exploits, and preventing outsized positions from building up faster than the risk framework can monitor. ## Two Cap Types Each asset reserve on Kamino has two daily caps: ### New Debt Cap The maximum **net new borrowing** of an asset within a 24-hour period. This limits how quickly debt exposure can accumulate. If an attacker discovers an oracle vulnerability, the new debt cap bounds the maximum amount they can borrow before the exploit is detected and patched. Without daily caps, an attacker could borrow the entire supply in a single transaction. ### Collateral Withdrawal Cap The maximum **net collateral outflow** within a 24-hour period. This limits how quickly deposited collateral can leave the system. This prevents a scenario where an attacker (or a panicking whale) drains collateral from the protocol faster than the system can respond — whether through legitimate withdrawals or exploit-driven extraction. ## Net Flow Mechanics Daily caps measure **net flows**, not gross flows. This is an important distinction: **Example:** In a 24-hour window: * \$10M USDC is borrowed by various users * \$8M USDC is repaid by other users * **Net new debt = \$2M** The net approach prevents legitimate market activity from being unnecessarily restricted. Normal borrowing and repayment can continue at high volumes as long as the net change stays within the cap. Only genuine one-directional accumulation triggers the limit. Similarly, for collateral: * \$5M SOL is deposited by new users * \$3M SOL is withdrawn by existing users * **Net collateral outflow = \$0** (net inflow of \$2M) Inflows do not consume cap capacity — the caps only limit net outflows. ## Protection Against Oracle Exploits Oracle exploits are among the most damaging attack vectors in DeFi lending. A successful oracle manipulation can allow an attacker to: 1. Artificially inflate the value of worthless collateral 2. Borrow large amounts of valuable tokens against the inflated collateral 3. Withdraw the borrowed tokens before the manipulation is detected Without daily caps, the attacker's potential gain is limited only by the total supply in the protocol. **With daily caps, the maximum damage is bounded by the daily cap amount** — regardless of how severe the oracle manipulation is. This turns a potentially protocol-ending exploit into a bounded loss that can be detected, investigated, and remediated. ### In Practice: Step Finance Incident (2026) Daily caps proved their value in a real-world incident when the [Step Finance treasury was compromised via social engineering](https://x.com/StepFinance_/status/2018379876642804213). The attacker gained access to Step's multisig and began draining assets — including a large vSOL position held on Kamino. Kamino's daily withdrawal caps stopped the attacker from extracting the full vSOL balance. Once the daily cap was reached, no further withdrawals were possible regardless of the attacker's access. The cap bought time for the incident to be detected and for response measures to be taken — limiting the total damage to the capped amount rather than the full position. This is exactly the scenario daily caps are designed for: an external compromise (not a Kamino vulnerability) where an unauthorized party attempts to rapidly drain assets. The cap converted what could have been a complete loss into a bounded one. ## Protection Against Outsized Positions Large positions — whether legitimate or malicious — introduce systemic risk. A single borrower with a \$100M position in a market with \$200M total supply represents 50% concentration risk. If that position becomes unhealthy, liquidating it requires finding buyers for \$100M of collateral — which may exceed available market depth. Daily caps prevent such positions from appearing overnight. An outsized position can only be built over multiple days, giving the risk monitoring system time to: * Detect the accumulating concentration * Assess the impact on protocol health metrics * Adjust parameters (caps, LTV, borrow factors) if the accumulation creates risk * Alert the Risk Council if intervention is needed This temporal buffer is critical. Without daily caps, a sophisticated actor could build a dangerously large position in a single block — before any monitoring system could react. ## Supply and Borrow Caps Separate from daily caps, Kamino enforces **global supply and borrow caps** per reserve. These are absolute limits on total deposits and total outstanding debt for each asset: | Cap Type | What It Limits | How It's Set | | - | - | - | | **Supply Cap** | Total amount of an asset that can be deposited as collateral | Based on on-chain liquidity — the cap ensures that the maximum collateral position is liquidatable | | **Borrow Cap** | Total outstanding debt for an asset | Based on debt token liquidity and market depth | | **Daily New Debt Cap** | Net new borrowing per 24 hours | Based on risk tolerance for oracle exploit damage | | **Daily Withdrawal Cap** | Net collateral outflow per 24 hours | Based on liquidity reserve requirements | Global caps limit total exposure; daily caps limit the rate of change. Together, they ensure that protocol exposure is bounded in both magnitude and velocity. ## How Caps Are Calibrated Daily caps are set by the Risk Council based on: * **On-chain liquidity depth:** Higher liquidity supports higher daily caps (larger positions can be absorbed by the market) * **Oracle robustness:** Assets with multiple oracle providers and strong [price protection mechanisms](/security/oracles/price-protection) can have higher daily caps (exploitation is harder) * **Market conditions:** During elevated volatility or reduced liquidity, daily caps may be temporarily lowered * **Historical analysis:** [KRAF Dashboard](/risk/kraf-dashboard) data on typical daily flows informs cap calibration — caps should be high enough not to restrict normal activity, but low enough to meaningfully limit exploit damage Caps are publicly visible in the Info & Risk section of each asset reserve page on the Kamino app. ## Interaction with Other Safeguards Daily caps work in concert with other protocol safeguards: * **[Auto-deleverage](/risk/safeguards/auto-deleverage):** If an asset's risk profile deteriorates, daily caps prevent rapid exposure buildup while the Risk Council evaluates whether to trigger auto-deleverage * **[E-Mode caps](/risk/safeguards/e-mode-caps):** Per-pair borrow limits provide an additional granularity layer — even within the daily cap, E-Mode caps can restrict how much of a specific debt can be taken against a specific collateral * **[Interest rate curves](/risk/safeguards/interest-rates):** As utilization increases (potentially approaching daily caps), interest rates spike to create economic disincentives for further borrowing # E-Mode Caps Source: https://docs.kamino.com/risk/safeguards/e-mode-caps Per-pair borrow limits that enable granular risk control for each collateral/debt combination E-Mode Caps is a novel risk management mechanism that enables each collateral/debt pairing on Kamino to have a unique debt limit. This introduces granular per-pair risk control into a pool-based lending model — a capability that most lending protocols lack. ## The Problem with Pool-Wide Caps In a traditional multi-asset lending pool (Kamino Lend V1, Aave V3), borrow caps are set per asset — not per pair. If the protocol raises the USDC borrow cap by \$10M, users can borrow that additional USDC against *any* available collateral in the pool. But not all collateral is equal. SOL is deeply liquid and can be liquidated efficiently at large sizes. A newer token might have thin liquidity and high liquidation risk. In a pool-wide cap model, the borrow cap is constrained by the riskiest available collateral — because the protocol must assume that all new borrows could be collateralized by that weakest asset. This creates a scaling problem: to protect against risk from low-quality collateral, the protocol must restrict borrowing capacity against high-quality collateral. Conservative caps for the weakest asset penalize users of the strongest asset. ## What E-Mode Caps Enable E-Mode Caps decouple borrow limits by collateral/debt pair. Instead of a single USDC borrow cap, the protocol can set: | Pair | Cap | | - | - | | SOL / USDC | \$50M | | wBTC / USDC | \$30M | | JUP / USDC | \$5M | | Other / USDC | \$0 (no E-Mode access) | Now the SOL/USDC cap can be raised aggressively — reflecting SOL's deep liquidity and efficient liquidation — without increasing exposure through JUP/USDC, where liquidation risk is higher. The result: **more capital efficiency for borrowers using high-quality collateral, without compromising protocol safety**. ## How E-Mode Works ### Automatic Detection Users do not need to manually enter or exit E-Mode. The system automatically detects whether a user qualifies for E-Mode based on the assets in their loan: * **Single collateral + single debt** that matches an E-Mode pair → E-Mode cap applies * **Multiple collateral or debt assets** → standard pool-wide caps apply ### When You CAN Access E-Mode Using the example above (SOL/USDC and wBTC/USDC E-Mode pairs): * A loan with **only SOL supplied** can borrow USDC up to the SOL/USDC E-Mode cap * A loan with **only wBTC supplied** can borrow USDC up to the wBTC/USDC E-Mode cap ### When You CANNOT Access E-Mode E-Mode Caps support **single-collateral, single-debt combinations only**. Any position that does not contain exactly one collateral and one debt asset within an E-Mode grouping cannot access E-Mode: * A loan with **both SOL and wBTC supplied** cannot borrow PYUSD via E-Mode — the position has multiple collateral assets * A loan with **SOL supplied and USDC already borrowed** cannot additionally borrow PYUSD via the SOL/PYUSD E-Mode — the position already has debt outside the E-Mode pair * A loan with **SOL and another collateral supplied** cannot access any SOL-based E-Mode ### Accessing E-Mode with Existing Positions If you want to access E-Mode borrow capacity but your current loan contains assets outside the E-Mode pair, you have two options: 1. **Remove non-E-Mode assets** from the position (repay other debts, withdraw other collateral) 2. **Open a separate loan** from a different wallet dedicated to the E-Mode pair ## Why This Matters for Risk Management E-Mode Caps transform how the protocol manages collateral risk: ### Targeted Scaling High-quality collateral pairs (SOL/USDC, JitoSOL/SOL) can be scaled aggressively because the liquidity and correlation characteristics are well-understood. Low-quality pairs can be capped tightly or excluded entirely. The protocol grows where it's safe, and restricts where it's risky. ### Precise Liquidation Sizing Because each pair has its own cap, the maximum position size for each pair is known. This allows [market risk analysis](/risk/market-risk) to verify — per pair — that the maximum position can be liquidated profitably given the collateral's specific liquidity profile. Pool-wide caps cannot provide this guarantee because the maximum position could use any collateral. ### Risk Isolation If a specific collateral asset deteriorates (liquidity drops, volatility spikes), only the E-Mode cap for that pair needs to be adjusted. Other pairs are unaffected. This provides surgical risk control without disrupting the broader market. ### Correlation-Aware Parameterization Correlated pairs (e.g., JitoSOL/SOL) can have higher E-Mode caps because the collateral and debt move together — the LTV ratio is inherently stable. Uncorrelated pairs (e.g., SOL/USDC) need more conservative caps because a SOL crash directly impairs the collateral while leaving the debt unchanged. This distinction — which pool-wide caps cannot make — is central to capital-efficient lending with sound risk management. ## Interaction with Other Safeguards E-Mode Caps operate alongside other risk mechanisms: * **[Daily caps](/risk/safeguards/daily-caps):** Even within an E-Mode pair, daily caps limit how quickly new positions can be built * **Supply and borrow caps:** Global per-reserve limits still apply — E-Mode caps provide additional granularity within those limits * **LTV limits:** Each E-Mode pair can have its own LTV parameters, reflecting the specific risk profile of that collateral/debt combination * **[Auto-deleverage](/risk/safeguards/auto-deleverage):** If conditions deteriorate for a specific collateral, auto-deleverage can target positions in that E-Mode pair specifically # Interest Rate Model Source: https://docs.kamino.com/risk/safeguards/interest-rates How Kamino's poly-linear interest rate curve manages liquidity risk and maintains withdrawal availability Interest rates are the protocol's primary defense against liquidity risk — the risk that lenders cannot withdraw because all supply is being borrowed. The interest rate model creates automatic economic pressure that prevents utilization from reaching 100%, ensuring that lenders can always access their funds. ## What Liquidity Risk Means Liquidity risk in a lending protocol is distinct from insolvency risk. When utilization reaches 100% — all deposited tokens are borrowed — lenders cannot withdraw. This does not cause financial loss. In fact, 100% utilization produces the highest possible interest rates for lenders. But it temporarily prevents withdrawals until borrowers repay or new supply arrives. While not catastrophic, extended high utilization is suboptimal: * Lenders who need to access their funds are locked out * Lending Vault curators cannot rebalance allocations * New deposits that could bring utilization down are discouraged (why deposit if you might get locked?) The interest rate model is designed to make 100% utilization economically unsustainable — rates spike so aggressively that borrowers are compelled to repay and new lenders are attracted by the elevated yields. ## The Poly-Linear Curve Kamino employs a **poly-linear interest rate curve** — a piecewise linear function that maps utilization to interest rates with configurable breakpoints (knot points). The curve is designed with a sharp "kink" at the target utilization level: * **Below target utilization:** Rates increase gradually. Borrowing is encouraged, and rates are competitive. * **Above target utilization:** Rates increase steeply. Borrowing becomes expensive rapidly, creating strong economic pressure to repay. This kink structure ensures that utilization naturally gravitates toward the target level. If utilization exceeds the target, the interest rate spike makes borrowing prohibitively expensive — borrowers repay, utilization drops back to target. If utilization is well below target, low rates attract borrowers until utilization rises. ## Borrow Rate Formula The current borrowing rate is determined by interpolating between configured knot points on the curve: ``` Bₜ = B_F + (B_C - B_F) / (U_C - U_F) × (Uₜ - U_F) ``` Where: | Variable | Definition | | - | - | | `Bₜ` | Current borrow interest rate | | `B_C` | Borrow rate at the ceiling utilization knot point | | `B_F` | Borrow rate at the floor utilization knot point | | `Uₜ` | Current utilization rate | | `U_C` | Utilization rate at the ceiling knot point | | `U_F` | Utilization rate at the floor knot point | **Example:** A typical stablecoin curve might have: * Floor knot: 80% utilization → 5% borrow rate * Ceiling knot: 95% utilization → 150% borrow rate At 85% utilization (slightly above target): ``` Bₜ = 0.05 + (1.50 - 0.05) / (0.95 - 0.80) × (0.85 - 0.80) Bₜ = 0.05 + 1.45 / 0.15 × 0.05 Bₜ = 0.05 + 0.483 Bₜ ≈ 53.3% ``` The rate jumps dramatically once utilization exceeds the floor knot point — this is the "kink" that makes overcrowded reserves self-correcting. ## Supply Rate Formula The supply rate — what lenders earn — is derived from the borrow rate: ``` Sₜ = Uₜ × Bₜ × (1 - Rₜ) ``` Where: | Variable | Definition | | - | - | | `Sₜ` | Current supply interest rate | | `Uₜ` | Current utilization rate | | `Bₜ` | Current borrow interest rate | | `Rₜ` | Reserve factor (protocol take rate) | The supply rate is always lower than the borrow rate because: 1. **Utilization \< 100%:** Not all supply is being borrowed, so interest income is distributed across a larger base 2. **Reserve factor:** A portion of the interest goes to the protocol treasury **Example:** Continuing from above with 85% utilization, 53.3% borrow rate, and 15% reserve factor: ``` Sₜ = 0.85 × 0.533 × (1 - 0.15) Sₜ = 0.85 × 0.533 × 0.85 Sₜ ≈ 38.5% ``` Lenders earn 38.5% APY — a significant yield that attracts new deposits and reduces utilization. ## Target Utilization The Risk Council calibrates curve parameters to achieve a target utilization for each asset. Target utilization varies by asset class: | Asset Class | Typical Target Utilization | Rationale | | - | - | - | | **Stablecoins** (USDC, USDT) | 80-90% | High demand, predictable repayment patterns, low volatility | | **Major assets** (SOL, ETH) | 60-75% | Moderate demand, need more withdrawal buffer during volatility | | **Volatile assets** | 40-60% | Lower demand, need substantial buffer for rapid deleveraging | Higher target utilization means more capital efficiency (more of the deposited supply is earning interest). Lower target utilization means more liquidity buffer (lenders are more likely to be able to withdraw at any time). The curve parameters are set such that the equilibrium utilization — where borrowing demand balances with the interest rate — naturally settles near the target. ## Reserve Factor The reserve factor is the protocol's take rate — the percentage of interest income that accrues to the Kamino treasury rather than being distributed to lenders. This serves as: * **Protocol revenue:** Funds operations, development, and potential future insurance mechanisms * **Rate buffer:** A small reduction in lender yield in exchange for protocol sustainability Reserve factors are typically in the 10-20% range, varying by asset and market. Higher reserve factors reduce lender yield but increase protocol revenue; lower reserve factors maximize lender yield but reduce protocol sustainability. ## How the Curve Self-Corrects The interest rate model creates a negative feedback loop that maintains utilization near target: 1. **Utilization rises above target** → borrow rates spike → borrowers repay (expensive to hold debt) → new lenders deposit (yields are attractive) → utilization falls back to target 2. **Utilization falls below target** → borrow rates drop → new borrowers enter (cheap to borrow) → some lenders withdraw (yields are low) → utilization rises back to target This self-correcting property means the protocol does not need active management to maintain healthy utilization under normal conditions. The curve does the work automatically. ## When the Curve Isn't Enough In extreme scenarios, the interest rate curve alone may not prevent prolonged high utilization: * **Market-wide stress:** During a crash, borrowers may be unable to repay (their collateral is losing value), even though rates are high * **Intentional utilization attacks:** An attacker could borrow the entire supply and hold it, paying the high interest rate, to prevent other users from withdrawing For these edge cases, other safeguards intervene: * **[Daily caps](/risk/safeguards/daily-caps)** prevent rapid utilization increases * **[Auto-deleverage](/risk/safeguards/auto-deleverage)** can be triggered to forcibly unwind positions * **Supply caps** limit total deposits, bounding the maximum amount at risk The interest rate model is the first line of defense — it handles 99%+ of utilization management automatically. The other safeguards are backstops for the remaining edge cases. # Security Audits Source: https://docs.kamino.com/security/audits Complete inventory of all security audits conducted on Kamino's smart contracts Kamino has completed 20 external security reviews across all major smart contract components — 15 traditional security audits, [4 formal verifications](/security/formal-verification), and [fuzzing campaigns](/security/fuzzing). Audits are conducted by independent security teams before and after every major launch, with rolling code reviews for ongoing changes. Every report is published publicly. > [!TIP] > > **Found something?** If you discover a vulnerability while reviewing these reports, report it through Kamino's [Bug Bounty program](/security/bug-bounty) on Sherlock for rewards up to 1,000,000 USDC. > [card] 20 Security Reports > [card] 6 Independent Firms > [card] 0 Critical Vulnerabilities ## Audit Firms Kamino engages multiple specialized security firms, each with distinct methodologies and areas of expertise: * **OtterSec** — Solana-native security firm specializing in manual code review and formal verification of Rust/Anchor programs * **Sec3** — Automated and manual auditing with deep Solana program analysis tooling * **Offside Labs** — Independent security research firm focused on DeFi protocol auditing * **Certora** — Formal verification specialists using symbolic execution and mathematical provers * **Ackee Blockchain** — Fuzzing and automated testing using their proprietary Trident framework * **RX Security** — Smart contract security auditing Using multiple firms ensures that no single auditor's blind spots carry through. Different methodologies — manual review, automated analysis, fuzzing, and formal verification — each catch different classes of bugs. ## Audits by Component ### Kamino Lend The core lending and borrowing smart contract — the highest-stakes component. | Date | Firm | Link | | - | - | - | | 6 February 2025 | Sec3 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_klend_sec3.pdf) | | 6 September 2023 | OtterSec | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_lend_ottersec.pdf) | | 3 July 2023 | RX Security | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_lend_rx.pdf) | ### Kamino Earn Vaults Vault contracts that manage depositor funds across lending markets. | Date | Firm | Link | | - | - | - | | 12 April 2025 | Offside Labs | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_vault_offside_labs.pdf) | | 6 February 2025 | Sec3 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_vault_sec3.pdf) | | 9 December 2024 | OtterSec | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_vault_osec.pdf) | ### Scope Oracle Kamino's proprietary oracle aggregator that ingests and validates price feeds. | Date | Firm | Link | | - | - | - | | 16 December 2024 | Sec3 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_scope_sec3.pdf) | | 16 December 2023 | OtterSec | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_scope_ottersec.pdf) | | 8 December 2023 | Offside Labs | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_scope-offside_labs.pdf) | ### Limit Orders (LIMO) Zero-fee limit order contracts. | Date | Firm | Link | | - | - | - | | 29 January 2025 | Sec3 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_limo_audit_sec3.pdf) | | 29 November 2024 | Offside Labs | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_limo_audit_offside_labs.pdf) | | 7 November 2024 | OtterSec | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_limo_audit_ottersec.pdf) | ### Liquidity Vaults Automated liquidity provisioning contracts. | Date | Firm | Link | | - | - | - | | 14 November 2023 | OtterSec | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_liquidity_audit_ottersec.pdf) | ### Farms Reward distribution and farming contracts. | Date | Firm | Link | | - | - | - | | 8 December 2023 | Offside Labs | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_farms-offside_labs.pdf) | | 13 October 2023 | OtterSec | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_farms_ottersec.pdf) | ## Rolling Code Reviews Point-in-time audits catch issues at a snapshot. But code evolves continuously — new features, parameter changes, and optimizations are deployed between scheduled audits. To close this gap, Kamino maintains ongoing code review contracts with security teams. New pull requests are reviewed by independent security researchers before they reach production. This ensures that every code change — not just major releases — receives external scrutiny. ## Public Audit Repository All 20 security reports — including audit, formal verification, and fuzzing reports — are published publicly. Anyone can download and review them. [View all audit reports on GitHub →](https://github.com/Kamino-Finance/audits) # Bug Bounty Source: https://docs.kamino.com/security/bug-bounty Kamino's bug bounty program on Sherlock, with rewards up to 1,000,000 USDC Security / Bug Bounty Live on Sherlock # Bug Bounty Put your security expertise to the test. Get rewarded for responsibly disclosing vulnerabilities in eligible smart contracts and applications. Rewards up to 1,000,000 USDC [View bounty on Sherlock ↗](https://audits.sherlock.xyz/bug-bounties/433) Rewards depend on demonstrated impact and program eligibility. 01 ## [Review the Scope](https://audits.sherlock.xyz/bug-bounties/433?tab=scope) Check eligible assets, impacts, and program exclusions. 02 ## [Reproduce Safely](https://audits.sherlock.xyz/bug-bounties/433?tab=rewards) Demonstrate a realistic exploit in an authorized test environment. 03 ## [Report Privately](https://audits.sherlock.xyz/bug-bounties/433?tab=submission) Submit your findings and evidence through Sherlock. ## Explore the Scope > [card] [KLend](https://github.com/kamino-finance/klend) > > Lending and borrowing > [card] [KVault](https://github.com/kamino-finance/kvault) > > Lending vaults > [card] [Kamino Liquidity](https://github.com/Kamino-Finance/kliquidity-sdk) > > Automated liquidity > [card] [KFarms](https://github.com/kamino-finance/kfarms) > > Rewards infrastructure > [card] [Scope](https://github.com/kamino-finance/scope) > > Oracle infrastructure > [card] [Web and App](https://kamino.com) > > kamino.com and app.kamino.finance ## Research Resources > [card] [Security Audits](/security/audits) > > Review published audits and verification reports > [card] [Source Repositories](https://github.com/Kamino-Finance) > > Explore Kamino's public code and SDKs > [!NOTE] > > The [Sherlock program rules](https://audits.sherlock.xyz/bug-bounties/433) govern eligibility, rewards, and submissions. Kamino does not set or override reward calculations, exclusions, or disclosure terms independently of the Sherlock platform. # Formal Verification Source: https://docs.kamino.com/security/formal-verification Mathematical proofs of correctness for Kamino's core smart contracts Formal verification is fundamentally different from auditing. Where an audit is a human-driven review that checks for known vulnerability patterns, formal verification uses mathematical provers to exhaustively verify that specific properties hold for *all possible inputs and states* — not just the ones a human thinks to test. If a property is formally verified, it is mathematically guaranteed to hold. Kamino has completed 4 formal verifications on its most critical contracts. ## Verified Contracts | Component | Firm | Date | Link | | - | - | - | - | | Kamino Lend | OtterSec | 6 October 2025 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_lend_osec_formal_verification.pdf) | | Kamino Earn Vaults | Certora | 27 June 2025 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_vault_certora.pdf) | | Kamino Lend | Certora | 13 May 2025 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_lend_certora.pdf) | | Kamino Limit Orders | Certora | 21 February 2025 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_limo_audit_formal_verification_certora.pdf) | ## What Was Proved For Kamino Lend, the Certora Prover used symbolic execution to verify two critical invariants: ### Reserve Solvency Invariant The number of issued shares (cTokens representing depositor claims) must always be less than or equal to the number of underlying assets held by the reserve. This means the protocol cannot create claims on liquidity that doesn't exist. No sequence of transactions — deposits, withdrawals, borrows, repayments, liquidations, or any combination — can violate this property. ### Share Value Monotonicity The ratio of liquidity to collateral supply must remain non-decreasing across all transactions. In practical terms: no user operation should ever decrease the value of a depositor's share. Interest accrues, share value goes up — but it should never go down as a result of protocol operations. This property ensures that depositors cannot be diluted by any transaction sequence. ## Zero Critical Vulnerabilities Across all 4 formal verifications, no critical invariant violations were identified in the core lending, liquidation, or vault mechanics. The reserve solvency and share value invariants hold unconditionally. ## How Certora's Prover Works The Certora Prover translates smart contract code into a mathematical model and then uses SMT (Satisfiability Modulo Theories) solvers to check whether any execution path can violate a specified property. Unlike testing, which checks specific inputs, the prover checks all possible inputs simultaneously. If the prover cannot find any counterexample, the property is proven to hold. For Kamino, the properties were specified as invariants — conditions that must be true before and after every possible transaction. The prover then exhaustively searches for any transaction or sequence of transactions that could violate them. [Read the full Certora blog post on Kamino Lend verification →](https://www.certora.com/blog/securing-kamino-lending) # Fuzzing & Testing Source: https://docs.kamino.com/security/fuzzing Automated fuzzing campaigns and verifiable builds for Kamino's smart contracts Fuzzing discovers vulnerabilities by generating millions of random or semi-random inputs and verifying that the system behaves correctly under all of them. Unlike unit tests that validate known scenarios and formal verification that proves specific properties, fuzzing explores the unexpected — edge cases, race conditions, and interaction sequences that developers did not anticipate. Fuzzing is particularly valuable for smart contracts, where the combinatorial space of possible transaction sequences is vast and the cost of an undiscovered bug is catastrophic. ## Ackee Blockchain Partnership Kamino partnered with [Ackee Blockchain](https://ackee.xyz/) for an extensive fuzzing campaign on the core lending contracts. Ackee developed [Trident](https://github.com/Ackee-Blockchain/trident), a Rust-based fuzzing framework purpose-built for Solana programs, which they applied to Kamino Lend. | Report | Date | Link | | - | - | - | | Ackee Blockchain Fuzz Tests — Kamino Lend | 22 September 2025 | [View Report](https://github.com/Kamino-Finance/audits/blob/main/kamino_lend_ackee_blockchain_fuzz_tests.pdf) | ## Testing Methodology The fuzzing campaign covered three distinct approaches: ### Instruction Handler Fuzzing The fuzzer generates random sequences of Kamino Lend program instructions — deposits, withdrawals, borrows, repayments, liquidations — in arbitrary orders with arbitrary parameters. Each sequence is executed against the program, and the fuzzer checks whether the program panics, produces unexpected state, or violates any assertion. This approach tests the program's robustness against inputs that no human tester would think to try. It catches issues like integer overflows, underflows, unhandled edge cases in account validation, and unexpected interactions between instructions. ### Invariant Testing Beyond checking for crashes, invariant testing verifies that protocol-level properties hold after every instruction in every sequence. For Kamino Lend, invariants include: * Reserve balances remain consistent with tracked deposits and borrows * Collateral ratios are correctly computed after any operation * Interest accrual does not produce negative values or overflow * Liquidation eligibility is correctly determined regardless of prior operations If any randomly generated sequence violates an invariant, the fuzzer captures the minimal reproduction case for debugging. ### Regression Detection As the codebase evolves, fuzzing ensures that fixes and new features do not reintroduce previously resolved issues. The fuzzer maintains a corpus of interesting inputs from prior campaigns and re-runs them against new code versions to detect regressions. ## Campaign Results The fuzzing campaign executed millions of instruction sequences over a months-long period. Results: * **Zero insolvency risks identified** — no sequence of instructions could create a state where the protocol's liabilities exceeded its assets * **Zero economic bugs** — no sequence could extract more value than deposited, bypass collateral requirements, or manipulate interest calculations * **Integrated into ongoing development** — fuzzing is now a permanent part of Kamino's security stack, run continuously as part of the development and review process ## Verifiable Builds A separate but related concern: how do users know that the program deployed on-chain is the same code that was audited? A compromised deployment pipeline could insert malicious code after auditing. Verifiable builds solve this by cryptographically linking the deployed on-chain bytecode to the audited source code. Anyone can independently rebuild the program from source and verify that the hash matches the deployed program. If they don't match, the discrepancy is immediately detectable. Kamino Lend, Vaults, and Farms are all verifiable builds. Verification is available on Solscan: | Program | Solscan | | - | - | | Kamino Lend | [KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD](https://solscan.io/account/KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD) | | Kamino Vaults | [kvauTFR8qm1dhniz6pYuBZkuene38GZMyALHMLo2EoP](https://solscan.io/account/kvauTFR8qm1dhniz6pYuBZkuene38GZMyALHMLo2EoP) | | Kamino Farms | [FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr](https://solscan.io/account/FarmsPZpWu9i7Kky8tPN37rs2TpmMrAZrC7S7vJa91Hr) | This means the deployed code is not just audited — it is independently verifiable by anyone, at any time, without trusting Kamino's deployment process. # Security Source: https://docs.kamino.com/security/index Kamino's layered security approach: audits, formal verification, and continuous monitoring > [card] 20 Security Reports > > Audits, formal verifications, and fuzzing from 6 independent firms > [card] 4 Formal Verifications > > Mathematical proofs of correctness for core lending, vault, and order contracts > [card] \$0 Bad Debt > > 3+ years live, \$175M+ in liquidations processed with zero losses ## Defense in Depth Kamino is a credit protocol — the stakes are existential. A single exploit or risk management failure could result in catastrophic loss for lenders. Security is not a single checkpoint but a continuous, multi-layer process where each layer operates independently. If any one fails, the others remain. This defense-in-depth approach spans the full stack: smart contract correctness, oracle reliability, operational infrastructure, protocol-level safeguards, market risk monitoring, and economic stress testing. The protocol has operated since September 2022 without a single security incident, bad debt event, or oracle exploit. This track record is not the result of any one measure — it is the product of all layers working together. ## Security Stack > [card] [Security Audits](/security/audits) > > 15 independent code audits across all smart contracts, conducted by OtterSec, Sec3, Offside Labs, and RX Security. > [card] [Formal Verification](/security/formal-verification) > > 4 formal verifications providing mathematical proofs that critical invariants hold — not probabilistic testing, but exhaustive verification across all possible states. > [card] [Fuzzing & Testing](/security/fuzzing) > > Months-long automated fuzzing campaigns using Ackee Blockchain's Trident framework, with millions of instruction sequences tested. Plus verifiable on-chain builds. > [card] [Oracle Architecture](/security/oracles) > > Kamino's proprietary Scope oracle aggregator combines feeds from Chainlink, Pyth, Switchboard, and Redstone with TWAP/EWMA smoothing and price band validation. > [card] [Infrastructure & Redundancy](/security/infrastructure) > > No single point of failure across RPC providers, cloud infrastructure, oracle cranks, and liquidation bots. Full real-time monitoring with anomaly escalation. > [card] Open Source > > All core contracts are publicly available on GitHub, enabling community review, peer security analysis, and independent verification. > [card] [Protocol Safeguards](/risk/safeguards/auto-deleverage) > > Auto-deleverage, daily caps, E-Mode caps, and interest rate controls provide protocol-level defense against market stress and outsized risk. > [card] [Bug Bounty](/security/bug-bounty) > > Up to 1,000,000 USDC for responsibly disclosed vulnerabilities across Kamino's smart contracts and web applications, hosted on Sherlock. ## Open Source Contracts All core smart contracts are fully open source. Anyone can inspect the code, verify deployments against audited source, and contribute to identifying issues. | Repository | Description | | - | - | | [kamino-finance/klend](https://github.com/kamino-finance/klend) | Kamino Lend — core lending and borrowing | | [kamino-finance/kvault](https://github.com/kamino-finance/kvault) | Kamino Earn Vaults | | [Kamino-Finance/limo](https://github.com/Kamino-Finance/limo) | LIMO — limit orders | | [kamino-finance/scope](https://github.com/kamino-finance/scope) | Scope — oracle aggregator | | [kamino-finance/kfarms](https://github.com/kamino-finance/kfarms) | Kamino Farms | > [!NOTE] > > The information on this page is provided for informational purposes only. While Kamino implements rigorous security measures, no system is fully immune to risk. Refer to the [Terms & Conditions](https://kamino.com/terms) for full details. # Infrastructure & Redundancy Source: https://docs.kamino.com/security/infrastructure Operational security: redundancy, monitoring, liquidation infrastructure, and stress testing Smart contract security is necessary but not sufficient. A lending protocol also depends on off-chain infrastructure — RPC nodes, oracle update bots, liquidation bots, and cloud services — that must function correctly under stress. A single point of failure in any of these systems can delay liquidations, stale price feeds, or prevent users from interacting with the protocol during critical moments. Kamino runs redundant instances of every critical off-chain component, with real-time monitoring and automatic failover. ## Redundancy Architecture ### RPC Providers Kamino's infrastructure connects to multiple independent Solana RPC providers. If one provider experiences downtime, degraded performance, or rate limiting, traffic automatically fails over to alternatives. No single RPC outage can halt protocol operations. ### Cloud Providers Infrastructure spans multiple cloud providers. A single cloud provider outage — whether regional or global — does not take down Kamino's off-chain systems. Critical services are deployed across independent providers with no shared failure domain. ### Oracle Cranks Oracle feeds on Solana require "cranks" — transactions that push updated prices on-chain. Kamino operates multiple independent crankers that push Scope oracle updates. If one cranker fails, goes offline, or is rate-limited, others continue to push fresh prices. Price feed liveness does not depend on any single operator. ### Liquidation Bots Multiple independent liquidator bots monitor positions continuously. Kamino's liquidation system is **permissionless** — anyone can run a liquidation bot. There is no single operator responsible for liquidations. This creates a competitive market: if one bot misses a liquidation opportunity, another will capture it. The result: during the [February 2026 stress event](/risk), 55,649 liquidation events were processed across 30,030 wallets in 48 hours — with zero bad debt. The liquidation infrastructure performed under real-world conditions that far exceeded normal operating parameters. ## Monitoring & Alerting Kamino maintains full transparency in what is monitored and how anomalies are escalated. ### What Is Monitored in Real-Time | Metric | What it indicates | | - | - | | **Utilization rates per reserve** | How close each market is to full utilization (100% = lenders cannot withdraw) | | **LTV distributions across all positions** | How many positions are approaching liquidation thresholds | | **Oracle staleness** | Whether price feeds are being updated within expected intervals | | **Oracle deviation** | Whether different providers are reporting consistent prices | | **Cap utilization** | How close supply, borrow, and daily caps are to their limits | | **Liquidation-at-risk metrics** | What percentage of positions would be liquidated at various price shock levels | | **Vault allocation changes** | Whether Earn Vault curators are making unusual reallocation decisions | ### Escalation Process Anomalies detected by monitoring trigger review and potential action. The response path depends on severity: * **Utilization approaching targets:** Interest rate curves are designed to self-correct (higher rates incentivize repayment and new supply). Monitoring tracks whether the curve is working as intended. * **Oracle staleness or deviation:** Scope's multi-provider architecture provides automatic fallback. Persistent staleness across providers triggers manual review. * **Positions clustering near liquidation thresholds:** Risk analysis determines whether parameter adjustments (cap reductions, LTV changes) are warranted. * **Extreme market conditions:** The Risk Council can trigger emergency measures including cap reductions and [auto-deleverage](/risk/safeguards/auto-deleverage). ## Liquidation Infrastructure Liquidation on Kamino is a permissionless, competitive process. When a position's LTV exceeds the liquidation threshold, any entity can submit a liquidation transaction. The liquidator provides the debt token, receives collateral at a small discount (the liquidation bonus), and sells the collateral to realize profit. ### How It Scales on Solana Solana's architecture introduces specific considerations for liquidation at scale: * **Priority fees:** During congestion, liquidators compete via priority fees to have their transactions included. This ensures liquidations execute even when the network is busy. * **Compute limits:** Each Solana transaction has a compute unit limit, which constrains how many operations can occur in a single transaction. Large liquidations may require multiple transactions. * **Transaction ordering:** Solana's leader schedule means transaction inclusion depends on the current validator. Multiple independent liquidators submitting to multiple RPC providers increases the probability of timely inclusion. ### Track Record > [card] \$175M+ > > Total liquidation volume processed > [card] 130,000+ > > Individual liquidation events executed > [card] \$0 > > Bad debt across all liquidation events ## Emergency Measures When market conditions deteriorate beyond normal parameters, several levers are available: * **Cap reductions:** Supply and borrow caps can be lowered to prevent further exposure buildup * **Auto-deleverage:** The [auto-deleverage mechanism](/risk/safeguards/auto-deleverage) can be triggered to systematically unwind risky positions * **Daily cap enforcement:** [Daily caps](/risk/safeguards/daily-caps) limit the rate at which exposure can change, even during extreme conditions * **Market freezes:** In extreme scenarios, individual reserves can be frozen to prevent further interaction until conditions stabilize These measures are not routine. They represent last-resort interventions designed to protect lenders when market conditions exceed the protocol's normal operating parameters. > [!NOTE] > > Stress event analyses are published to the Kamino governance forum after every significant market event. Historical reports are available at [gov.kamino.finance](https://gov.kamino.finance). # Scope Aggregator Source: https://docs.kamino.com/security/oracles/index Kamino's proprietary on-chain oracle aggregator: cross-validated Chainlink and Pyth Pro feeds with independent on-chain validation Oracles are the most critical attack surface in DeFi lending. Every LTV calculation, every liquidation decision, every interest rate update depends on accurate price data. A compromised or stale oracle feed can trigger improper liquidations, enable collateral drain exploits, or create bad debt. Historically, oracle manipulation has been the single most common vector for DeFi exploits — responsible for billions in losses across protocols like Euler, Mango Markets, and Cream Finance. Kamino did not rely on a single off-the-shelf oracle solution. Instead, it built **Scope** — a proprietary on-chain oracle aggregator — from the ground up. > [card] 3 Dedicated Audits > > Audited by Sec3, OtterSec, and Offside Labs — plus oracle coverage in broader Lend and Vault audits > [card] \$19.33B Volume > > Total volume processed through Scope price feeds > [card] 0 Oracle Exploits > > Zero oracle-related exploits since launch ## What Scope Is Scope is an on-chain program deployed on Solana that aggregates price data from independent premium oracle networks into a single, validated price feed. It is not a pass-through: Scope applies its own validation rules before accepting any price, and only publishes prices that pass all checks. The key insight behind Scope is that no single oracle provider is reliable enough to secure billions in deposits. Scope draws on two independent, institutional-grade networks whose strengths and failure modes do not overlap: * Different update models and latency profiles * Different aggregation methodologies * Independent infrastructure and operators * Different manipulation-resistance characteristics By cross-validating these independent feeds and applying its own checks, Scope achieves a level of reliability that no single provider can match. ## Architecture Scope operates as a Solana program that: 1. **Ingests prices** from two independent premium oracle networks (Chainlink Data Streams and Pyth Pro) 2. **Validates each price** against a preset of rules — staleness checks, deviation checks, cross-provider consistency 3. **Selects the best price** dynamically based on freshness, consistency with other providers, and validation status 4. **Publishes the validated price** to a single on-chain account that Kamino's lending and vault contracts read from If a provider's feed goes stale, deviates significantly from other providers, or fails a validation check, Scope automatically falls back to the next-best source. This self-healing behavior means that an outage or anomaly in any single provider does not compromise price accuracy. ## Multi-Price Oracle System The most significant upgrade to Scope's architecture is the **Multi-Price Oracle System** — a fundamental evolution from selecting a single "best" price to continuously aggregating and cross-validating all available high-quality sources in real time. This system eliminates any remaining dependence on a single data provider, dynamically selects the freshest valid price at the moment of each transaction, and self-heals during provider downtime or deviation without manual intervention. The Multi-Price Oracle System was double-audited by **Certora** and **Offside Labs** before deployment. For details on how this system reduces oracle pricing risk, see [Oracle Pricing Risk](/risk/asset-risk/oracle-pricing#multi-price-oracle-system). ## Oracle Providers Scope is built on two independent, institutional-grade decentralized oracle networks: | Provider | Type | Strengths | | - | - | - | | **Chainlink Data Streams** | Pull-based decentralized oracle | High-frequency, low-latency market data on demand; industry-standard infrastructure securing hundreds of billions across chains | | **Pyth Pro** | Pull-based high-frequency oracle | Sub-second updates, native Solana integration, confidence intervals | Both are pull-based: prices are requested on-demand rather than pushed on fixed heartbeat intervals, so the protocol reads the freshest available price at the exact moment it is needed. Chainlink Data Streams underwent extensive mainnet testing for multiple weeks before integration, demonstrating consistently strong results in accuracy and latency against existing feeds. For each asset on Kamino, Scope cross-validates both providers in real time. The protocol does not depend on any single provider: if one deviates or goes stale, the other continues to provide accurate pricing, and Scope's own validation layer rejects any price that fails its checks before it is published. ## Open Source Scope is fully open source. The smart contract code, aggregation logic, and validation rules are all publicly available for review: * **Smart contract:** [github.com/Kamino-Finance/scope](https://github.com/Kamino-Finance/scope) * **TypeScript SDK:** [github.com/Kamino-Finance/scope-sdk](https://github.com/Kamino-Finance/scope-sdk) Anyone can inspect how prices are aggregated, what validation rules are applied, and how fallback selection works. ## Oracle Audits Scope has been independently audited 3 times by 3 different firms. In addition, oracle integration is reviewed as part of every Kamino Lend and Vault audit: | Report | Firm | Date | | - | - | - | | Sec3 Audit | Sec3 | 16 December 2024 | | OtterSec Audit | OtterSec | 16 December 2023 | | Offside Labs Audit | Offside Labs | 8 December 2023 | Beyond these dedicated Scope audits, the oracle aggregation layer is reviewed as part of every Kamino Lend and Vault audit — meaning oracle security is scrutinized from multiple angles across the protocol's full audit portfolio. # LST Oracles Source: https://docs.kamino.com/security/oracles/lst-oracles How Kamino prices liquid staking tokens using stake rates instead of market prices Liquid staking tokens (LSTs) like JitoSOL, mSOL, and bSOL represent staked SOL plus accumulated staking rewards. Their theoretical value increases monotonically relative to SOL as staking yields accrue each epoch. But their *market* price — the price at which they trade on DEXes — can deviate from this theoretical value due to temporary supply/demand imbalances. Kamino uses a fundamentally different approach to pricing LSTs than most lending protocols. ## The Problem with Market-Price LST Oracles The amount of LSTs deposited across Solana DeFi far outweighs the liquidity available in DEX pools. This creates a structural vulnerability: even moderate selling pressure on an LST can cause a temporary market depeg — where the LST trades below its theoretical value. If a lending protocol uses market price to value LST collateral, a temporary depeg would reduce the collateral value of every LST position on the protocol. Positions that were healthy moments before could suddenly breach their liquidation threshold — not because of any real loss of value, but because of a transient liquidity event in a DEX pool. For products like [Multiply](/products/multiply), where users leverage LSTs against SOL, a market-price oracle would mean that every LST depeg — however brief — triggers unnecessary liquidations. This creates a cascade: liquidations produce more selling pressure, deepening the depeg, triggering more liquidations. ## Kamino's Approach: Stake-Rate Pricing Instead of using market price, Kamino prices LSTs using the **stake rate** — the ratio of SOL staked in the LST's validator pool to the total LST tokens minted: ``` LST Price = SOL_staked / LST_minted ``` Each Solana epoch (\~2 days), the amount of SOL in the staking pool increases due to: 1. **Proof of Stake emissions** — validators earn SOL rewards for securing the network 2. **Transaction fees** — a portion of network transaction fees flows to validators Meanwhile, the number of LST tokens minted remains stable relative to the SOL increase. The result: the stake rate increases monotonically each epoch, and so does the LST price on Kamino. ## What This Protects Against **Market depeg events.** If JitoSOL temporarily trades at 0.95 SOL on a DEX due to a large sell order, Kamino continues to value it at its stake rate (e.g., 1.02 SOL). Positions are not affected. No liquidations are triggered. The temporary market dislocation is irrelevant to the protocol. This protection is especially important for Multiply positions, where users hold leveraged LST/SOL exposure. Without stake-rate pricing, these positions would be perpetually vulnerable to market noise. ## What This Does NOT Protect Against **Smart contract exploits on the LST platform.** If the staking vault underlying an LST suffers a smart contract exploit and SOL is drained, the stake rate would reflect the loss (fewer SOL staked per LST minted). In this scenario, positions on Kamino would correctly be at risk, and liquidations would proceed normally. Stake-rate pricing removes *market noise* risk but does not remove *fundamental* risk. If an LST's backing is genuinely impaired, the oracle will reflect it. ## The Arbitrage Assumption This approach assumes that market arbitrageurs will restore the market price to align with the theoretical stake-rate price. When an LST trades below its theoretical value, arbitrageurs can buy the discounted LST, unstake it for SOL at the stake rate, and profit from the difference. This arbitrage mechanism provides the economic incentive to close any depeg. **Risk:** If arbitrage fails to occur and an LST depeg is sustained — for example, due to a staking pool smart contract issue that prevents unstaking — the protocol may be carrying collateral valued higher than the market is willing to pay. In this scenario, the protocol is at risk of bad debt. If bad debt materializes, losses are socialized among lenders in the affected market. This risk is mitigated by: * Supply caps on individual LSTs (limiting total protocol exposure) * The [Asset Risk Framework](/risk/asset-risk) evaluating each LST's smart contract risk before onboarding * Continuous monitoring of stake pool health and unstaking delays ## Supported LSTs All liquid staking tokens on Kamino use stake-rate pricing, including JitoSOL, mSOL, bSOL, and others. The stake rate is read directly from each LST's on-chain stake pool account — there is no off-chain dependency or oracle delay in the pricing. # Price Protection Source: https://docs.kamino.com/security/oracles/price-protection TWAP, EWMA, and price band mechanisms that defend against oracle manipulation Even with a multi-provider oracle system, individual price feeds can be temporarily manipulated — through flash loans, large market orders, or liquidity pool manipulation. Kamino deploys three complementary protection mechanisms that make oracle exploitation prohibitively expensive. ## TWAP — Time Weighted Average Price A Time Weighted Average Price smooths the price of an asset over a configurable time window. Instead of using the instantaneous spot price, the protocol uses the average price observed over the interval. **Why this matters for security:** Flash loan attacks work by manipulating a price within a single transaction. Because a TWAP reflects the average price over minutes or hours, a single-transaction manipulation has negligible effect on the weighted average. The attacker would need to sustain the manipulated price for the entire TWAP interval — requiring significant capital held at risk for an extended period. For example, if TWAP is configured with a 30-minute window and an attacker manipulates the price for one block (\~400ms), the manipulated price accounts for less than 0.02% of the weighted average. To meaningfully influence the TWAP, the attacker would need to sustain the manipulation continuously for a substantial portion of the window — at which point the capital costs make the attack economically irrational. ## EWMA — Exponentially Weighted Moving Average An Exponentially Weighted Moving Average gives more weight to recent prices while still incorporating historical data. This makes it more responsive to genuine market movements than a simple TWAP, while still smoothing out short-term manipulation. **Why both TWAP and EWMA?** They are complementary: * **TWAP** is more resistant to sustained manipulation (each time period has equal weight) * **EWMA** is more responsive to legitimate price changes (recent prices matter more) Using both allows the protocol to balance between responsiveness and manipulation resistance. Rapid genuine price movements are reflected more quickly through EWMA, while manipulation attempts are filtered by TWAP. ## Price Bands Each stable or soft-pegged asset on Kamino has a **price band** — a range within which the smart contract expects the price to fall. If a reported price falls outside this band, it is rejected outright. **How it works for USD stablecoins:** A token like USDC might have a price band of ±1% from \$1.00. If the oracle reports a USDC price below \$0.99 or above \$1.01, the price is rejected and the protocol falls back to the previous valid price or an alternative provider. **How it works for SOL-pegged assets:** For tokens pegged to SOL (like liquid staking tokens in non-stake-rate mode), price bands are expressed relative to the SOL price rather than a fixed dollar amount. **What this prevents:** * **Flash crash exploits:** An attacker who temporarily crashes a stablecoin price on a DEX cannot use that manipulated price to trigger improper liquidations on Kamino — the price would be outside the band and rejected. * **Oracle feed corruption:** If an oracle feed malfunctions and reports an obviously incorrect price, the band prevents it from affecting protocol operations. ## How the Mechanisms Interact These three mechanisms form a layered defense: 1. **Price bands** are the first filter — they catch obvious outliers and reject them immediately. This is a coarse but fast check. 2. **TWAP smoothing** absorbs short-term manipulation by averaging over time. Even if a manipulated price passes the band check (e.g., a 0.8% deviation on a stablecoin), the TWAP dilutes its impact. 3. **EWMA smoothing** provides an additional smoothing layer that is more responsive to genuine market movements but still resistant to single-block manipulation. 4. **Multi-provider consensus** (from [Scope](/security/oracles)) provides an independent validation layer — if one provider reports a price that deviates significantly from others, Scope flags the discrepancy. The result: exploiting Kamino's oracle system requires simultaneously manipulating the price across multiple independent oracle providers, sustaining the manipulation for the full TWAP interval, staying within the price band to avoid rejection, and doing all of this profitably after accounting for the capital required. No oracle exploit has ever been successfully executed against Kamino.