Skip to main content

endpoint_libs/libs/
types.rs

1use std::fmt::{Debug, Display, Formatter};
2use std::ops::{Deref, DerefMut};
3use std::str::FromStr;
4
5use serde::de::Error;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8#[cfg(feature = "blockchain")]
9#[doc(hidden)]
10pub use alloy_primitives::{Address, B256 as H256, U256};
11
12#[cfg(not(feature = "blockchain"))]
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
14pub struct Address(pub [u8; 20]);
15#[cfg(not(feature = "blockchain"))]
16#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
17pub struct H256(pub [u8; 32]);
18#[cfg(not(feature = "blockchain"))]
19#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
20pub struct U256(pub [u64; 4]);
21
22#[cfg(not(feature = "blockchain"))]
23macro_rules! byte_scalar {
24    ($ty:ty, $len:literal) => {
25        impl Deref for $ty {
26            type Target = [u8];
27            fn deref(&self) -> &Self::Target { &self.0 }
28        }
29        impl Debug for $ty {
30            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
31                Display::fmt(self, f)
32            }
33        }
34        impl Display for $ty {
35            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
36                write!(f, "0x{}", hex::encode(&self.0))
37            }
38        }
39        impl FromStr for $ty {
40            type Err = String;
41            fn from_str(value: &str) -> Result<Self, Self::Err> {
42                let bytes = decode_scalar(value, $len)?;
43                let mut result = [0u8; $len];
44                result.copy_from_slice(&bytes);
45                Ok(Self(result))
46            }
47        }
48        impl Serialize for $ty {
49            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
50            where S: Serializer {
51                self.to_string().serialize(serializer)
52            }
53        }
54        impl<'de> Deserialize<'de> for $ty {
55            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
56            where D: Deserializer<'de> {
57                let value = String::deserialize(deserializer)?;
58                value.parse().map_err(D::Error::custom)
59            }
60        }
61    };
62}
63
64#[cfg(not(feature = "blockchain"))]
65byte_scalar!(Address, 20);
66#[cfg(not(feature = "blockchain"))]
67byte_scalar!(H256, 32);
68
69#[cfg(not(feature = "blockchain"))]
70impl Deref for U256 {
71    type Target = [u8];
72    fn deref(&self) -> &Self::Target {
73        // A u64 array has a contiguous byte representation for read-only viewing.
74        unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast::<u8>(), 32) }
75    }
76}
77#[cfg(not(feature = "blockchain"))]
78impl Debug for U256 {
79    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Display::fmt(self, f) }
80}
81#[cfg(not(feature = "blockchain"))]
82impl Display for U256 {
83    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "0x{}", hex::encode(&**self)) }
84}
85#[cfg(not(feature = "blockchain"))]
86impl FromStr for U256 {
87    type Err = String;
88    fn from_str(value: &str) -> Result<Self, Self::Err> {
89        let bytes = decode_scalar(value, 32)?;
90        let mut words = [0u64; 4];
91        for (index, chunk) in bytes.chunks_exact(8).enumerate() {
92            words[index] = u64::from_be_bytes(chunk.try_into().expect("eight byte chunk"));
93        }
94        Ok(Self(words))
95    }
96}
97#[cfg(not(feature = "blockchain"))]
98impl Serialize for U256 {
99    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
100    where S: Serializer { self.to_string().serialize(serializer) }
101}
102#[cfg(not(feature = "blockchain"))]
103impl<'de> Deserialize<'de> for U256 {
104    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
105    where D: Deserializer<'de> {
106        let value = String::deserialize(deserializer)?;
107        value.parse().map_err(D::Error::custom)
108    }
109}
110
111fn decode_scalar(value: &str, digits: usize) -> Result<Vec<u8>, String> {
112    if value.len() != digits * 2 + 2 || !value.starts_with("0x") {
113        return Err(format!("expected 0x followed by exactly {} hexadecimal digits", digits * 2));
114    }
115    hex::decode(&value[2..]).map_err(|error| error.to_string())
116}
117
118fn parse_blockchain_scalar<E: Error, T: FromStr>(value: &str, digits: usize) -> Result<T, E>
119where T::Err: std::fmt::Display {
120    if value.len() != digits + 2 || !value.starts_with("0x") {
121        return Err(E::custom(format!("expected 0x followed by exactly {digits} hexadecimal digits")));
122    }
123    T::from_str(value).map_err(|error| E::custom(error.to_string()))
124}
125
126#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
127pub struct BlockchainAddress(pub Address);
128impl Debug for BlockchainAddress {
129    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Debug::fmt(&self.0, f) }
130}
131#[allow(non_snake_case)]
132pub mod WithBlockchainAddress {
133    use super::*;
134    pub fn serialize<S>(this: &Address, serializer: S) -> Result<S::Ok, S::Error>
135    where S: Serializer { format!("{this:?}").serialize(serializer) }
136    pub fn deserialize<'de, D>(deserializer: D) -> Result<Address, D::Error>
137    where D: Deserializer<'de> {
138        let value = String::deserialize(deserializer)?;
139        parse_blockchain_scalar::<D::Error, Address>(&value, 40)
140    }
141}
142impl Serialize for BlockchainAddress {
143    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
144    where S: Serializer { format!("{:?}", self.0).serialize(serializer) }
145}
146impl<'de> Deserialize<'de> for BlockchainAddress {
147    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
148    where D: Deserializer<'de> {
149        let value = String::deserialize(deserializer)?;
150        parse_blockchain_scalar::<D::Error, Address>(&value, 40).map(Self)
151    }
152}
153impl From<Address> for BlockchainAddress { fn from(value: Address) -> Self { Self(value) } }
154impl From<BlockchainAddress> for Address { fn from(value: BlockchainAddress) -> Self { value.0 } }
155impl Deref for BlockchainAddress {
156    type Target = Address;
157    fn deref(&self) -> &Self::Target { &self.0 }
158}
159impl DerefMut for BlockchainAddress { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
160
161#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
162pub struct BlockchainTransactionHash(pub H256);
163impl Debug for BlockchainTransactionHash {
164    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Debug::fmt(&self.0, f) }
165}
166#[allow(non_snake_case)]
167pub mod WithBlockchainTransactionHash {
168    use super::*;
169    pub fn serialize<S>(this: &H256, serializer: S) -> Result<S::Ok, S::Error>
170    where S: Serializer { format!("{this:?}").serialize(serializer) }
171    pub fn deserialize<'de, D>(deserializer: D) -> Result<H256, D::Error>
172    where D: Deserializer<'de> {
173        let value = String::deserialize(deserializer)?;
174        parse_blockchain_scalar::<D::Error, H256>(&value, 64)
175    }
176}
177impl Serialize for BlockchainTransactionHash {
178    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
179    where S: Serializer { format!("{:?}", self.0).serialize(serializer) }
180}
181impl<'de> Deserialize<'de> for BlockchainTransactionHash {
182    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
183    where D: Deserializer<'de> {
184        let value = String::deserialize(deserializer)?;
185        parse_blockchain_scalar::<D::Error, H256>(&value, 64).map(Self)
186    }
187}
188impl From<H256> for BlockchainTransactionHash { fn from(value: H256) -> Self { Self(value) } }
189impl From<BlockchainTransactionHash> for H256 { fn from(value: BlockchainTransactionHash) -> Self { value.0 } }
190impl Deref for BlockchainTransactionHash {
191    type Target = H256;
192    fn deref(&self) -> &Self::Target { &self.0 }
193}
194impl DerefMut for BlockchainTransactionHash { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }