stratus/eth/primitives/
nonce.rs

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