From c6a79603d44ebe0d3c04674ea00706a8725b8acc Mon Sep 17 00:00:00 2001 From: incrypto32 Date: Mon, 18 Nov 2024 15:54:58 +0400 Subject: [PATCH] graph: implement custom deserializer for BlockTime --- graph/src/blockchain/types.rs | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/graph/src/blockchain/types.rs b/graph/src/blockchain/types.rs index 7186dccf42b..f060b66b2c5 100644 --- a/graph/src/blockchain/types.rs +++ b/graph/src/blockchain/types.rs @@ -355,6 +355,25 @@ where } } +fn deserialize_block_time<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let value = String::deserialize(deserializer)?; + + if value.starts_with("0x") { + let hex_value = value.trim_start_matches("0x"); + + i64::from_str_radix(hex_value, 16) + .map(|secs| BlockTime::since_epoch(secs, 0)) + .map_err(serde::de::Error::custom) + } else { + value + .parse::() + .map(|secs| BlockTime::since_epoch(secs, 0)) + .map_err(serde::de::Error::custom) + } +} #[derive(Clone, PartialEq, Eq, Hash, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BlockPtrExt { @@ -362,6 +381,7 @@ pub struct BlockPtrExt { #[serde(deserialize_with = "deserialize_block_number")] pub number: BlockNumber, pub parent_hash: BlockHash, + #[serde(deserialize_with = "deserialize_block_time")] pub timestamp: BlockTime, } @@ -666,8 +686,8 @@ mod tests { { "hash": "0x8186da3ec5590631ae7b9415ce58548cb98c7f1dc68c5ea1c519a3f0f6a25aac", "number": "0x2A", - "parentHash": "0xabc123", - "timestamp": "123456789012345678901234567890" + "parentHash": "0xd71699894d637632dea4d425396086edf033c1ff72b13753e8c4e67700e3eb8e", + "timestamp": "0x673b284f" } "#; @@ -677,6 +697,12 @@ mod tests { // Verify the deserialized values assert_eq!(block_ptr_ext.number, 42); // 0x2A in hex is 42 in decimal + assert_eq!( + block_ptr_ext.hash_hex(), + "8186da3ec5590631ae7b9415ce58548cb98c7f1dc68c5ea1c519a3f0f6a25aac" + ); + assert_eq!(block_ptr_ext.parent_hash_hex(), "d71699894d637632dea4d425396086edf033c1ff72b13753e8c4e67700e3eb8e"); + assert_eq!(block_ptr_ext.timestamp.0.as_secs_since_epoch(), 1731930191); } #[test] @@ -685,7 +711,7 @@ mod tests { { "hash": "0x8186da3ec5590631ae7b9415ce58548cb98c7f1dc68c5ea1c519a3f0f6a25aac", "number": "invalid_hex_string", - "parentHash": "0xabc123", + "parentHash": "0xd71699894d637632dea4d425396086edf033c1ff72b13753e8c4e67700e3eb8e", "timestamp": "123456789012345678901234567890" } "#;