From 5dab959d886f67700c92d0d0a19418bb1c53f6b4 Mon Sep 17 00:00:00 2001 From: Joseph Livesey Date: Tue, 22 Oct 2024 13:34:43 -0400 Subject: [PATCH] refactor(firehose-protos): use utility function for conversion error --- crates/firehose-protos/src/ethereum_v2.rs | 34 +++++++++++++++++++---- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/crates/firehose-protos/src/ethereum_v2.rs b/crates/firehose-protos/src/ethereum_v2.rs index 2e9242b0..e183442c 100644 --- a/crates/firehose-protos/src/ethereum_v2.rs +++ b/crates/firehose-protos/src/ethereum_v2.rs @@ -4,6 +4,7 @@ use alloy_primitives::{Address, Bloom, FixedBytes, Uint}; use ethportal_api::types::execution::header::Header; use prost::Message; +use prost_wkt_types::Any; use reth_primitives::TxType; use transaction_trace::Type; @@ -115,13 +116,36 @@ impl From for TxType { } } +fn decode_block(response: M) -> Result +where + M: MessageWithBlock, +{ + let any = response.block().ok_or(ProtosError::NullBlock)?; + let block = Block::decode(any.value.as_ref())?; + Ok(block) +} + +trait MessageWithBlock { + fn block(&self) -> Option<&Any>; +} + +impl MessageWithBlock for SingleBlockResponse { + fn block(&self) -> Option<&Any> { + self.block.as_ref() + } +} + +impl MessageWithBlock for Response { + fn block(&self) -> Option<&Any> { + self.block.as_ref() + } +} + impl TryFrom for Block { type Error = ProtosError; fn try_from(response: SingleBlockResponse) -> Result { - let any = response.block.ok_or(ProtosError::NullBlock)?; - let block = Block::decode(any.value.as_ref())?; - Ok(block) + decode_block(response) } } @@ -129,9 +153,7 @@ impl TryFrom for Block { type Error = ProtosError; fn try_from(response: Response) -> Result { - let any = response.block.ok_or(ProtosError::NullBlock)?; - let block = Block::decode(any.value.as_ref())?; - Ok(block) + decode_block(response) } }