1use alloy_primitives::B256;
2use serde::de::Error;
3use serde::{Deserializer, Serializer};
4
5use crate::hex::PrefixedHexVisitor;
6
7pub fn serialize<S>(hash: &B256, serializer: S) -> Result<S::Ok, S::Error>
8where
9 S: Serializer,
10{
11 let mut hex_string: String = "0x".to_string();
12 hex_string.push_str(&hex::encode(&hash));
13
14 serializer.serialize_str(&hex_string)
15}
16
17pub fn deserialize<'de, D>(deserializer: D) -> Result<B256, D::Error>
18where
19 D: Deserializer<'de>,
20{
21 let decoded = deserializer.deserialize_str(PrefixedHexVisitor)?;
22
23 if decoded.len() != 32 {
24 return Err(D::Error::custom(format!(
25 "expected {} bytes for array, got {}",
26 32,
27 decoded.len()
28 )));
29 }
30
31 let mut array = [0; 32];
32 array.copy_from_slice(&decoded);
33 Ok(array.into())
34}
35
36#[cfg(test)]
37mod test {
38 use super::*;
39 use serde::{Deserialize, Serialize};
40
41 #[derive(Debug, PartialEq, Serialize, Deserialize)]
42 #[serde(transparent)]
43 struct Wrapper {
44 #[serde(with = "super")]
45 val: B256,
46 }
47
48 #[test]
49 fn encoding() {
50 assert_eq!(
51 &serde_json::to_string(&Wrapper { val: B256::ZERO }).unwrap(),
52 "\"0x0000000000000000000000000000000000000000000000000000000000000000\""
53 );
54 assert_eq!(
55 &serde_json::to_string(&Wrapper {
56 val: B256::with_last_byte(0x03)
57 })
58 .unwrap(),
59 "\"0x0000000000000000000000000000000000000000000000000000000000000003\""
60 );
61 assert_eq!(
62 &serde_json::to_string(&Wrapper {
63 val: B256::repeat_byte(0x03)
64 })
65 .unwrap(),
66 "\"0x0303030303030303030303030303030303030303030303030303030303030303\""
67 );
68 }
69
70 #[test]
71 fn decoding() {
72 assert_eq!(
73 serde_json::from_str::<Wrapper>(
74 "\"0x0000000000000000000000000000000000000000000000000000000000000000\""
75 )
76 .unwrap(),
77 Wrapper { val: B256::ZERO },
78 );
79 assert_eq!(
80 serde_json::from_str::<Wrapper>(
81 "\"0x0000000000000000000000000000000000000000000000000000000000000003\""
82 )
83 .unwrap(),
84 Wrapper {
85 val: B256::with_last_byte(0x03)
86 },
87 );
88
89 serde_json::from_str::<Wrapper>(
91 "\"0000000000000000000000000000000000000000000000000000000000000000\"",
92 )
93 .unwrap_err();
94 serde_json::from_str::<Wrapper>(
96 "\"0x00000000000000000000000000000000000000000000000000000000000000\"",
97 )
98 .unwrap_err();
99 }
100}