diff --git a/crates/network-primitives/src/block.rs b/crates/network-primitives/src/block.rs index be9f7c3e90b..02d66a905ee 100644 --- a/crates/network-primitives/src/block.rs +++ b/crates/network-primitives/src/block.rs @@ -46,6 +46,33 @@ impl BlockTransactions { matches!(self, Self::Full(_)) } + /// Converts the transaction type by applying a function to each transaction. + /// + /// Returns the block with the new transaction type. + pub fn map(self, f: impl FnMut(T) -> U) -> BlockTransactions { + match self { + Self::Full(txs) => BlockTransactions::Full(txs.into_iter().map(f).collect()), + Self::Hashes(hashes) => BlockTransactions::Hashes(hashes), + Self::Uncle => BlockTransactions::Uncle, + } + } + + /// Converts the transaction type by applying a fallible function to each transaction. + /// + /// Returns the block with the new transaction type if all transactions were successfully. + pub fn try_map( + self, + f: impl FnMut(T) -> Result, + ) -> Result, E> { + match self { + Self::Full(txs) => { + Ok(BlockTransactions::Full(txs.into_iter().map(f).collect::>()?)) + } + Self::Hashes(hashes) => Ok(BlockTransactions::Hashes(hashes)), + Self::Uncle => Ok(BlockTransactions::Uncle), + } + } + /// Fallibly cast to a slice of transactions. /// /// Returns `None` if the enum variant is not `Full`. diff --git a/crates/rpc-types-eth/src/block.rs b/crates/rpc-types-eth/src/block.rs index 1883a7ec640..c4c67dbaca6 100644 --- a/crates/rpc-types-eth/src/block.rs +++ b/crates/rpc-types-eth/src/block.rs @@ -16,7 +16,7 @@ pub use alloy_eips::{ BlockNumberOrTag, ForkBlock, RpcBlockHash, }; -/// Block representation +/// Block representation for RPC. #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] @@ -54,6 +54,35 @@ impl Default for Block { } } +impl Block { + /// Converts the block's transaction type by applying a function to each transaction. + /// + /// Returns the block with the new transaction type. + pub fn map_transactions(self, f: impl FnMut(T) -> U) -> Block { + Block { + header: self.header, + uncles: self.uncles, + transactions: self.transactions.map(f), + withdrawals: self.withdrawals, + } + } + + /// Converts the block's transaction type by applying a fallible function to each transaction. + /// + /// Returns the block with the new transaction type if all transactions were successfully. + pub fn try_map_transactions( + self, + f: impl FnMut(T) -> Result, + ) -> Result, E> { + Ok(Block { + header: self.header, + uncles: self.uncles, + transactions: self.transactions.try_map(f)?, + withdrawals: self.withdrawals, + }) + } +} + impl Block { /// Converts a block with Tx hashes into a full block. pub fn into_full_block(self, txs: Vec) -> Self {