Skip to content

Commit

Permalink
feat: add conversions from rpc block to consensus (#1869)
Browse files Browse the repository at this point in the history
* feat: add conversions from rpc block to consensus

* rename
  • Loading branch information
mattsse authored Dec 31, 2024
1 parent 125bd7d commit d630096
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
10 changes: 10 additions & 0 deletions crates/network-primitives/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,16 @@ impl<T> BlockTransactions<T> {
}
}

/// Consumes the type and returns the transactions as a vector.
///
/// Note: if this is an uncle or hashes, this will return an empty vector.
pub fn into_transactions_vec(self) -> Vec<T> {
match self {
Self::Full(txs) => txs,
_ => vec![],
}
}

/// Returns an instance of BlockTransactions with the Uncle special case.
#[inline]
pub const fn uncle() -> Self {
Expand Down
29 changes: 28 additions & 1 deletion crates/rpc-types-eth/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,22 @@ impl<T> Block<T> {
withdrawals,
}
}

/// Consumes the block and returns the [`alloy_consensus::Block`].
///
/// This has two caveats:
/// - The returned block will always have empty uncles.
/// - If the block's transaction is not [`BlockTransactions::Full`], the returned block will
/// have an empty transaction vec.
pub fn into_consensus(self) -> alloy_consensus::Block<T> {
let Self { header, transactions, withdrawals, .. } = self;
alloy_consensus::BlockBody {
transactions: transactions.into_transactions_vec(),
ommers: vec![],
withdrawals,
}
.into_block(header.into_consensus())
}
}

/// RPC representation of block header, wrapping a consensus header.
Expand Down Expand Up @@ -232,6 +248,11 @@ impl<H> Header<H> {
Self { hash, inner, total_difficulty: None, size: None }
}

/// Consumes the type and returns the wrapped consensus header.
pub fn into_consensus(self) -> H {
self.inner
}

/// Create a new [`Header`] from a sealed consensus header and additional fields.
pub fn from_consensus(
header: Sealed<H>,
Expand Down Expand Up @@ -393,6 +414,12 @@ impl<H: BlockHeader> HeaderResponse for Header<H> {
}
}

impl From<Header> for alloy_consensus::Header {
fn from(header: Header) -> Self {
header.into_consensus()
}
}

/// Error that can occur when converting other types to blocks
#[derive(Clone, Copy, Debug, thiserror::Error)]
pub enum BlockError {
Expand Down Expand Up @@ -504,7 +531,7 @@ impl<T: TransactionResponse, H> BlockResponse for Block<T, H> {
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct BadBlock {
/// Underyling block object.
/// Underlying block object.
block: Block,
/// Hash of the block.
hash: BlockHash,
Expand Down

0 comments on commit d630096

Please sign in to comment.