Skip to main content

df_hyperliquid_core/earn/lending/
state.rs

1//! `allBorrowLendReserveStates`, `borrowLendReserveState` and
2//! `borrowLendUserState`. Figures are the venue's decimal strings; rates and
3//! utilization are fractions (0.05 is 5%). A token is its spot index, from the
4//! caller's `spotMeta`: HYPE is 150 on mainnet and 1105 on testnet.
5
6use crate::client::{ApiError, Transport, info, info_request, user_request};
7use crate::utils::{Address, Dec, Figure, Json};
8use serde::Deserialize;
9
10/// `{"type":"allBorrowLendReserveStates"}`.
11#[must_use]
12pub fn all_reserve_states_request() -> String {
13    info_request("allBorrowLendReserveStates", &[])
14}
15
16/// `{"type":"borrowLendReserveState","token":..}`. A token with no reserve is
17/// answered HTTP 500.
18#[must_use]
19pub fn reserve_state_request(token: u32) -> String {
20    info_request("borrowLendReserveState", &[("token", Json::Number(token.to_string()))])
21}
22
23/// `{"type":"borrowLendUserState","user":..}`.
24#[must_use]
25pub fn user_state_request(user: Address) -> String {
26    user_request("borrowLendUserState", user)
27}
28
29/// Every reserve, as `[token index, state]` pairs.
30pub async fn all_reserve_states(transport: &impl Transport) -> Result<Vec<(u32, ReserveState)>, ApiError> {
31    info(transport, all_reserve_states_request()).await
32}
33
34/// One token's reserve.
35pub async fn reserve_state(transport: &impl Transport, token: u32) -> Result<ReserveState, ApiError> {
36    info(transport, reserve_state_request(token)).await
37}
38
39/// An account's lending positions and health.
40pub async fn user_state(transport: &impl Transport, user: Address) -> Result<UserState, ApiError> {
41    info(transport, user_state_request(user)).await
42}
43
44/// One token's reserve.
45#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
46#[serde(rename_all = "camelCase")]
47#[non_exhaustive]
48pub struct ReserveState {
49    /// What a borrower pays a year.
50    pub borrow_yearly_rate: Dec,
51    /// What a supplier earns a year.
52    pub supply_yearly_rate: Dec,
53    /// The reserve's balance, in the token: what it can still lend. Live it is
54    /// near, but not exactly, supplied less borrowed.
55    pub balance: Dec,
56    /// Borrowed over supplied.
57    pub utilization: Dec,
58    /// In USDC.
59    pub oracle_px: Dec,
60    /// How much of the token's value backs a borrow; 0 where it backs none.
61    pub ltv: Dec,
62    /// Everything supplied to the reserve, in the token (`totalSupplied`).
63    pub total_supplied: Dec,
64    /// Everything borrowed from the reserve, in the token (`totalBorrowed`).
65    pub total_borrowed: Dec,
66}
67
68/// The reserve of `token` among `reserves`.
69#[must_use]
70pub fn reserve(reserves: &[(u32, ReserveState)], token: u32) -> Option<&ReserveState> {
71    reserves.iter().find(|(index, _)| *index == token).map(|(_, reserve)| reserve)
72}
73
74/// An account's lending: a position per token it ever touched, and its
75/// health.
76#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
77#[serde(rename_all = "camelCase")]
78#[non_exhaustive]
79pub struct UserState {
80    /// `[token index, position]` pairs; zero rows stay listed.
81    #[serde(default)]
82    pub token_to_state: Vec<(u32, Position)>,
83    /// The venue's word: `healthy`, `atRisk` (seen live on a portfolio-margin
84    /// account), or `liquidatable`.
85    pub health: String,
86    /// `null` while nothing is borrowed.
87    #[serde(default)]
88    pub health_factor: Option<Figure>,
89}
90
91/// How near liquidation the venue says an account's lending is.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93#[non_exhaustive]
94pub enum Risk {
95    /// `healthy`.
96    Safe,
97    /// `atRisk`, or a word not seen yet: worth a warning.
98    Near,
99    /// `liquidatable`.
100    Liquidatable,
101}
102
103impl UserState {
104    /// The position in `token`; `None` when the account never touched it.
105    #[must_use]
106    pub fn position(&self, token: u32) -> Option<&Position> {
107        self.token_to_state.iter().find(|(index, _)| *index == token).map(|(_, position)| position)
108    }
109
110    /// The positions that hold or owe anything.
111    pub fn positions(&self) -> impl Iterator<Item = (u32, &Position)> {
112        self.token_to_state
113            .iter()
114            .filter(|(_, position)| !position.supply.value.is_zero() || !position.borrow.value.is_zero())
115            .map(|(token, position)| (*token, position))
116    }
117
118    /// What is supplied of `token` now, interest in; zero for none.
119    #[must_use]
120    pub fn supplied(&self, token: u32) -> Dec {
121        self.position(token).map_or(Dec::ZERO, |position| position.supply.value)
122    }
123
124    /// What is owed of `token` now, interest in; zero for none.
125    #[must_use]
126    pub fn borrowed(&self, token: u32) -> Dec {
127        self.position(token).map_or(Dec::ZERO, |position| position.borrow.value)
128    }
129
130    /// Whether the venue says `healthy`.
131    #[must_use]
132    pub fn is_healthy(&self) -> bool {
133        self.health == "healthy"
134    }
135
136    /// The venue's word as a [`Risk`]: any word other than `healthy` or
137    /// `liquidatable` reads as [`Risk::Near`].
138    #[must_use]
139    pub fn risk(&self) -> Risk {
140        match self.health.as_str() {
141            "healthy" => Risk::Safe,
142            "liquidatable" => Risk::Liquidatable,
143            _ => Risk::Near,
144        }
145    }
146
147    /// The health factor as written, while something is borrowed.
148    #[must_use]
149    pub fn factor(&self) -> Option<Dec> {
150        self.health_factor.as_ref().and_then(Figure::to_dec)
151    }
152}
153
154/// One token's position: what is borrowed and what is supplied.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
156#[non_exhaustive]
157pub struct Position {
158    /// What is borrowed; zero when the venue leaves it out.
159    #[serde(default)]
160    pub borrow: Basis,
161    /// What is supplied; zero when the venue leaves it out.
162    #[serde(default)]
163    pub supply: Basis,
164}
165
166/// `value` is what is held or owed now, in the token; `basis` what went in.
167/// A live portfolio-margin account wrote positions with no `basis`.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
169#[non_exhaustive]
170pub struct Basis {
171    /// What went in, in the token; zero when the venue leaves it out.
172    #[serde(default)]
173    pub basis: Dec,
174    /// What is held or owed now, in the token.
175    pub value: Dec,
176}
177
178impl Basis {
179    /// The interest earned or owed so far: the value less the basis.
180    #[must_use]
181    pub fn interest(&self) -> Option<Dec> {
182        self.value.checked_sub(self.basis)
183    }
184}
185
186#[cfg(test)]
187#[path = "tests/lend.rs"]
188mod tests;