Skip to main content

foundry_evm_core/evm/
tx.rs

1//! Network-native transactions.
2//!
3//! Transactions stay in their network's Alloy form until execution: tools keep the selected
4//! [`TransactionRequest`](alloy_network::Network::TransactionRequest) or signed
5//! [`TxEnvelope`](alloy_network::Network::TxEnvelope), mutate common fields through Alloy's
6//! [`TransactionBuilder`], and convert once, right before execution, into the family's evm2
7//! transaction with [`FoundryTxConversion`]. Signed, resumed and replayed transactions convert
8//! from exactly the payload that was signed; nothing is rebuilt from Ethereum-shaped fields.
9
10use super::{ChainFor, FoundryEvmExt, FoundryEvmNetwork, TxFor, TypesFor};
11use alloy_chains::NamedChain;
12use alloy_consensus::{
13    BlockHeader, EthereumTxEnvelope, EthereumTypedTransaction, SignableTransaction, Signed,
14    Transaction, TxEip1559, TxEip4844Variant, Typed2718,
15    transaction::{Recovered, SignerRecoverable},
16};
17use alloy_eips::Decodable2718;
18use alloy_network::{
19    AnyNetwork, AnyRpcBlock, AnyRpcTransaction, AnyTxEnvelope, Network, NetworkTransactionBuilder,
20    TransactionBuilder, TransactionResponse,
21};
22use alloy_primitives::{Address, Signature};
23use alloy_provider::Provider;
24use alloy_rpc_types::{BlockTransactions, TransactionRequest};
25use evm2::{
26    EvmTypesHost,
27    ethereum::{LazyTxEip7702, TxEnvelope},
28};
29use eyre::WrapErr;
30use foundry_evm_networks::celo::CELO_DYNAMIC_FEE_TX_TYPE;
31
32/// Converts an Alloy network's native transactions into an evm2 execution family's transactions.
33///
34/// The family, rather than the transaction type alone, owns conversion: families can share a
35/// transaction representation while retaining different conversion policies and diagnostics.
36pub trait FoundryTxConversion<N: Network>: EvmTypesHost {
37    /// Converts a network envelope sent by `sender`, once, right before execution.
38    fn evm_tx(
39        envelope: N::TxEnvelope,
40        sender: Address,
41        payload: TxPayload,
42    ) -> eyre::Result<Recovered<Self::Tx>>;
43
44    /// Converts a complete unsigned request into a simulated transaction.
45    ///
46    /// The request must name its sender and carry every field its transaction type needs; Foundry
47    /// fills defaults through [`TransactionBuilder`] before converting, never afterwards.
48    fn tx_from_request(request: N::TransactionRequest) -> eyre::Result<Recovered<Self::Tx>>
49    where
50        N::TransactionRequest: NetworkTransactionBuilder<N>,
51        N::UnsignedTx: SignableTransaction<Signature>,
52        N::TxEnvelope: From<Signed<N::UnsignedTx>>,
53    {
54        let sender =
55            request.from().ok_or_else(|| eyre::eyre!("transaction request has no sender"))?;
56        let unsigned =
57            request.build_unsigned().map_err(|err| eyre::eyre!(err.error.to_string()))?;
58        let envelope = N::TxEnvelope::from(unsigned.into_signed(placeholder_signature()));
59        Self::evm_tx(envelope, sender, TxPayload::Simulated)
60    }
61
62    /// Converts a signed envelope into a transaction sent by its recovered signer.
63    fn tx_from_signed(envelope: N::TxEnvelope) -> eyre::Result<Recovered<Self::Tx>>
64    where
65        N::TxEnvelope: SignerRecoverable,
66    {
67        let sender = envelope.recover_signer()?;
68        Self::evm_tx(envelope, sender, TxPayload::Signed)
69    }
70
71    /// Decodes exactly the EIP-2718 bytes that were signed and converts them for execution.
72    fn decode_tx(mut bytes: &[u8]) -> eyre::Result<Recovered<Self::Tx>>
73    where
74        N::TxEnvelope: SignerRecoverable,
75    {
76        let envelope = N::TxEnvelope::decode_2718(&mut bytes)?;
77        eyre::ensure!(bytes.is_empty(), "trailing bytes after the encoded transaction");
78        Self::tx_from_signed(envelope)
79    }
80
81    /// Converts a transaction fetched over RPC into this network's envelope.
82    ///
83    /// Envelopes this family cannot represent fail rather than being projected onto another type.
84    fn envelope_from_any_rpc(tx: &AnyRpcTransaction) -> eyre::Result<N::TxEnvelope>;
85
86    /// Converts a transaction fetched over RPC, using its RPC sender as it executed on chain.
87    fn tx_from_any_rpc(tx: &AnyRpcTransaction) -> eyre::Result<Recovered<Self::Tx>> {
88        Self::evm_tx(Self::envelope_from_any_rpc(tx)?, tx.from(), TxPayload::Signed)
89    }
90}
91
92/// Returns the error for an RPC transaction whose envelope `target` cannot represent.
93pub(crate) fn unknown_transaction_type(tx: &AnyRpcTransaction, target: &str) -> eyre::Report {
94    eyre::eyre!("cannot convert unknown transaction type {:#04x} to {target}", tx.inner.inner.ty())
95}
96
97/// What an execution-time transaction is priced and validated as.
98#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
99pub enum TxPayload {
100    /// The transaction's own signed encoding, as broadcast or replayed.
101    Signed,
102    /// A simulation of an unsigned request.
103    ///
104    /// Networks that price fees over the encoded transaction, such as the OP-stack L1 data fee,
105    /// charge nothing for it, and networks with simulation-only metadata, such as Tempo, mark the
106    /// transaction as simulated.
107    #[default]
108    Simulated,
109}
110
111impl TxPayload {
112    /// Returns whether this is a simulation of an unsigned request.
113    pub const fn is_simulated(self) -> bool {
114        matches!(self, Self::Simulated)
115    }
116}
117
118/// Placeholder signature used to put an unsigned request into its network's envelope.
119///
120/// The sender is always supplied separately, so the signature is never recovered.
121pub fn placeholder_signature() -> Signature {
122    Signature::test_signature()
123}
124
125/// Converts a signed Ethereum envelope into evm2's Ethereum transaction.
126///
127/// Signed EIP-7702 authorizations are kept as signed, so their authorities are recovered during
128/// execution exactly as on chain.
129pub fn eth_tx(envelope: EthereumTxEnvelope<TxEip4844Variant>) -> TxEnvelope {
130    eth_unsigned_tx(match envelope {
131        EthereumTxEnvelope::Legacy(tx) => tx.strip_signature().into(),
132        EthereumTxEnvelope::Eip2930(tx) => tx.strip_signature().into(),
133        EthereumTxEnvelope::Eip1559(tx) => tx.strip_signature().into(),
134        EthereumTxEnvelope::Eip4844(tx) => tx.strip_signature().into(),
135        EthereumTxEnvelope::Eip7702(tx) => tx.strip_signature().into(),
136    })
137}
138
139/// Converts an unsigned Ethereum transaction into evm2's Ethereum transaction.
140fn eth_unsigned_tx(tx: EthereumTypedTransaction<TxEip4844Variant>) -> TxEnvelope {
141    match tx {
142        EthereumTypedTransaction::Legacy(tx) => TxEnvelope::Legacy(tx),
143        EthereumTypedTransaction::Eip2930(tx) => TxEnvelope::Eip2930(tx),
144        EthereumTypedTransaction::Eip1559(tx) => TxEnvelope::Eip1559(tx),
145        EthereumTypedTransaction::Eip4844(tx) => TxEnvelope::Eip4844(tx),
146        EthereumTypedTransaction::Eip7702(tx) => {
147            TxEnvelope::Eip7702(LazyTxEip7702::from_recovered_authorizations(tx))
148        }
149    }
150}
151
152/// Converts a complete unsigned Ethereum request into a simulated evm2 transaction.
153///
154/// evm2's Ethereum transaction has no signature, so this skips the placeholder-signed envelope of
155/// [`FoundryTxConversion::tx_from_request`], which hashes the encoded transaction.
156pub fn eth_tx_from_request(request: TransactionRequest) -> eyre::Result<Recovered<TxEnvelope>> {
157    let sender = request.from.ok_or_else(|| eyre::eyre!("transaction request has no sender"))?;
158    let unsigned = request.build_unsigned().map_err(|err| eyre::eyre!(err.error.to_string()))?;
159    Ok(Recovered::new_unchecked(eth_unsigned_tx(unsigned), sender))
160}
161
162/// Returns the Ethereum envelope of a transaction fetched over RPC.
163///
164/// Celo CIP-64 transactions on Celo chains execute as EIP-1559 transactions with the same fields
165/// and native fees: fee currencies are not supported by evm2.
166pub fn eth_envelope_from_any_rpc(
167    tx: &AnyRpcTransaction,
168    target: &str,
169) -> eyre::Result<alloy_consensus::TxEnvelope> {
170    match &*tx.inner.inner {
171        AnyTxEnvelope::Ethereum(envelope) => Ok(envelope.clone()),
172        AnyTxEnvelope::Unknown(unknown)
173            if unknown.ty() == CELO_DYNAMIC_FEE_TX_TYPE
174                && matches!(
175                    unknown.chain_id().and_then(NamedChain::from_chain_id),
176                    Some(NamedChain::Celo | NamedChain::CeloSepolia)
177                ) =>
178        {
179            let mut fields = unknown.inner.fields().clone();
180            fields.insert("hash".into(), serde_json::to_value(unknown.hash)?);
181            let signed = fields
182                .deserialize_into::<Signed<TxEip1559>>()
183                .wrap_err("invalid Celo CIP-64 transaction")?;
184            Ok(signed.into())
185        }
186        _ => Err(unknown_transaction_type(tx, target)),
187    }
188}
189
190/// Transactions of a block and its two ancestors, for network state that depends on the block
191/// position of a transaction (see [`FoundryEvmExt::for_block`]).
192#[derive(Clone, Debug)]
193pub struct BlockContext<FEN: FoundryEvmNetwork> {
194    grandparent: Vec<Recovered<TxFor<FEN>>>,
195    parent: Vec<Recovered<TxFor<FEN>>>,
196    current: Vec<Recovered<TxFor<FEN>>>,
197}
198
199impl<FEN: FoundryEvmNetwork> BlockContext<FEN> {
200    /// Creates block context from grandparent, parent, and current block transactions.
201    pub const fn new(
202        grandparent: Vec<Recovered<TxFor<FEN>>>,
203        parent: Vec<Recovered<TxFor<FEN>>>,
204        current: Vec<Recovered<TxFor<FEN>>>,
205    ) -> Self {
206        Self { grandparent, parent, current }
207    }
208
209    /// Fetches the ancestors of `block` and converts the transactions of all three blocks.
210    pub async fn fetch<P: Provider<AnyNetwork>>(
211        provider: &P,
212        block: &AnyRpcBlock,
213    ) -> eyre::Result<Self> {
214        let parent = fetch_parent(provider, block).await?;
215        let grandparent = match &parent {
216            Some(parent) => fetch_parent(provider, parent).await?,
217            None => None,
218        };
219        Ok(Self::new(
220            grandparent.as_ref().map(block_txs::<FEN>).transpose()?.unwrap_or_default(),
221            parent.as_ref().map(block_txs::<FEN>).transpose()?.unwrap_or_default(),
222            block_txs::<FEN>(block)?,
223        ))
224    }
225
226    /// Prepares `ext` for the transaction at `index` in the current block.
227    pub fn prepare(&self, ext: &mut ChainFor<FEN>, index: usize) {
228        ext.for_block(&self.grandparent, &self.parent, &self.current, index);
229    }
230
231    /// Prepares `ext` for `tx` appended after the current block's transactions so far.
232    pub fn prepare_next(&self, ext: &mut ChainFor<FEN>, tx: &Recovered<TxFor<FEN>>) {
233        let mut current = self.current.clone();
234        let index = current.len();
235        current.push(tx.clone());
236        ext.for_block(&self.grandparent, &self.parent, &current, index);
237    }
238
239    /// Returns a cursor positioned immediately before `index` in the current block.
240    pub fn before_transaction(mut self, index: usize) -> eyre::Result<Self> {
241        eyre::ensure!(
242            index <= self.current.len(),
243            "transaction index {index} exceeds block transaction count {}",
244            self.current.len()
245        );
246        self.current.truncate(index);
247        Ok(self)
248    }
249
250    /// Records a committed transaction at the cursor's current block position.
251    pub fn record_transaction(&mut self, tx: Recovered<TxFor<FEN>>) {
252        self.current.push(tx);
253    }
254
255    /// Advances the cursor to the start of the next block.
256    pub fn advance_block(&mut self) {
257        self.grandparent = std::mem::take(&mut self.parent);
258        self.parent = std::mem::take(&mut self.current);
259    }
260}
261
262/// Fetches the parent of `block`, or `None` for genesis.
263async fn fetch_parent<P: Provider<AnyNetwork>>(
264    provider: &P,
265    block: &AnyRpcBlock,
266) -> eyre::Result<Option<AnyRpcBlock>> {
267    let parent_hash = block.header.parent_hash();
268    if parent_hash.is_zero() {
269        return Ok(None);
270    }
271    let parent = provider
272        .get_block_by_hash(parent_hash)
273        .full()
274        .await
275        .wrap_err_with(|| format!("failed to fetch ancestor block {parent_hash}"))?
276        .ok_or_else(|| eyre::eyre!("ancestor block {parent_hash} not found"))?;
277    eyre::ensure!(
278        parent.header.hash == parent_hash
279            && Some(parent.header.number()) == block.header.number().checked_sub(1),
280        "ancestor block {parent_hash} does not match its child"
281    );
282    Ok(Some(parent))
283}
284
285/// Converts every transaction of a full RPC block.
286pub fn block_txs<FEN: FoundryEvmNetwork>(
287    block: &AnyRpcBlock,
288) -> eyre::Result<Vec<Recovered<TxFor<FEN>>>> {
289    full_transactions(block)?.iter().map(TypesFor::<FEN>::tx_from_any_rpc).collect()
290}
291
292/// Returns the transactions of `block`, which must contain full transactions.
293pub(crate) fn full_transactions(block: &AnyRpcBlock) -> eyre::Result<&[AnyRpcTransaction]> {
294    let BlockTransactions::Full(transactions) = &block.transactions else {
295        eyre::bail!("block {} does not contain full transactions", block.header.number());
296    };
297    Ok(transactions)
298}