df_hyperliquid_core/utils/nonce.rs
1//! [`NonceClock`], the source of action nonces.
2
3/// One account's nonces: milliseconds, strictly increasing. The venue keeps
4/// the highest nonces it has seen per signer and refuses a repeat, so each
5/// account holds its own clock. The time is passed in, since the browser and
6/// Workers have no std clock.
7#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
8pub struct NonceClock {
9 last: u64,
10}
11
12impl NonceClock {
13 /// A clock that has handed out nothing yet.
14 #[must_use]
15 pub const fn new() -> Self {
16 NonceClock { last: 0 }
17 }
18
19 /// A clock that hands out nothing at or below `last`.
20 #[must_use]
21 pub const fn after(last: u64) -> Self {
22 NonceClock { last }
23 }
24
25 /// `max(now_ms, last + 1)`, remembered as the new last.
26 pub fn next(&mut self, now_ms: u64) -> u64 {
27 let nonce = now_ms.max(self.last.saturating_add(1));
28 self.last = nonce;
29 nonce
30 }
31
32 /// The last nonce handed out, or the `last` it was made with; 0 for a new clock.
33 #[must_use]
34 pub const fn last(&self) -> u64 {
35 self.last
36 }
37}
38
39#[cfg(test)]
40#[path = "tests/nonce.rs"]
41mod tests;