anvil_zksync_types/
serde_helpers.rs

1use serde::Deserialize;
2use zksync_types::U64;
3
4/// Helper type to be able to parse both integers (as `u64`) and hex strings (as `U64`) depending on
5/// the user input.
6#[derive(Copy, Clone, Deserialize)]
7#[serde(untagged)]
8pub enum Numeric {
9    /// A [U64] value.
10    U64(U64),
11    /// A `u64` value.
12    Num(u64),
13}
14
15impl From<u64> for Numeric {
16    fn from(value: u64) -> Self {
17        Numeric::Num(value)
18    }
19}
20
21impl From<Numeric> for u64 {
22    fn from(value: Numeric) -> Self {
23        match value {
24            Numeric::U64(value) => value.as_u64(),
25            Numeric::Num(value) => value,
26        }
27    }
28}
29
30#[cfg(test)]
31mod tests {
32    use crate::serde_helpers::Numeric;
33
34    #[test]
35    fn test_deserialize() {
36        let tests = [
37            // Hex strings
38            ("\"0x0\"", 0u64),
39            ("\"0x1\"", 1u64),
40            ("\"0x2\"", 2u64),
41            ("\"0xa\"", 10u64),
42            ("\"0xf\"", 15u64),
43            ("\"0x10\"", 16u64),
44            ("\"0\"", 0u64),
45            ("\"1\"", 1u64),
46            ("\"2\"", 2u64),
47            ("\"a\"", 10u64),
48            ("\"f\"", 15u64),
49            ("\"10\"", 16u64),
50            // Numbers
51            ("0", 0u64),
52            ("1", 1u64),
53            ("2", 2u64),
54            ("10", 10u64),
55            ("15", 15u64),
56            ("16", 16u64),
57        ];
58        for (serialized, expected_value) in tests {
59            let actual_value: Numeric = serde_json::from_str(serialized).unwrap();
60            assert_eq!(u64::from(actual_value), expected_value);
61        }
62    }
63}