Skip to main content

df_hyperliquid_core/earn/staking/
reads.rs

1//! `validatorSummaries`, `delegatorSummary`, `delegations`,
2//! `delegatorRewards`, `delegatorHistory`. HYPE figures are decimal strings,
3//! except a validator's `stake`, which is wei.
4
5use crate::client::{ApiError, Network, Transport, info, info_request, user_request};
6use crate::utils::{Address, Dec, HYPE_DECIMALS};
7use serde::{Deserialize, Deserializer};
8use serde_json::Value;
9
10/// A mainnet delegation is locked one day before it can be undelegated.
11pub const MAINNET_DELEGATION_LOCK_MS: u64 = 86_400_000;
12
13/// Testnet's delegation lock: two minutes, as live testnet delegations show.
14pub const TESTNET_DELEGATION_LOCK_MS: u64 = 120_000;
15
16/// A mainnet withdrawal from staking waits seven days in the queue before it
17/// reaches spot.
18pub const MAINNET_UNSTAKING_MS: u64 = 7 * 86_400_000;
19
20/// Testnet's unstaking queue: five minutes, as live testnet histories show.
21pub const TESTNET_UNSTAKING_MS: u64 = 300_000;
22
23/// At most this many withdrawals wait in the queue at once.
24pub const MAX_PENDING_WITHDRAWALS: u64 = 5;
25
26/// How long a new delegation on `network` is locked.
27#[must_use]
28pub const fn delegation_lock_ms(network: Network) -> u64 {
29    match network {
30        Network::Mainnet => MAINNET_DELEGATION_LOCK_MS,
31        Network::Testnet => TESTNET_DELEGATION_LOCK_MS,
32    }
33}
34
35/// How long a withdrawal on `network` waits before it reaches spot.
36#[must_use]
37pub const fn unstaking_ms(network: Network) -> u64 {
38    match network {
39        Network::Mainnet => MAINNET_UNSTAKING_MS,
40        Network::Testnet => TESTNET_UNSTAKING_MS,
41    }
42}
43
44/// When a delegation made at `now_ms` may first be undelegated.
45#[must_use]
46pub const fn locked_until(network: Network, now_ms: u64) -> u64 {
47    now_ms.saturating_add(delegation_lock_ms(network))
48}
49
50/// `{"type":"validatorSummaries"}`.
51#[must_use]
52pub fn validator_summaries_request() -> String {
53    info_request("validatorSummaries", &[])
54}
55
56/// `{"type":"delegatorSummary","user":..}`.
57#[must_use]
58pub fn delegator_summary_request(user: Address) -> String {
59    user_request("delegatorSummary", user)
60}
61
62/// `{"type":"delegations","user":..}`.
63#[must_use]
64pub fn delegations_request(user: Address) -> String {
65    user_request("delegations", user)
66}
67
68/// `{"type":"delegatorRewards","user":..}`.
69#[must_use]
70pub fn delegator_rewards_request(user: Address) -> String {
71    user_request("delegatorRewards", user)
72}
73
74/// `{"type":"delegatorHistory","user":..}`.
75#[must_use]
76pub fn delegator_history_request(user: Address) -> String {
77    user_request("delegatorHistory", user)
78}
79
80/// Every validator's summary.
81pub async fn validator_summaries(transport: &impl Transport) -> Result<Vec<ValidatorSummary>, ApiError> {
82    info(transport, validator_summaries_request()).await
83}
84
85/// The account's staking totals.
86pub async fn delegator_summary(transport: &impl Transport, user: Address) -> Result<DelegatorSummary, ApiError> {
87    info(transport, delegator_summary_request(user)).await
88}
89
90/// The account's delegations, one per validator.
91pub async fn delegations(transport: &impl Transport, user: Address) -> Result<Vec<Delegation>, ApiError> {
92    info(transport, delegations_request(user)).await
93}
94
95/// Newest first.
96pub async fn delegator_rewards(transport: &impl Transport, user: Address) -> Result<Vec<Reward>, ApiError> {
97    info(transport, delegator_rewards_request(user)).await
98}
99
100/// Newest first.
101pub async fn delegator_history(transport: &impl Transport, user: Address) -> Result<Vec<StakeEvent>, ApiError> {
102    info(transport, delegator_history_request(user)).await
103}
104
105/// One validator, as `validatorSummaries` lists it.
106#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
107#[serde(rename_all = "camelCase")]
108#[non_exhaustive]
109pub struct ValidatorSummary {
110    /// The validator's address.
111    pub validator: Address,
112    /// The address that signs the validator's blocks.
113    pub signer: Address,
114    /// The validator's name; empty when the venue leaves it out.
115    #[serde(default)]
116    pub name: String,
117    /// The validator's description; empty when the venue leaves it out.
118    #[serde(default)]
119    pub description: String,
120    /// How many blocks the validator produced recently (`nRecentBlocks`).
121    #[serde(default)]
122    pub n_recent_blocks: u64,
123    /// In wei, 1e8 to a HYPE.
124    pub stake: u64,
125    /// Whether the validator is jailed (`isJailed`) and earns no rewards.
126    #[serde(default)]
127    pub is_jailed: bool,
128    /// When a jailed validator may unjail itself (`unjailableAfter`), milliseconds; `None` when not set.
129    #[serde(default)]
130    pub unjailable_after: Option<u64>,
131    /// Whether the validator is in the active set (`isActive`).
132    #[serde(default)]
133    pub is_active: bool,
134    /// A fraction of rewards: 0.04 is 4%.
135    pub commission: Dec,
136    /// By window: `day`, `week`, `month`.
137    #[serde(default)]
138    pub stats: Vec<(String, ValidatorStats)>,
139}
140
141/// A validator's figures over one window.
142#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
143#[serde(rename_all = "camelCase")]
144#[non_exhaustive]
145pub struct ValidatorStats {
146    /// The share of the window the validator was up (`uptimeFraction`), as a fraction.
147    pub uptime_fraction: Dec,
148    /// Yearly, as a fraction.
149    pub predicted_apr: Dec,
150    /// How many samples the figures come from (`nSamples`).
151    #[serde(default)]
152    pub n_samples: u64,
153}
154
155impl ValidatorSummary {
156    /// The stake in HYPE; `None` past what a [`Dec`] holds.
157    #[must_use]
158    pub fn stake_hype(&self) -> Option<Dec> {
159        Dec::new(i128::from(self.stake), HYPE_DECIMALS)
160    }
161
162    /// The stats over one window: `week` is what most clients show.
163    #[must_use]
164    pub fn stats(&self, window: &str) -> Option<&ValidatorStats> {
165        self.stats.iter().find(|(name, _)| name == window).map(|(_, stats)| stats)
166    }
167}
168
169/// An account's staking totals, as `delegatorSummary` answers them. HYPE.
170#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
171#[serde(rename_all = "camelCase")]
172#[non_exhaustive]
173pub struct DelegatorSummary {
174    /// Everything delegated to validators.
175    pub delegated: Dec,
176    /// The staking balance free to delegate or withdraw.
177    pub undelegated: Dec,
178    /// HYPE in the unstaking queue (`totalPendingWithdrawal`).
179    pub total_pending_withdrawal: Dec,
180    /// How many withdrawals wait in the queue (`nPendingWithdrawals`).
181    pub n_pending_withdrawals: u64,
182}
183
184/// One delegation, as `delegations` lists it.
185#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
186#[serde(rename_all = "camelCase")]
187#[non_exhaustive]
188pub struct Delegation {
189    /// The validator delegated to.
190    pub validator: Address,
191    /// The HYPE delegated.
192    pub amount: Dec,
193    /// Milliseconds; undelegating before it is refused.
194    pub locked_until_timestamp: u64,
195}
196
197impl Delegation {
198    /// Whether undelegating at `now_ms` is refused because the lock has not ended.
199    #[must_use]
200    pub const fn is_locked(&self, now_ms: u64) -> bool {
201        now_ms < self.locked_until_timestamp
202    }
203}
204
205/// One reward credit, as `delegatorRewards` lists it.
206#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
207#[serde(rename_all = "camelCase")]
208#[non_exhaustive]
209pub struct Reward {
210    /// When it was credited, milliseconds.
211    pub time: u64,
212    /// `delegation`, or `commission` for a validator's own cut.
213    #[serde(default)]
214    pub source: String,
215    /// The HYPE credited (`totalAmount`).
216    pub total_amount: Dec,
217}
218
219/// One row of `delegatorHistory`.
220#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
221#[non_exhaustive]
222pub struct StakeEvent {
223    /// When it happened, milliseconds.
224    pub time: u64,
225    /// The L1 transaction hash.
226    pub hash: String,
227    /// What the row did.
228    #[serde(deserialize_with = "delta")]
229    pub delta: StakeDelta,
230}
231
232/// What a history row did, keyed by its one field's name.
233#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
234#[serde(rename_all = "camelCase")]
235#[non_exhaustive]
236pub enum StakeDelta {
237    /// `delegate`: staking balance to a validator, or back.
238    #[serde(rename_all = "camelCase")]
239    Delegate {
240        /// The validator.
241        validator: Address,
242        /// The HYPE moved.
243        amount: Dec,
244        /// `true` for an undelegation (`isUndelegate`).
245        is_undelegate: bool,
246    },
247    /// `withdrawal`: from staking toward spot: `initiated`, then `finalized` once queued
248    /// [`unstaking_ms`].
249    Withdrawal {
250        /// The HYPE withdrawn.
251        amount: Dec,
252        /// `initiated` or `finalized`.
253        phase: String,
254    },
255    /// `cDeposit`: spot into staking.
256    CDeposit {
257        /// The HYPE deposited.
258        amount: Dec,
259    },
260    /// A kind this build does not read, by name.
261    #[serde(skip_deserializing)]
262    Other {
263        /// The row's field name.
264        kind: String,
265    },
266}
267
268impl StakeEvent {
269    /// When an initiated withdrawal reaches spot on `network`.
270    #[must_use]
271    pub fn unstaked_at(&self, network: Network) -> Option<u64> {
272        match &self.delta {
273            StakeDelta::Withdrawal { phase, .. } if phase == "initiated" => {
274                Some(self.time.saturating_add(unstaking_ms(network)))
275            }
276            _ => None,
277        }
278    }
279}
280
281/// A known kind that no longer reads as modelled falls back to `Other` too:
282/// one changed row must not blank the history.
283fn delta<'de, D: Deserializer<'de>>(deserializer: D) -> Result<StakeDelta, D::Error> {
284    let value = Value::deserialize(deserializer)?;
285    let kind = value.as_object().and_then(|object| object.keys().next().cloned()).unwrap_or_default();
286    Ok(serde_json::from_value(value).unwrap_or(StakeDelta::Other { kind }))
287}
288
289#[cfg(test)]
290#[path = "tests/stake.rs"]
291mod tests;