Skip to content

Commit a3891bb

Browse files
committed
graph: implement custom deserializer for BlockTime
1 parent a3b03a3 commit a3891bb

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

graph/src/blockchain/types.rs

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -355,13 +355,33 @@ where
355355
}
356356
}
357357

358+
fn deserialize_block_time<'de, D>(deserializer: D) -> Result<BlockTime, D::Error>
359+
where
360+
D: Deserializer<'de>,
361+
{
362+
let value = String::deserialize(deserializer)?;
363+
364+
if value.starts_with("0x") {
365+
let hex_value = value.trim_start_matches("0x");
366+
367+
i64::from_str_radix(hex_value, 16)
368+
.map(|secs| BlockTime::since_epoch(secs, 0))
369+
.map_err(serde::de::Error::custom)
370+
} else {
371+
value
372+
.parse::<i64>()
373+
.map(|secs| BlockTime::since_epoch(secs, 0))
374+
.map_err(serde::de::Error::custom)
375+
}
376+
}
358377
#[derive(Clone, PartialEq, Eq, Hash, Deserialize)]
359378
#[serde(rename_all = "camelCase")]
360379
pub struct ExtendedBlockPtr {
361380
pub hash: BlockHash,
362381
#[serde(deserialize_with = "deserialize_block_number")]
363382
pub number: BlockNumber,
364383
pub parent_hash: BlockHash,
384+
#[serde(deserialize_with = "deserialize_block_time")]
365385
pub timestamp: BlockTime,
366386
}
367387

@@ -666,8 +686,8 @@ mod tests {
666686
{
667687
"hash": "0x8186da3ec5590631ae7b9415ce58548cb98c7f1dc68c5ea1c519a3f0f6a25aac",
668688
"number": "0x2A",
669-
"parentHash": "0xabc123",
670-
"timestamp": "123456789012345678901234567890"
689+
"parentHash": "0xd71699894d637632dea4d425396086edf033c1ff72b13753e8c4e67700e3eb8e",
690+
"timestamp": "0x673b284f"
671691
}
672692
"#;
673693

@@ -677,6 +697,15 @@ mod tests {
677697

678698
// Verify the deserialized values
679699
assert_eq!(block_ptr_ext.number, 42); // 0x2A in hex is 42 in decimal
700+
assert_eq!(
701+
block_ptr_ext.hash_hex(),
702+
"8186da3ec5590631ae7b9415ce58548cb98c7f1dc68c5ea1c519a3f0f6a25aac"
703+
);
704+
assert_eq!(
705+
block_ptr_ext.parent_hash_hex(),
706+
"d71699894d637632dea4d425396086edf033c1ff72b13753e8c4e67700e3eb8e"
707+
);
708+
assert_eq!(block_ptr_ext.timestamp.0.as_secs_since_epoch(), 1731930191);
680709
}
681710

682711
#[test]
@@ -685,7 +714,7 @@ mod tests {
685714
{
686715
"hash": "0x8186da3ec5590631ae7b9415ce58548cb98c7f1dc68c5ea1c519a3f0f6a25aac",
687716
"number": "invalid_hex_string",
688-
"parentHash": "0xabc123",
717+
"parentHash": "0xd71699894d637632dea4d425396086edf033c1ff72b13753e8c4e67700e3eb8e",
689718
"timestamp": "123456789012345678901234567890"
690719
}
691720
"#;

0 commit comments

Comments
 (0)