1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use alloy_primitives::B256;
use serde::de::Error;
use serde::{Deserializer, Serializer};

use crate::hex::PrefixedHexVisitor;

pub fn serialize<S>(hash: &B256, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut hex_string: String = "0x".to_string();
    hex_string.push_str(&hex::encode(&hash));

    serializer.serialize_str(&hex_string)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<B256, D::Error>
where
    D: Deserializer<'de>,
{
    let decoded = deserializer.deserialize_str(PrefixedHexVisitor)?;

    if decoded.len() != 32 {
        return Err(D::Error::custom(format!(
            "expected {} bytes for array, got {}",
            32,
            decoded.len()
        )));
    }

    let mut array = [0; 32];
    array.copy_from_slice(&decoded);
    Ok(array.into())
}

#[cfg(test)]
mod test {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    #[serde(transparent)]
    struct Wrapper {
        #[serde(with = "super")]
        val: B256,
    }

    #[test]
    fn encoding() {
        assert_eq!(
            &serde_json::to_string(&Wrapper { val: B256::ZERO }).unwrap(),
            "\"0x0000000000000000000000000000000000000000000000000000000000000000\""
        );
        assert_eq!(
            &serde_json::to_string(&Wrapper {
                val: B256::with_last_byte(0x03)
            })
            .unwrap(),
            "\"0x0000000000000000000000000000000000000000000000000000000000000003\""
        );
        assert_eq!(
            &serde_json::to_string(&Wrapper {
                val: B256::repeat_byte(0x03)
            })
            .unwrap(),
            "\"0x0303030303030303030303030303030303030303030303030303030303030303\""
        );
    }

    #[test]
    fn decoding() {
        assert_eq!(
            serde_json::from_str::<Wrapper>(
                "\"0x0000000000000000000000000000000000000000000000000000000000000000\""
            )
            .unwrap(),
            Wrapper { val: B256::ZERO },
        );
        assert_eq!(
            serde_json::from_str::<Wrapper>(
                "\"0x0000000000000000000000000000000000000000000000000000000000000003\""
            )
            .unwrap(),
            Wrapper {
                val: B256::with_last_byte(0x03)
            },
        );

        // Require 0x.
        serde_json::from_str::<Wrapper>(
            "\"0000000000000000000000000000000000000000000000000000000000000000\"",
        )
        .unwrap_err();
        // Wrong length.
        serde_json::from_str::<Wrapper>(
            "\"0x00000000000000000000000000000000000000000000000000000000000000\"",
        )
        .unwrap_err();
    }
}