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