1use 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
32pub trait FoundryTxConversion<N: Network>: EvmTypesHost {
37 fn evm_tx(
39 envelope: N::TxEnvelope,
40 sender: Address,
41 payload: TxPayload,
42 ) -> eyre::Result<Recovered<Self::Tx>>;
43
44 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 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 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 fn envelope_from_any_rpc(tx: &AnyRpcTransaction) -> eyre::Result<N::TxEnvelope>;
85
86 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
92pub(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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
99pub enum TxPayload {
100 Signed,
102 #[default]
108 Simulated,
109}
110
111impl TxPayload {
112 pub const fn is_simulated(self) -> bool {
114 matches!(self, Self::Simulated)
115 }
116}
117
118pub fn placeholder_signature() -> Signature {
122 Signature::test_signature()
123}
124
125pub 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
139fn 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
152pub 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
162pub 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#[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 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 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 pub fn prepare(&self, ext: &mut ChainFor<FEN>, index: usize) {
228 ext.for_block(&self.grandparent, &self.parent, &self.current, index);
229 }
230
231 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, ¤t, index);
237 }
238
239 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 pub fn record_transaction(&mut self, tx: Recovered<TxFor<FEN>>) {
252 self.current.push(tx);
253 }
254
255 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
262async 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
285pub 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
292pub(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}