stratus/eth/primitives/
nonce.rs

1use alloy_primitives::U64;
2use alloy_primitives::U256;
3use anyhow::bail;
4use display_json::DebugAsJson;
5#[cfg(test)]
6use fake::Dummy;
7#[cfg(test)]
8use fake::Faker;
9
10use crate::ext::RuintExt;
11
12#[derive(DebugAsJson, derive_more::Display, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
13pub struct Nonce(U64);
14
15impl Nonce {
16    pub const ZERO: Nonce = Nonce(U64::ZERO);
17
18    pub fn as_u64(&self) -> u64 {
19        self.0.as_u64()
20    }
21
22    /// Returns the next nonce.
23    pub fn next_nonce(&self) -> Self {
24        Self(self.0 + U64::ONE)
25    }
26}
27
28#[cfg(test)]
29impl Dummy<Faker> for Nonce {
30    fn dummy_with_rng<R: rand::Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
31        Self(U64::random_with(rng))
32    }
33}
34
35// -----------------------------------------------------------------------------
36// Conversions: Other -> Self
37// -----------------------------------------------------------------------------
38
39impl TryFrom<i32> for Nonce {
40    type Error = anyhow::Error;
41
42    fn try_from(value: i32) -> Result<Self, Self::Error> {
43        if value < 0 {
44            bail!("Nonce cannot be negative");
45        }
46        Ok(Self(U64::from(value as u32)))
47    }
48}
49
50impl From<u64> for Nonce {
51    fn from(value: u64) -> Self {
52        Self(U64::from(value))
53    }
54}
55
56// -----------------------------------------------------------------------------
57// Conversions: Self -> Other
58// -----------------------------------------------------------------------------
59impl From<Nonce> for u64 {
60    fn from(value: Nonce) -> Self {
61        value.as_u64()
62    }
63}
64
65impl From<Nonce> for U256 {
66    fn from(value: Nonce) -> Self {
67        U256::from(value.as_u64())
68    }
69}