Skip to main content

df_hyperliquid_core/account/settings/
limits.rs

1//! What an address may still send (`userRateLimit`), the venue's formulas for what it earns:
2//! requests by volume traded, cancels past the cap, open orders by volume; and
3//! `reserveRequestWeight`, which buys more requests outright. Action limits are per
4//! address, a subaccount having its own; reads are the IP's ([`crate::client::http::limit`]).
5
6use crate::account::{ActionKind, Signers};
7use crate::client::{ApiError, Transport, info, user_request};
8use crate::utils::sign::{L1Action, Map};
9use crate::utils::{Address, Dec, Round};
10use serde::Deserialize;
11
12/// What every address starts with; it earns one more request for every USDC it trades.
13pub const INITIAL_REQUESTS: u64 = 10_000;
14
15/// How often a throttled address may send one request.
16pub const THROTTLED_EVERY_MS: u64 = 10_000;
17
18/// The open orders every address has.
19pub const OPEN_ORDERS: u64 = 1_000;
20/// The most open orders an address can earn.
21pub const MOST_OPEN_ORDERS: u64 = 5_000;
22
23/// The volume that earns one more open order, in USDC.
24pub const VOLUME_PER_OPEN_ORDER: i64 = 5_000_000;
25
26/// What one reserved request costs, in USDC, paid from the perps balance.
27pub const RESERVED_REQUEST_COST: Dec = Dec::lit::<4>(5);
28
29/// The most weight one `reserveRequestWeight` reserves, as `@nktkas/hyperliquid` 0.33.3 bounds it.
30pub const MOST_RESERVED_WEIGHT: u64 = 1_844_674_407_370_955;
31
32/// A reservation the venue would not take.
33#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
34#[error("a reservation is 1 to {MOST_RESERVED_WEIGHT} requests, not {0}")]
35pub struct BadWeight(pub u64);
36
37/// `reserveRequestWeight`: `{type, weight, destination}`, the destination only when set. Buys
38/// `weight` more requests at [`RESERVED_REQUEST_COST`] each, for the signer's account or for
39/// another account that already exists. An agent may sign it for its master.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct ReserveRequestWeight {
42    weight: u64,
43    destination: Option<Address>,
44}
45
46impl ReserveRequestWeight {
47    /// L1: an agent may sign it for its master.
48    pub const KEY: Signers = ActionKind::ReserveRequestWeight.signers();
49
50    /// `weight` more requests for the account that signs.
51    pub fn new(weight: u64) -> Result<ReserveRequestWeight, BadWeight> {
52        match (1..=MOST_RESERVED_WEIGHT).contains(&weight) {
53            true => Ok(ReserveRequestWeight { weight, destination: None }),
54            false => Err(BadWeight(weight)),
55        }
56    }
57
58    /// For `destination` instead, paid by the account that signs.
59    #[must_use]
60    pub const fn for_user(mut self, destination: Address) -> ReserveRequestWeight {
61        self.destination = Some(destination);
62        self
63    }
64
65    /// How many requests it reserves.
66    #[must_use]
67    pub const fn weight(&self) -> u64 {
68        self.weight
69    }
70
71    /// The account the requests are for; `None` for the one that signs.
72    #[must_use]
73    pub const fn destination(&self) -> Option<Address> {
74        self.destination
75    }
76
77    /// What it costs, in USDC.
78    #[must_use]
79    pub fn cost(&self) -> Option<Dec> {
80        Dec::new(i128::from(self.weight), 0)?.checked_mul(RESERVED_REQUEST_COST)
81    }
82}
83
84impl L1Action for ReserveRequestWeight {
85    fn action(&self) -> Map {
86        Map::new()
87            .put("type", "reserveRequestWeight")
88            .put("weight", self.weight)
89            .put_some("destination", self.destination.map(|destination| destination.to_hex()))
90    }
91}
92
93/// `{"type":"userRateLimit","user":..}`.
94#[must_use]
95pub fn rate_limit_request(user: Address) -> String {
96    user_request("userRateLimit", user)
97}
98
99/// One address's limit. Weighs 20 against the IP.
100pub async fn rate_limit(transport: &impl Transport, user: Address) -> Result<RateLimit, ApiError> {
101    info(transport, rate_limit_request(user)).await
102}
103
104/// `userRateLimit`.
105#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
106#[non_exhaustive]
107pub struct RateLimit {
108    /// USDC traded since the address began: what buys its cap.
109    #[serde(rename = "cumVlm")]
110    pub volume: Dec,
111    /// Requests sent so far (`nRequestsUsed`), throttled ones included.
112    #[serde(rename = "nRequestsUsed")]
113    pub used: u64,
114    /// The requests the address may send before it is throttled (`nRequestsCap`).
115    #[serde(rename = "nRequestsCap")]
116    pub cap: u64,
117    /// Bought with `reserveRequestWeight`.
118    #[serde(rename = "nRequestsSurplus", default)]
119    pub surplus: u64,
120}
121
122impl RateLimit {
123    /// What is left before the address is throttled; never a wrapped total,
124    /// since throttled requests still count.
125    #[must_use]
126    pub const fn remaining(&self) -> u64 {
127        self.cap.saturating_sub(self.used)
128    }
129
130    /// Whether the address has used its cap, so it may send one request every
131    /// [`THROTTLED_EVERY_MS`].
132    #[must_use]
133    pub const fn is_throttled(&self) -> bool {
134        self.remaining() == 0
135    }
136
137    /// What cancels may use: `min(cap + 100000, cap * 2)`, so a throttled address can still cancel.
138    #[must_use]
139    pub const fn cancel_cap(&self) -> u64 {
140        let wider = self.cap.saturating_add(100_000);
141        let doubled = self.cap.saturating_mul(2);
142        if wider < doubled { wider } else { doubled }
143    }
144
145    /// The cap `volume` earns: 10,000 and one for every whole USDC. `None`
146    /// for a negative volume.
147    #[must_use]
148    pub fn earned_cap(volume: Dec) -> Option<u64> {
149        let whole = u64::try_from(volume.units_at(0, Round::Down)?).ok()?;
150        INITIAL_REQUESTS.checked_add(whole)
151    }
152}
153
154/// The USDC to trade to earn `requests` more.
155#[must_use]
156pub fn volume_for(requests: u64) -> Dec {
157    Dec::lit::<0>(i128::from(requests))
158}
159
160/// What `reserveRequestWeight` charges for `requests` more, in USDC: 0.0005 a request, paid from
161/// the perps balance.
162#[must_use]
163pub fn surplus_cost(requests: u64) -> Option<Dec> {
164    Dec::lit::<0>(i128::from(requests)).checked_mul(RESERVED_REQUEST_COST)
165}
166
167/// What an action costs the address: one, or one for every order or cancel it batches. The IP
168/// counts a batch as one.
169#[must_use]
170pub fn address_requests(batched: usize) -> u64 {
171    u64::try_from(batched.max(1)).unwrap_or(u64::MAX)
172}
173
174/// The open orders `volume` allows: one more for every 5M USDC, at most 5000.
175#[must_use]
176pub fn open_order_cap(volume: Dec) -> u64 {
177    let earned = volume
178        .checked_div(Dec::from_int(VOLUME_PER_OPEN_ORDER), 0, Round::Down)
179        .and_then(|earned| earned.units_at(0, Round::Down))
180        .and_then(|earned| u64::try_from(earned).ok())
181        .unwrap_or(0);
182    OPEN_ORDERS.saturating_add(earned).min(MOST_OPEN_ORDERS)
183}
184
185#[cfg(test)]
186#[path = "tests/limits.rs"]
187mod tests;