stratus/eth/primitives/
chain_id.rs

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