Skip to main content

endpoint_libs/libs/
types.rs

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