bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 15쪽
estReserveDepositLiquidationLtv": "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": []
}
```
<a href="https://github.com/Kamino-Finance/klend-sdk/blob/80f29fcda3ac954b400ceb3000999def487cff5c/src/%40codegen/klend/accounts/Obligation.ts#L81">
<Icon icon="github" />
<span>View Full JSON Obligation</span>
</a>
<Expandable title="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) |
</Expandable>
</Tab>
<Tab title="Rust">
##### Obligation
```rust theme={null}
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: u128
pub borrows: [ObligationLiquidity; 5]
pub borrow_factor_adjusted_debt_value_sf: u128
pub borrowed_assets_market_value_sf: u128
pub allowed_borrow_value_sf: u128
pub unhealthy_borrow_value_sf: u128
pub deposits_asset_tiers: [u8; 8]
pub borrows_asset_tiers: [u8; 5]
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 reserved: [u8; 4]
pub highest_borrow_factor_pct: u64
pub autodeleverage_margin_call_started_timestamp: u64
pub orders: [ObligationOrder; 2]
pub padding_3: [u64; 93]
}
```
<a href="https://github.com/Kamino-Finance/klend/blob/5b37d7522aa070fad87f2fcf30bdf2e19d9e607a/programs/klend/src/state/obligation.rs#L23">
<Icon icon="github" />
<span>View Full Rust Obligation</span>
</a>
<Expandable title="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) |
</Expandable>
</Tab>
</Tabs>
</div>
## Relevant Links
<CardGroup>
<Card title="Fetch Market Data via the API" icon="globe" href="https://api-docs.kamino.com/">
Access market metrics and performance data through REST endpoints.
</Card>
<Card title="Smart contract repository" icon="github" href="https://github.com/Kamino-Finance/klend">
Explore the on-chain program source code and documentation.
</Card>
<Card title="NPM SDK package" icon="npm" href="https://www.npmjs.com/package/@kamino-finance/klend-sdk">
Install the TypeScript SDK to integrate borrowing and lending operations.
</Card>
<Card title="Rust Interface Crate" icon="rust" href="https://crates.io/crates/klend-interface">
Lightweight Rust instruction builder for Kamino Lending operations.
</Card>
<Card title="More Borrow tutorials" icon="book" href="/docs/build/tutorials/borrow/index">
Step-by-step guides for building with Kamino lending markets.
</Card>
</CardGroup>
# Build a Liquidation Bot with KSwap
Source: https://kamino.com/docs/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.
<Tabs>
<Tab title="TypeScript">
<Steps>
<Step>
### Import Dependencies
```typescript theme={null}
import {
createSolanaRpc,
createSolanaRpcSubscriptions,
createKeyPairSignerFromBytes,
sendAndConfirmTransactionFactory,
address,
} from '@solana/kit';
import {
KaminoMarket,
KaminoObligation,
DEFAULT_RECENT_SLOT_DURATION_MS,
} from '@kamino-finance/klend-sdk';
```
</Step>
<Step>
### Set Up RPC and Load Market
```typescript theme={null}
const RPC_ENDPOINT = 'YOUR_RPC_URL';
const WS_ENDPOINT = RPC_ENDPOINT.replace('https://', 'wss://');
const SOL_BTC_MARKET = '7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF';
const rpc = createSolanaRpc(RPC_ENDPOINT);
const rpcSubscriptions = createSolanaRpcSubscriptions(WS_ENDPOINT);
const sendAndConfirm = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
const keypairBytes = new Uint8Array(JSON.parse(process.env.LENDING_USER_SECRET_KEY!));
const liquidator = await createKeyPairSignerFromBytes(keypairBytes);
const market = await KaminoMarket.load(
rpc, address(SOL_BTC_MARKET), DEFAULT_RECENT_SLOT_DURATION_MS,
);
```
<Note>
Kamino operates multiple markets (SOL/BTC, JLP, Altcoins, Prime). A production bot should scan all of them. See [Markets](/docs/products/borrow/markets) for the full list.
</Note>
</Step>
<Step>
### Scan Obligations in Batches
Scan obligations in batches of 100 to avoid out-of-memory on large markets. Use the on-chain LTV methods, not `refreshedStats.loanToValue`, to match the program's liquidation check.
```typescript theme={null}
// Scanning 100k+ obligations in batches takes several minutes.
const currentSlot = await rpc.getSlot().send();
const unhealthy: KaminoObligation[] = [];
let totalScanned = 0;
for await (const batch of market!.batchGetAllObligationsForMarket(currentSlot)) {
totalScanned += batch.length;
batch.forEach((ob) => {
const ltv = ob.loanToValue();
const liqLtv = ob.liquidationLtv();
if (ltv.gte(liqLtv) && ob.refreshedStats.userTotalBorrow.gt(0)) {
unhealthy.push(ob);
}
});
}
console.log(`Found ${unhealthy.length} liquidatable out of ${totalScanned} total`);
```
</Step>
</Steps>
</Tab>
<Tab title="Rust">
<Steps>
<Step>
### Add Dependencies
```toml theme={null}
[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<Instruction>` with required refresh instructions prepended automatically.
</Note>
</Step>
<Step>
### Set Up RPC Client
```rust theme={null}
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.).
</Warning>
</Step>
<Step>
### 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={null}
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::<Obligation>() 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.
</Warning>
</Step>
<Step>
### 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={null}
use klend_interface::Fraction;
let mut liquidatable = Vec::new();
for (pubkey, account) in &accounts {
let obligation = klend_interface::from_account_data::<Obligation>(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>
<Step>
### 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={null}
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<Pubkey> = 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::<HashSet<_>>()
.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<Pubkey, Reserve> = reserve_pubkeys
.iter()
.zip(reserve_accounts.iter())
.filter_map(|(pk, acc)| {
acc.as_ref().and_then(|a| {
from_account_data::<Reserve>(&a.data).ok().map(|r| (*pk, *r))
})
})
.collect();
// Fetch fresh prices from the Scope REST API
let fresh_prices: HashMap<String, f64> = reqwest::blocking::get(
"https://api.kamino.finance/oracles/prices",
)
.ok()
.and_then(|r| r.json::<Vec<OraclePrice>>().ok())
.map(|prices| prices.into_iter()
.filter_map(|p| p.price.parse::<f64>().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());
```
</Step>
</Steps>
</Tab>
</Tabs>
## 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.
<Tabs>
<Tab title="TypeScript">
<Steps>
<Step>
### Load the Obligation
```typescript theme={null}
import { KaminoReserve } from '@kamino-finance/klend-sdk';
import { Address } from '@solana/kit';
const obligation = (await market!.getObligationByAddress(
address('<OBLIGATION_PUBKEY>')
))!;
const resolveReserve = (market: KaminoMarket, reserveAddr: Address) =>
market.getReserveByAddress(reserveAddr) as KaminoReserve | undefined;
```
</Step>
<Step>
### Sort by Priority
Sort deposits by `liquidationThresholdPct` ascending (weakest collateral first) and borrows by `borrowFactorPct` descending (riskiest debt first).
```typescript theme={null}
const deposits = obligation.getDeposits();
const borrows = obligation.getBorrows();
const sortedDeposits = deposits.sort((a, b) => {
const reserveA = resolveReserve(market!, a.reserveAddress)!;
const reserveB = resolveReserve(market!, b.reserveAddress)!;
return reserveA.state.config.liquidationThresholdPct
- reserveB.state.config.liquidationThresholdPct;
});
const sortedBorrows = borrows.sort((a, b) => {
const reserveA = resolveReserve(market!, a.reserveAddress)!;
const reserveB = resolveReserve(market!, b.reserveAddress)!;
return Number(reserveB.state.config.borrowFactorPct)
- Number(reserveA.state.config.borrowFactorPct);
});
```
</Step>
<Step>
### Select the Target Pair
The first entry in each sorted list is the priority target. Reserves with `loanToValuePct == 0` are deposit-only and cannot be seized.
```typescript theme={null}
const targetCollateral = sortedDeposits.find((d) => {
const reserve = resolveReserve(market!, d.reserveAddress);
return reserve && reserve.state.config.loanToValuePct > 0;
});
const targetDebt = sortedBorrows[0];
if (!targetCollateral || !targetDebt) {
console.log('No valid liquidation pair프로젝트로 돌아가기