diff --git a/Cargo.toml b/Cargo.toml index c31d78d..c5e9ddb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ categories = ["cryptography::cryptocurrencies"] name = "serde_utils" [dependencies] -alloy-primitives = { version = "0.7.0", features = ["ssz", "serde"] } +alloy-primitives = { version = "0.7.7", features = ["serde"] } serde = { version = "1.0.0", features = ["derive"] } serde_derive = "1.0.0" serde_json = "1.0.0" diff --git a/src/address_hex.rs b/src/address_hex.rs new file mode 100644 index 0000000..9a132f1 --- /dev/null +++ b/src/address_hex.rs @@ -0,0 +1,34 @@ +use alloy_primitives::Address; +use serde::de::Error; +use serde::{Deserializer, Serializer}; + +use crate::hex::PrefixedHexVisitor; + +pub fn serialize(address: &Address, serializer: S) -> Result +where + S: Serializer, +{ + let mut hex_string: String = "0x".to_string(); + hex_string.push_str(&hex::encode(&address)); + + serializer.serialize_str(&hex_string) +} + +pub fn deserialize<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let decoded = deserializer.deserialize_str(PrefixedHexVisitor)?; + + if decoded.len() != 20 { + return Err(D::Error::custom(format!( + "expected {} bytes for array, got {}", + 20, + decoded.len() + ))); + } + + let mut array = [0; 20]; + array.copy_from_slice(&decoded); + Ok(array.into()) +} diff --git a/src/b256_hex.rs b/src/b256_hex.rs new file mode 100644 index 0000000..1ddea36 --- /dev/null +++ b/src/b256_hex.rs @@ -0,0 +1,34 @@ +use alloy_primitives::B256; +use serde::de::Error; +use serde::{Deserializer, Serializer}; + +use crate::hex::PrefixedHexVisitor; + +pub fn serialize(hash: &B256, serializer: S) -> Result +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 +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()) +} diff --git a/src/lib.rs b/src/lib.rs index 1813f95..a2a1f64 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ mod quoted_int; +pub mod address_hex; +pub mod b256_hex; pub mod fixed_bytes_hex; pub mod hex; pub mod hex_vec;