1use std::{
17 collections::hash_map::DefaultHasher,
18 hash::{Hash, Hasher},
19 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
20};
21
22use serde_json::Value;
23
24use crate::{
25 common::enums::HyperliquidInfoRequestType,
26 http::{
27 models::HyperliquidExecAction,
28 query::{ExchangeAction, ExchangeActionParams, InfoRequest},
29 },
30};
31
32#[derive(Debug)]
33pub struct WeightedLimiter {
34 capacity: f64, refill_per_sec: f64, state: tokio::sync::Mutex<State>,
37}
38
39#[derive(Debug)]
40struct State {
41 tokens: f64,
42 last_refill: Instant,
43}
44
45impl WeightedLimiter {
46 pub fn per_minute(capacity: u32) -> Self {
47 let cap = capacity as f64;
48 Self {
49 capacity: cap,
50 refill_per_sec: cap / 60.0,
51 state: tokio::sync::Mutex::new(State {
52 tokens: cap,
53 last_refill: Instant::now(),
54 }),
55 }
56 }
57
58 pub async fn acquire(&self, weight: u32) {
60 let need = weight as f64;
61
62 loop {
63 let mut st = self.state.lock().await;
64 Self::refill_locked(&mut st, self.refill_per_sec, self.capacity);
65
66 if st.tokens >= need {
67 st.tokens -= need;
68 return;
69 }
70 let deficit = need - st.tokens;
71 let secs = deficit / self.refill_per_sec;
72 drop(st);
73 tokio::time::sleep(Duration::from_secs_f64(secs.max(0.01))).await;
74 }
75 }
76
77 pub async fn debit_extra(&self, extra: u32) {
79 if extra == 0 {
80 return;
81 }
82 let mut st = self.state.lock().await;
83 Self::refill_locked(&mut st, self.refill_per_sec, self.capacity);
84 st.tokens = (st.tokens - extra as f64).max(0.0);
85 }
86
87 pub async fn snapshot(&self) -> RateLimitSnapshot {
88 let mut st = self.state.lock().await;
89 Self::refill_locked(&mut st, self.refill_per_sec, self.capacity);
90 RateLimitSnapshot {
91 capacity: self.capacity as u32,
92 tokens: st.tokens.max(0.0) as u32,
93 }
94 }
95
96 fn refill_locked(st: &mut State, per_sec: f64, cap: f64) {
97 let dt = Instant::now().duration_since(st.last_refill).as_secs_f64();
98 if dt > 0.0 {
99 st.tokens = (st.tokens + dt * per_sec).min(cap);
100 st.last_refill = Instant::now();
101 }
102 }
103}
104
105#[derive(Debug, Clone, Copy)]
106pub struct RateLimitSnapshot {
107 pub capacity: u32,
108 pub tokens: u32,
109}
110
111pub fn backoff_full_jitter(attempt: u32, base: Duration, cap: Duration) -> Duration {
112 let mut hasher = DefaultHasher::new();
113 attempt.hash(&mut hasher);
114 let nanos = SystemTime::now()
115 .duration_since(UNIX_EPOCH)
116 .unwrap_or_default()
117 .as_nanos();
118 nanos.hash(&mut hasher);
119 let hash = hasher.finish();
120
121 let max = (base.as_millis() as u64)
122 .saturating_mul(1u64 << attempt.min(16))
123 .min(cap.as_millis() as u64)
124 .max(base.as_millis() as u64);
125
126 Duration::from_millis((hash % max).max(1))
128}
129
130pub fn info_base_weight(req: &InfoRequest) -> u32 {
132 match req.request_type {
133 HyperliquidInfoRequestType::L2Book
134 | HyperliquidInfoRequestType::AllMids
135 | HyperliquidInfoRequestType::RecentTrades
136 | HyperliquidInfoRequestType::ClearinghouseState
137 | HyperliquidInfoRequestType::OrderStatus
138 | HyperliquidInfoRequestType::SpotClearinghouseState
139 | HyperliquidInfoRequestType::ExchangeStatus
140 | HyperliquidInfoRequestType::UserFees => 2,
141 HyperliquidInfoRequestType::UserRole => 60,
142 _ => 20,
143 }
144}
145
146pub fn info_extra_weight(req: &InfoRequest, json: &Value) -> u32 {
149 let items = match json {
150 Value::Array(a) => a.len(),
151 Value::Object(m) => m
152 .values()
153 .filter_map(|v| v.as_array().map(|a| a.len()))
154 .max()
155 .unwrap_or(0),
156 _ => 0,
157 };
158
159 let unit = match req.request_type {
160 HyperliquidInfoRequestType::CandleSnapshot => 60usize,
161 HyperliquidInfoRequestType::HistoricalOrders
162 | HyperliquidInfoRequestType::UserFills
163 | HyperliquidInfoRequestType::UserFillsByTime
164 | HyperliquidInfoRequestType::FundingHistory
165 | HyperliquidInfoRequestType::UserFunding
166 | HyperliquidInfoRequestType::NonUserFundingUpdates
167 | HyperliquidInfoRequestType::TwapHistory
168 | HyperliquidInfoRequestType::UserTwapSliceFills
169 | HyperliquidInfoRequestType::UserTwapSliceFillsByTime
170 | HyperliquidInfoRequestType::DelegatorHistory
171 | HyperliquidInfoRequestType::DelegatorRewards
172 | HyperliquidInfoRequestType::ValidatorStats => 20usize,
173 _ => return 0,
174 };
175 (items / unit) as u32
176}
177
178pub fn exchange_weight(action: &ExchangeAction) -> u32 {
180 let batch_size = match &action.params {
182 ExchangeActionParams::Order(params) => params.orders.len(),
183 ExchangeActionParams::Cancel(params) => params.cancels.len(),
184 ExchangeActionParams::Modify(_) => {
185 1
187 }
188 ExchangeActionParams::UpdateLeverage(_) | ExchangeActionParams::UpdateIsolatedMargin(_) => {
189 0
190 }
191 };
192 1 + (batch_size as u32 / 40)
193}
194
195pub fn exec_action_weight(action: &HyperliquidExecAction) -> u32 {
197 let batch_size = match action {
198 HyperliquidExecAction::Order { orders, .. } => orders.len(),
199 HyperliquidExecAction::Cancel { cancels } => cancels.len(),
200 HyperliquidExecAction::CancelByCloid { cancels } => cancels.len(),
201 HyperliquidExecAction::Modify { .. } => 1,
202 HyperliquidExecAction::BatchModify { modifies } => modifies.len(),
203 HyperliquidExecAction::UpdateLeverage { .. }
204 | HyperliquidExecAction::UpdateIsolatedMargin { .. }
205 | HyperliquidExecAction::ScheduleCancel { .. }
206 | HyperliquidExecAction::UsdClassTransfer { .. }
207 | HyperliquidExecAction::UserOutcome { .. }
208 | HyperliquidExecAction::TwapPlace { .. }
209 | HyperliquidExecAction::TwapCancel { .. }
210 | HyperliquidExecAction::Noop => 0,
211 };
212 1 + (batch_size as u32 / 40)
213}
214
215#[cfg(test)]
216mod tests {
217 use rstest::rstest;
218 use rust_decimal::Decimal;
219
220 use super::{
221 super::models::{
222 Cloid, HyperliquidExecAction, HyperliquidExecCancelByCloidRequest,
223 HyperliquidExecCancelOrderRequest, HyperliquidExecGrouping, HyperliquidExecLimitParams,
224 HyperliquidExecModifyOrderRequest, HyperliquidExecOrderKind,
225 HyperliquidExecPlaceOrderRequest, HyperliquidExecTif,
226 },
227 *,
228 };
229 use crate::http::query::{
230 CancelParams, ExchangeAction, ExchangeActionParams, ExchangeActionType, OrderParams,
231 UpdateLeverageParams,
232 };
233
234 fn exec_order() -> HyperliquidExecPlaceOrderRequest {
235 HyperliquidExecPlaceOrderRequest {
236 asset: 0,
237 is_buy: true,
238 price: Decimal::new(50000, 0),
239 size: Decimal::new(1, 0),
240 reduce_only: false,
241 kind: HyperliquidExecOrderKind::Limit {
242 limit: HyperliquidExecLimitParams {
243 tif: HyperliquidExecTif::Gtc,
244 },
245 },
246 cloid: Some(Cloid::from_hex("0x00000000000000000000000000000000").unwrap()),
247 }
248 }
249
250 fn exec_modify() -> HyperliquidExecModifyOrderRequest {
251 HyperliquidExecModifyOrderRequest {
252 oid: 12345,
253 order: exec_order(),
254 }
255 }
256
257 fn exec_cancel_by_cloid() -> HyperliquidExecCancelByCloidRequest {
258 HyperliquidExecCancelByCloidRequest {
259 asset: 0,
260 cloid: Cloid::from_hex("0x00000000000000000000000000000000").unwrap(),
261 }
262 }
263
264 #[rstest]
265 #[case(1, 1)]
266 #[case(39, 1)]
267 #[case(40, 2)]
268 #[case(79, 2)]
269 #[case(80, 3)]
270 fn test_exchange_weight_order_steps_every_40(
271 #[case] array_len: usize,
272 #[case] expected_weight: u32,
273 ) {
274 let orders: Vec<HyperliquidExecPlaceOrderRequest> =
275 (0..array_len).map(|_| exec_order()).collect();
276
277 let action = ExchangeAction {
278 action_type: ExchangeActionType::Order,
279 params: ExchangeActionParams::Order(OrderParams {
280 orders,
281 grouping: HyperliquidExecGrouping::Na,
282 builder: None,
283 }),
284 };
285 assert_eq!(exchange_weight(&action), expected_weight);
286 }
287
288 #[rstest]
289 #[case(1, 1)]
290 #[case(39, 1)]
291 #[case(40, 2)]
292 #[case(79, 2)]
293 #[case(80, 3)]
294 fn test_exec_action_weight_order_steps_every_40(
295 #[case] array_len: usize,
296 #[case] expected_weight: u32,
297 ) {
298 let action = HyperliquidExecAction::Order {
299 orders: (0..array_len).map(|_| exec_order()).collect(),
300 grouping: HyperliquidExecGrouping::Na,
301 builder: None,
302 };
303
304 assert_eq!(exec_action_weight(&action), expected_weight);
305 }
306
307 #[rstest]
308 #[case(1, 1)]
309 #[case(39, 1)]
310 #[case(40, 2)]
311 #[case(79, 2)]
312 #[case(80, 3)]
313 fn test_exec_action_weight_cancel_by_oid_steps_every_40(
314 #[case] array_len: usize,
315 #[case] expected_weight: u32,
316 ) {
317 let action = HyperliquidExecAction::Cancel {
318 cancels: (0..array_len)
319 .map(|i| HyperliquidExecCancelOrderRequest {
320 asset: 0,
321 oid: i as u64,
322 })
323 .collect(),
324 };
325
326 assert_eq!(exec_action_weight(&action), expected_weight);
327 }
328
329 #[rstest]
330 #[case(1, 1)]
331 #[case(39, 1)]
332 #[case(40, 2)]
333 #[case(79, 2)]
334 #[case(80, 3)]
335 fn test_exec_action_weight_cancel_by_cloid_steps_every_40(
336 #[case] array_len: usize,
337 #[case] expected_weight: u32,
338 ) {
339 let action = HyperliquidExecAction::CancelByCloid {
340 cancels: (0..array_len).map(|_| exec_cancel_by_cloid()).collect(),
341 };
342
343 assert_eq!(exec_action_weight(&action), expected_weight);
344 }
345
346 #[rstest]
347 #[case(1, 1)]
348 #[case(39, 1)]
349 #[case(40, 2)]
350 #[case(79, 2)]
351 #[case(80, 3)]
352 fn test_exec_action_weight_batch_modify_steps_every_40(
353 #[case] array_len: usize,
354 #[case] expected_weight: u32,
355 ) {
356 let action = HyperliquidExecAction::BatchModify {
357 modifies: (0..array_len).map(|_| exec_modify()).collect(),
358 };
359
360 assert_eq!(exec_action_weight(&action), expected_weight);
361 }
362
363 #[rstest]
364 fn test_exec_action_weight_modify() {
365 let action = HyperliquidExecAction::Modify {
366 modify: exec_modify(),
367 };
368
369 assert_eq!(exec_action_weight(&action), 1);
370 }
371
372 #[rstest]
373 fn test_exec_action_weight_non_batch_action() {
374 let action = HyperliquidExecAction::UpdateLeverage {
375 asset: 1,
376 is_cross: true,
377 leverage: 10,
378 };
379
380 assert_eq!(exec_action_weight(&action), 1);
381 }
382
383 #[rstest]
384 fn test_exchange_weight_cancel() {
385 let cancels: Vec<HyperliquidExecCancelByCloidRequest> =
386 (0..40).map(|_| exec_cancel_by_cloid()).collect();
387
388 let action = ExchangeAction {
389 action_type: ExchangeActionType::Cancel,
390 params: ExchangeActionParams::Cancel(CancelParams { cancels }),
391 };
392 assert_eq!(exchange_weight(&action), 2);
393 }
394
395 #[rstest]
396 fn test_exchange_weight_non_batch_action() {
397 let update_leverage = ExchangeAction {
398 action_type: ExchangeActionType::UpdateLeverage,
399 params: ExchangeActionParams::UpdateLeverage(UpdateLeverageParams {
400 asset: 1,
401 is_cross: true,
402 leverage: 10,
403 }),
404 };
405 assert_eq!(exchange_weight(&update_leverage), 1);
406 }
407
408 #[tokio::test]
409 async fn test_limiter_roughly_caps_to_capacity() {
410 let limiter = WeightedLimiter::per_minute(1200);
411
412 for _ in 0..60 {
414 limiter.acquire(20).await; }
416
417 let t0 = std::time::Instant::now();
419 limiter.acquire(20).await;
420 let elapsed = t0.elapsed();
421
422 assert!(
424 elapsed.as_millis() >= 500,
425 "Expected significant delay, was {}ms",
426 elapsed.as_millis()
427 );
428 }
429
430 #[tokio::test]
431 async fn test_limiter_debit_extra_works() {
432 let limiter = WeightedLimiter::per_minute(100);
433
434 let snapshot = limiter.snapshot().await;
436 assert_eq!(snapshot.capacity, 100);
437 assert_eq!(snapshot.tokens, 100);
438
439 limiter.acquire(30).await;
441 let snapshot = limiter.snapshot().await;
442 assert_eq!(snapshot.tokens, 70);
443
444 limiter.debit_extra(20).await;
446 let snapshot = limiter.snapshot().await;
447 assert_eq!(snapshot.tokens, 50);
448
449 limiter.debit_extra(100).await;
451 let snapshot = limiter.snapshot().await;
452 assert_eq!(snapshot.tokens, 0);
453 }
454
455 #[rstest]
456 #[case(0, 100)]
457 #[case(1, 200)]
458 #[case(2, 400)]
459 fn test_backoff_full_jitter_increases(#[case] attempt: u32, #[case] max_expected_ms: u64) {
460 let base = Duration::from_millis(100);
461 let cap = Duration::from_secs(5);
462
463 let delay = backoff_full_jitter(attempt, base, cap);
464
465 assert!(delay.as_millis() >= 1);
466 assert!(delay.as_millis() <= max_expected_ms as u128);
467 }
468
469 #[rstest]
470 fn test_backoff_full_jitter_respects_cap() {
471 let base = Duration::from_millis(100);
472 let cap = Duration::from_secs(5);
473
474 let delay_high = backoff_full_jitter(10, base, cap);
475 assert!(delay_high.as_millis() <= cap.as_millis());
476 }
477}