Skip to main content

walletkit/core/wallet/primitives/
nonce.rs

1use alloy_primitives::Address;
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeSet;
4
5/// Per-scope nonce allocation state: the next fresh nonce and the set of freed
6/// nonces (from released reservations) to recycle lowest-first.
7#[derive(Debug, Clone, Default, Serialize, Deserialize)]
8pub struct NonceState {
9    /// The next never-allocated nonce.
10    pub next: u64,
11    /// Freed nonces from released reservations, recycled lowest-first before `next`.
12    pub free: BTreeSet<u64>,
13}
14
15/// The key a [`NonceState`] is stored under. Keyed by account (EOA); a 4337 2D-nonce
16/// lane can be added here without changing the manager.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub struct NonceScope {
19    /// The account (EOA) whose nonce sequence this scope tracks.
20    pub account: Address,
21}
22
23impl NonceScope {
24    /// The scope for a plain EOA — one nonce sequence per account.
25    pub fn eoa(account: Address) -> Self {
26        Self { account }
27    }
28}
29
30/// Opaque, monotonic ownership token for the single-writer nonce seam. The
31/// [`StateStore`](crate::core::deps::StateStore) records the highest token committed per
32/// scope and rejects any lower one (fencing enforced at the resource, per Kleppmann).
33/// Only [`SINGLE_WRITER`](FenceToken::SINGLE_WRITER) is used today; a distributed lease
34/// issuer mints real tokens later with no trait change.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
36pub struct FenceToken(u64);
37
38impl FenceToken {
39    /// The sole token in single-writer mode — every write carries it, so the
40    /// reject-if-lower check is always satisfied (a no-op) until a lease issuer exists.
41    pub const SINGLE_WRITER: FenceToken = FenceToken(0);
42}
43
44#[cfg(feature = "postgres")]
45impl FenceToken {
46    /// The raw token value. Postgres stores the fence as a `BIGINT` column, so the adapter
47    /// needs the scalar; redb serializes the token directly and needs no accessor. (The
48    /// inverse `from_u64` is added when a consumer reconstructs a token from storage — the
49    /// CAS compares in `i64` space and never does, so it isn't needed yet.)
50    pub(crate) fn as_u64(self) -> u64 {
51        self.0
52    }
53}
54
55#[cfg(test)]
56impl FenceToken {
57    /// Test-only: a token above `SINGLE_WRITER` to exercise the reject-if-lower path.
58    pub(crate) fn for_test(n: u64) -> Self {
59        FenceToken(n)
60    }
61}