Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define TransactionRespConstructor #1316

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion crates/network-primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,14 @@

extern crate alloc;

pub mod transaction;
pub use transaction::TransactionInfo;

mod traits;
pub use traits::{BlockResponse, HeaderResponse, ReceiptResponse, TransactionResponse};
pub use traits::{
BlockResponse, Constructor, HeaderResponse, ReceiptResponse, TransactionRespConstructor,
TransactionResponse,
};

mod block;
pub use block::{BlockTransactionHashes, BlockTransactions, BlockTransactionsKind};
35 changes: 34 additions & 1 deletion crates/network-primitives/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ use alloy_serde::WithOtherFields;

use crate::BlockTransactions;

/// Universal constructor trait.
pub trait Constructor {
/// Data needed to construct type.
type Data<'a>;

/// Instantiates a new type from given data.
fn new(data: Self::Data<'_>) -> Self;
}

/// Receipt JSON-RPC response.
pub trait ReceiptResponse {
/// Address of the created contract, or `None` if the transaction was not a deployment.
Expand Down Expand Up @@ -61,8 +70,18 @@ pub trait ReceiptResponse {
fn state_root(&self) -> Option<B256>;
}

/// Constructs an RPC response transaction.
pub trait TransactionRespConstructor: Constructor {
/// Transaction data.
type UnsignedTx;
/// Signature of transaction.
type Signature;
/// Block context required for assembling the transaction for a RPC response.
type BlockCtx;
}

/// Transaction JSON-RPC response.
pub trait TransactionResponse {
pub trait TransactionResponse: TransactionRespConstructor {
/// Hash of the transaction
#[doc(alias = "transaction_hash")]
fn tx_hash(&self) -> TxHash;
Expand Down Expand Up @@ -151,6 +170,20 @@ pub trait BlockResponse {
}
}

impl<T: Constructor> Constructor for WithOtherFields<T> {
type Data<'a> = T::Data<'a>;

fn new(data: Self::Data<'_>) -> Self {
Self { inner: T::new(data), other: Default::default() }
}
}

impl<T: TransactionRespConstructor> TransactionRespConstructor for WithOtherFields<T> {
type UnsignedTx = T::UnsignedTx;
type Signature = T::Signature;
type BlockCtx = T::BlockCtx;
}

impl<T: TransactionResponse> TransactionResponse for WithOtherFields<T> {
fn tx_hash(&self) -> TxHash {
self.inner.tx_hash()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! Commonly used additional types that are not part of the JSON RPC spec but are often required
//! when working with RPC types, such as [Transaction]
//! when working with RPC type [`TransactionResponse`](crate::TransactionResponse).

use crate::Transaction;
use alloy_primitives::{BlockHash, TxHash};

/// Additional fields in the context of a block that contains this transaction.
Expand All @@ -27,17 +26,3 @@ impl TransactionInfo {
self
}
}

impl From<&Transaction> for TransactionInfo {
fn from(tx: &Transaction) -> Self {
Self {
hash: Some(tx.hash),
index: tx.transaction_index,
block_hash: tx.block_hash,
block_number: tx.block_number,
// We don't know the base fee of the block when we're constructing this from
// `Transaction`
base_fee: None,
}
}
}
2 changes: 1 addition & 1 deletion crates/rpc-types-eth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ alloy-rlp = { workspace = true, features = ["arrayvec", "derive"] }
alloy-primitives = { workspace = true, features = ["rlp"] }

itertools.workspace = true
derive_more = { workspace = true, features = ["display"] }
derive_more = { workspace = true, features = ["display", "constructor"] }

# serde
alloy-serde = { workspace = true, optional = true }
Expand Down
124 changes: 118 additions & 6 deletions crates/rpc-types-eth/src/transaction/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
//! RPC types for transactions

use alloy_consensus::{
SignableTransaction, Signed, TxEip1559, TxEip2930, TxEip4844, TxEip4844Variant, TxEip7702,
TxEnvelope, TxLegacy, TxType,
SignableTransaction, Signed, Transaction as _, TxEip1559, TxEip2930, TxEip4844,
TxEip4844Variant, TxEip7702, TxEnvelope, TxLegacy, TxType,
};
use alloy_eips::eip7702::SignedAuthorization;
use alloy_network_primitives::TransactionResponse;
use alloy_network_primitives::{
Constructor, TransactionInfo, TransactionRespConstructor, TransactionResponse,
};
use alloy_primitives::{Address, BlockHash, Bytes, ChainId, TxHash, TxKind, B256, U256};

use alloc::vec::Vec;
Expand All @@ -16,9 +18,6 @@ pub use alloy_eips::{
eip7702::Authorization,
};

mod common;
pub use common::TransactionInfo;

mod error;
pub use error::ConversionError;

Expand Down Expand Up @@ -338,6 +337,77 @@ impl TryFrom<Transaction> for TxEnvelope {
}
}

impl TransactionRespConstructor for Transaction {
type UnsignedTx = TxEnvelope;
type Signature = alloy_primitives::Signature;
type BlockCtx = TransactionInfo;
}

impl Constructor for Transaction {
type Data<'a> = TransactionResponseData<
<Self as TransactionRespConstructor>::UnsignedTx,
<Self as TransactionRespConstructor>::Signature,
<Self as TransactionRespConstructor>::BlockCtx,
>;

fn new(data: Self::Data<'_>) -> Self {
let TransactionResponseData { signed_tx, signer: from, tx_info } = data;

let (tx, signature, hash) = signed_tx.into_parts();

let TransactionInfo {
block_hash, block_number, base_fee, index: transaction_index, ..
} = tx_info;

let transaction_type = TxType::try_from(tx.ty()).expect("should decode");

// formats max fee per gas for the rpc response w.r.t. hard fork
let max_fee_per_gas = match transaction_type {
TxType::Legacy | TxType::Eip2930 => None,
TxType::Eip1559 | TxType::Eip4844 | TxType::Eip7702 => Some(tx.max_fee_per_gas()),
};

// formats gas price for the rpc response, as it should be shown w.r.t. hard fork
let gas_price = match transaction_type {
TxType::Legacy | TxType::Eip2930 => tx.max_fee_per_gas(),
TxType::Eip1559 | TxType::Eip4844 | TxType::Eip7702 => {
// the gas price field for EIP1559 is set to `min(tip, gasFeeCap - baseFee) +
// baseFee`
base_fee
.and_then(|base_fee| {
tx.effective_tip_per_gas(base_fee as u64).map(|tip| tip + base_fee)
})
.unwrap_or_else(|| tx.max_fee_per_gas())
}
};

Self {
hash,
nonce: tx.nonce(),
from,
to: tx.to().to().copied(),
value: tx.value(),
gas_price: Some(gas_price),
max_fee_per_gas,
max_priority_fee_per_gas: tx.max_priority_fee_per_gas(),
signature: Some(signature.into()),
gas: tx.gas_limit(),
input: tx.input().to_vec().into(),
chain_id: tx.chain_id(),
access_list: tx.access_list().cloned(),
transaction_type: Some(tx.ty()),
block_hash,
block_number,
transaction_index,
// EIP-4844 fields //
max_fee_per_blob_gas: tx.max_fee_per_blob_gas(),
blob_versioned_hashes: tx.blob_versioned_hashes().map(|hashes| hashes.to_vec()),
// --------------- //
authorization_list: tx.authorization_list().map(|l| l.to_vec()),
}
}
}

impl TransactionResponse for Transaction {
fn tx_hash(&self) -> B256 {
self.hash
Expand All @@ -363,6 +433,48 @@ impl TransactionResponse for Transaction {
&self.input
}
}

impl From<&Transaction> for TransactionInfo {
fn from(tx: &Transaction) -> Self {
Self {
hash: Some(tx.hash),
index: tx.transaction_index,
block_hash: tx.block_hash,
block_number: tx.block_number,
// We don't know the base fee of the block when we're constructing this from
// `Transaction`
base_fee: None,
}
}
}

/// Data needed to construct a [`Transaction`].
#[derive(Debug, derive_more::Constructor)]
pub struct TransactionResponseData<TxUnsigned, Signature, BlockCtx> {
/// Transaction with signature.
signed_tx: Signed<TxUnsigned, Signature>,
/// Transaction sender.
signer: Address,
/// Transaction context from block.
tx_info: BlockCtx,
}

impl<TxUnsigned, Signature, BlockCtx> TransactionResponseData<TxUnsigned, Signature, BlockCtx> {
/// Returns a new instance from the parts, without verifying the signature.
pub const fn new_unchecked(
tx: TxUnsigned,
sig: Signature,
tx_hash: B256,
signer: Address,
tx_info: BlockCtx,
) -> Self
where
TxUnsigned: SignableTransaction<Signature>,
{
Self::new(Signed::new_unchecked(tx, sig, tx_hash), signer, tx_info)
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down