Skip to main content

agglayer_primitives/
address.rs

1pub use alloy_primitives::Address as AlloyAddress;
2
3/// A wrapper over [alloy_primitives::Address] that allows us to add custom
4/// methods and trait implementations.
5#[derive(
6    Debug,
7    Clone,
8    Copy,
9    PartialEq,
10    Eq,
11    PartialOrd,
12    Ord,
13    serde::Serialize,
14    serde::Deserialize,
15    derive_more::From,
16    derive_more::Into,
17    derive_more::FromStr,
18    derive_more::AsRef,
19    derive_more::AsMut,
20    derive_more::Display,
21    derive_more::LowerHex,
22    derive_more::UpperHex,
23)]
24#[cfg_attr(feature = "testutils", derive(arbitrary::Arbitrary))]
25#[from(AlloyAddress, [u8; 20])]
26#[into(AlloyAddress, [u8; 20])]
27#[as_ref(AlloyAddress, [u8; 20], [u8])]
28#[repr(transparent)]
29#[serde(rename = "agglayer_primitives::Address")]
30pub struct Address(AlloyAddress);
31
32impl Address {
33    pub const ZERO: Self = Self::from_alloy(AlloyAddress::ZERO);
34
35    #[inline]
36    pub const fn new(bytes: [u8; 20]) -> Self {
37        Self::from_alloy(AlloyAddress::new(bytes))
38    }
39
40    #[inline]
41    pub const fn from_alloy(address: AlloyAddress) -> Self {
42        Self(address)
43    }
44
45    #[inline]
46    pub const fn as_alloy(&self) -> &AlloyAddress {
47        &self.0
48    }
49
50    #[inline]
51    pub const fn into_alloy(self) -> AlloyAddress {
52        self.0
53    }
54
55    #[inline]
56    pub const fn into_array(self) -> [u8; 20] {
57        self.into_alloy().into_array()
58    }
59
60    #[inline]
61    pub const fn as_slice(&self) -> &[u8] {
62        self.as_alloy().0.as_slice()
63    }
64}
65
66impl TryFrom<&[u8]> for Address {
67    type Error = std::array::TryFromSliceError;
68
69    #[inline]
70    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
71        AlloyAddress::try_from(value).map(Self)
72    }
73}
74
75#[macro_export]
76macro_rules! address {
77    ($($addr:literal)*) => {
78        $crate::Address::from_alloy($crate::alloy_primitives::address!($($addr)*))
79    };
80}
81
82#[cfg(test)]
83mod test {
84    use super::*;
85
86    #[test]
87    fn address_macro() {
88        let address = address!("00112233445566778899aabbccddeeff00112233");
89        let alloy_address = alloy_primitives::address!("00112233445566778899aabbccddeeff00112233");
90        assert_eq!(address, Address::from_alloy(alloy_address));
91    }
92}