Skip to main content

reth_rpc_eth_api/helpers/
transaction.rs

1//! Database access for `eth_` transaction RPC methods. Loads transaction and receipt data w.r.t.
2//! network.
3
4use super::{EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadReceipt, LoadState, SpawnBlocking};
5use crate::{
6    helpers::{estimate::EstimateCall, spec::SignersForRpc},
7    FromEthApiError, FullEthApiTypes, IntoEthApiError, RpcNodeCore, RpcNodeCoreExt, RpcReceipt,
8    RpcTransaction,
9};
10use alloy_consensus::{
11    transaction::{SignerRecoverable, TransactionMeta, TxHashRef},
12    BlockHeader, Transaction,
13};
14use alloy_dyn_abi::TypedData;
15use alloy_eips::{eip2718::Encodable2718, BlockId};
16use alloy_network::{TransactionBuilder, TransactionBuilder4844};
17use alloy_primitives::{Address, Bytes, TxHash, B256, U256};
18use alloy_rpc_types_eth::{BlockNumberOrTag, TransactionInfo};
19use futures::{Future, StreamExt};
20use reth_chain_state::CanonStateSubscriptions;
21use reth_primitives_traits::{
22    BlockBody, Recovered, RecoveredBlock, SignedTransaction, TxTy, WithEncoded,
23};
24use reth_rpc_convert::{transaction::RpcConvert, RpcTxReq, TransactionConversionError};
25use reth_rpc_eth_types::{
26    block::convert_transaction_receipt,
27    utils::{binary_search, recover_raw_transaction},
28    EthApiError::{self, TransactionConfirmationTimeout},
29    FillTransaction, SignError, TransactionSource,
30};
31use reth_storage_api::{
32    BlockNumReader, BlockReaderIdExt, ProviderBlock, ProviderReceipt, ProviderTx, ReceiptProvider,
33    TransactionsProvider,
34};
35use reth_transaction_pool::{
36    AddedTransactionOutcome, PoolPooledTx, PoolTransaction, TransactionOrigin, TransactionPool,
37};
38use std::{sync::Arc, time::Duration};
39
40/// Transaction related functions for the [`EthApiServer`](crate::EthApiServer) trait in
41/// the `eth_` namespace.
42///
43/// This includes utilities for transaction tracing, transacting and inspection.
44///
45/// Async functions that are spawned onto the
46/// [`BlockingTaskPool`](reth_tasks::pool::BlockingTaskPool) begin with `spawn_`
47///
48/// ## Calls
49///
50/// There are subtle differences between when transacting [`RpcTxReq`]:
51///
52/// The endpoints `eth_call` and `eth_estimateGas` and `eth_createAccessList` should always
53/// __disable__ the base fee check in the [`CfgEnv`](revm::context::CfgEnv).
54///
55/// The behaviour for tracing endpoints is not consistent across clients.
56/// Geth also disables the basefee check for tracing: <https://github.com/ethereum/go-ethereum/blob/bc0b87ca196f92e5af49bd33cc190ef0ec32b197/eth/tracers/api.go#L955-L955>
57/// Erigon does not: <https://github.com/ledgerwatch/erigon/blob/aefb97b07d1c4fd32a66097a24eddd8f6ccacae0/turbo/transactions/tracing.go#L209-L209>
58///
59/// See also <https://github.com/paradigmxyz/reth/issues/6240>
60///
61/// This implementation follows the behaviour of Geth and disables the basefee check for tracing.
62pub trait EthTransactions: LoadTransaction<Provider: BlockReaderIdExt> {
63    /// Returns a handle for signing data.
64    ///
65    /// Signer access in default (L1) trait method implementations.
66    fn signers(&self) -> &SignersForRpc<Self::Provider, Self::NetworkTypes>;
67
68    /// Returns a list of addresses owned by provider.
69    fn accounts(&self) -> Vec<Address> {
70        self.signers().read().iter().flat_map(|s| s.accounts()).collect()
71    }
72
73    /// Returns the timeout duration for `send_raw_transaction_sync` RPC method.
74    fn send_raw_transaction_sync_timeout(&self) -> Duration;
75
76    /// Decodes and recovers the transaction and submits it to the pool.
77    ///
78    /// Returns the hash of the transaction.
79    fn send_raw_transaction(
80        &self,
81        tx: Bytes,
82    ) -> impl Future<Output = Result<B256, Self::Error>> + Send {
83        async move {
84            let recovered = recover_raw_transaction::<PoolPooledTx<Self::Pool>>(&tx)?;
85            self.send_transaction(TransactionOrigin::External, WithEncoded::new(tx, recovered))
86                .await
87        }
88    }
89
90    /// Submits the transaction to the pool with the given [`TransactionOrigin`].
91    fn send_transaction(
92        &self,
93        origin: TransactionOrigin,
94        tx: WithEncoded<Recovered<PoolPooledTx<Self::Pool>>>,
95    ) -> impl Future<Output = Result<B256, Self::Error>> + Send;
96
97    /// Decodes and recovers the transaction and submits it to the pool.
98    ///
99    /// And awaits the receipt.
100    fn send_raw_transaction_sync(
101        &self,
102        tx: Bytes,
103    ) -> impl Future<Output = Result<RpcReceipt<Self::NetworkTypes>, Self::Error>> + Send
104    where
105        Self: LoadReceipt + 'static,
106    {
107        let this = self.clone();
108        let timeout_duration = self.send_raw_transaction_sync_timeout();
109        async move {
110            let mut stream = this.provider().canonical_state_stream();
111            let hash = EthTransactions::send_raw_transaction(&this, tx).await?;
112            tokio::time::timeout(timeout_duration, async {
113                while let Some(notification) = stream.next().await {
114                    let chain = notification.committed();
115                    if let Some((block, tx, receipt, all_receipts)) =
116                        chain.find_transaction_and_receipt_by_hash(hash) &&
117                        let Some(receipt) = convert_transaction_receipt(
118                            block,
119                            all_receipts,
120                            tx,
121                            receipt,
122                            this.converter(),
123                        )
124                        .transpose()
125                        .map_err(Self::Error::from)?
126                    {
127                        return Ok(receipt);
128                    }
129                }
130                Err(Self::Error::from_eth_err(TransactionConfirmationTimeout {
131                    hash,
132                    duration: timeout_duration,
133                }))
134            })
135            .await
136            .unwrap_or_else(|_elapsed| {
137                Err(Self::Error::from_eth_err(TransactionConfirmationTimeout {
138                    hash,
139                    duration: timeout_duration,
140                }))
141            })
142        }
143    }
144
145    /// Returns the transaction by hash.
146    ///
147    /// Checks the pool and state.
148    ///
149    /// Returns `Ok(None)` if no matching transaction was found.
150    #[expect(clippy::complexity)]
151    fn transaction_by_hash(
152        &self,
153        hash: B256,
154    ) -> impl Future<
155        Output = Result<Option<TransactionSource<ProviderTx<Self::Provider>>>, Self::Error>,
156    > + Send {
157        LoadTransaction::transaction_by_hash(self, hash)
158    }
159
160    /// Get all transactions in the block with the given hash.
161    ///
162    /// Returns `None` if block does not exist.
163    #[expect(clippy::type_complexity)]
164    fn transactions_by_block(
165        &self,
166        block: B256,
167    ) -> impl Future<Output = Result<Option<Vec<ProviderTx<Self::Provider>>>, Self::Error>> + Send
168    {
169        async move {
170            self.cache()
171                .get_recovered_block(block)
172                .await
173                .map(|b| b.map(|b| b.body().transactions().to_vec()))
174                .map_err(Self::Error::from_eth_err)
175        }
176    }
177
178    /// Returns the EIP-2718 encoded transaction by hash.
179    ///
180    /// If this is a pooled EIP-4844 transaction, the blob sidecar is included.
181    ///
182    /// Checks the pool and state.
183    ///
184    /// Returns `Ok(None)` if no matching transaction was found.
185    fn raw_transaction_by_hash(
186        &self,
187        hash: B256,
188    ) -> impl Future<Output = Result<Option<Bytes>, Self::Error>> + Send {
189        async move {
190            // Note: this is mostly used to fetch pooled transactions so we check the pool first
191            if let Some(tx) =
192                self.pool().get_pooled_transaction_element(hash).map(|tx| tx.encoded_2718().into())
193            {
194                return Ok(Some(tx))
195            }
196
197            self.spawn_blocking_io(move |ref this| {
198                Ok(this
199                    .provider()
200                    .transaction_by_hash(hash)
201                    .map_err(Self::Error::from_eth_err)?
202                    .map(|tx| tx.encoded_2718().into()))
203            })
204            .await
205        }
206    }
207
208    /// Returns the _historical_ transaction and the block it was mined in
209    #[expect(clippy::type_complexity)]
210    fn historical_transaction_by_hash_at(
211        &self,
212        hash: B256,
213    ) -> impl Future<
214        Output = Result<Option<(TransactionSource<ProviderTx<Self::Provider>>, B256)>, Self::Error>,
215    > + Send {
216        async move {
217            match self.transaction_by_hash_at(hash).await? {
218                None => Ok(None),
219                Some((tx, at)) => Ok(at.as_block_hash().map(|hash| (tx, hash))),
220            }
221        }
222    }
223
224    /// Returns the transaction receipt for the given hash.
225    ///
226    /// Returns None if the transaction does not exist or is pending
227    /// Note: The tx receipt is not available for pending transactions.
228    fn transaction_receipt(
229        &self,
230        hash: B256,
231    ) -> impl Future<Output = Result<Option<RpcReceipt<Self::NetworkTypes>>, Self::Error>> + Send
232    where
233        Self: LoadReceipt + 'static,
234    {
235        async move {
236            match self.load_transaction_and_receipt(hash).await? {
237                Some((tx, meta, receipt)) => {
238                    self.build_transaction_receipt(tx, meta, receipt).await.map(Some)
239                }
240                None => Ok(None),
241            }
242        }
243    }
244
245    /// Helper method that loads a transaction and its receipt.
246    #[expect(clippy::complexity)]
247    fn load_transaction_and_receipt(
248        &self,
249        hash: TxHash,
250    ) -> impl Future<
251        Output = Result<
252            Option<(ProviderTx<Self::Provider>, TransactionMeta, ProviderReceipt<Self::Provider>)>,
253            Self::Error,
254        >,
255    > + Send
256    where
257        Self: 'static,
258    {
259        self.spawn_blocking_io(move |this| {
260            let provider = this.provider();
261            let (tx, meta) = match provider
262                .transaction_by_hash_with_meta(hash)
263                .map_err(Self::Error::from_eth_err)?
264            {
265                Some((tx, meta)) => (tx, meta),
266                None => return Ok(None),
267            };
268
269            let receipt = match provider.receipt_by_hash(hash).map_err(Self::Error::from_eth_err)? {
270                Some(recpt) => recpt,
271                None => return Ok(None),
272            };
273
274            Ok(Some((tx, meta, receipt)))
275        })
276    }
277
278    /// Get transaction by [`BlockId`] and index of transaction within that block.
279    ///
280    /// Returns `Ok(None)` if the block does not exist, or index is out of range.
281    fn transaction_by_block_and_tx_index(
282        &self,
283        block_id: BlockId,
284        index: usize,
285    ) -> impl Future<Output = Result<Option<RpcTransaction<Self::NetworkTypes>>, Self::Error>> + Send
286    where
287        Self: LoadBlock,
288    {
289        async move {
290            if let Some(block) = self.recovered_block(block_id).await? {
291                let block_hash = block.hash();
292                let block_number = block.number();
293                let base_fee_per_gas = block.base_fee_per_gas();
294                if let Some((signer, tx)) = block.transactions_with_sender().nth(index) {
295                    #[allow(clippy::needless_update)]
296                    let tx_info = TransactionInfo {
297                        hash: Some(*tx.tx_hash()),
298                        block_hash: Some(block_hash),
299                        block_number: Some(block_number),
300                        base_fee: base_fee_per_gas,
301                        index: Some(index as u64),
302                        ..Default::default()
303                    };
304
305                    return Ok(Some(
306                        self.converter().fill(tx.clone().with_signer(*signer), tx_info)?,
307                    ))
308                }
309            }
310
311            Ok(None)
312        }
313    }
314
315    /// Find a transaction by sender's address and nonce.
316    fn get_transaction_by_sender_and_nonce(
317        &self,
318        sender: Address,
319        nonce: u64,
320        include_pending: bool,
321    ) -> impl Future<Output = Result<Option<RpcTransaction<Self::NetworkTypes>>, Self::Error>> + Send
322    where
323        Self: LoadBlock + LoadState,
324    {
325        async move {
326            // Check the pool first
327            if include_pending &&
328                let Some(tx) =
329                    RpcNodeCore::pool(self).get_transaction_by_sender_and_nonce(sender, nonce)
330            {
331                let transaction = tx.transaction.clone_into_consensus();
332                return Ok(Some(self.converter().fill_pending(transaction)?));
333            }
334
335            // Note: we can't optimize for contracts (account with code) and cannot shortcircuit if
336            // the address has code, because with 7702 EOAs can also have code
337
338            let highest = self.transaction_count(sender, None).await?.saturating_to::<u64>();
339
340            // If the nonce is higher or equal to the highest nonce, the transaction is pending or
341            // not exists.
342            if nonce >= highest {
343                return Ok(None);
344            }
345
346            let Ok(high) = self.provider().best_block_number() else {
347                return Err(EthApiError::HeaderNotFound(BlockNumberOrTag::Latest.into()).into());
348            };
349
350            // Perform a binary search over the block range to find the block in which the sender's
351            // nonce reached the requested nonce.
352            let num = binary_search::<_, _, Self::Error>(1, high, |mid| async move {
353                let mid_nonce =
354                    self.transaction_count(sender, Some(mid.into())).await?.saturating_to::<u64>();
355
356                Ok(mid_nonce > nonce)
357            })
358            .await?;
359
360            let block_id = num.into();
361            self.recovered_block(block_id)
362                .await?
363                .and_then(|block| {
364                    let block_hash = block.hash();
365                    let block_number = block.number();
366                    let base_fee_per_gas = block.base_fee_per_gas();
367
368                    block
369                        .transactions_with_sender()
370                        .enumerate()
371                        .find(|(_, (signer, tx))| **signer == sender && (*tx).nonce() == nonce)
372                        .map(|(index, (signer, tx))| {
373                            #[allow(clippy::needless_update)]
374                            let tx_info = TransactionInfo {
375                                hash: Some(*tx.tx_hash()),
376                                block_hash: Some(block_hash),
377                                block_number: Some(block_number),
378                                base_fee: base_fee_per_gas,
379                                index: Some(index as u64),
380                                ..Default::default()
381                            };
382                            Ok(self.converter().fill(tx.clone().with_signer(*signer), tx_info)?)
383                        })
384                })
385                .ok_or(EthApiError::HeaderNotFound(block_id))?
386                .map(Some)
387        }
388    }
389
390    /// Get transaction, as raw bytes, by [`BlockId`] and index of transaction within that block.
391    ///
392    /// Returns `Ok(None)` if the block does not exist, or index is out of range.
393    fn raw_transaction_by_block_and_tx_index(
394        &self,
395        block_id: BlockId,
396        index: usize,
397    ) -> impl Future<Output = Result<Option<Bytes>, Self::Error>> + Send
398    where
399        Self: LoadBlock,
400    {
401        async move {
402            if let Some(block) = self.recovered_block(block_id).await? &&
403                let Some(tx) = block.body().transactions().get(index)
404            {
405                return Ok(Some(tx.encoded_2718().into()))
406            }
407
408            Ok(None)
409        }
410    }
411
412    /// Signs transaction with a matching signer, if any and submits the transaction to the pool.
413    /// Returns the hash of the signed transaction.
414    fn send_transaction_request(
415        &self,
416        mut request: RpcTxReq<Self::NetworkTypes>,
417    ) -> impl Future<Output = Result<B256, Self::Error>> + Send
418    where
419        Self: EthApiSpec + LoadBlock + EstimateCall,
420    {
421        async move {
422            let from = match request.as_ref().from() {
423                Some(from) => from,
424                None => return Err(SignError::NoAccount.into_eth_err()),
425            };
426
427            if self.find_signer(&from).is_err() {
428                return Err(SignError::NoAccount.into_eth_err())
429            }
430
431            // set nonce if not already set before
432            if request.as_ref().nonce().is_none() {
433                let nonce = self.next_available_nonce(from).await?;
434                request.as_mut().set_nonce(nonce);
435            }
436
437            let chain_id = self.chain_id();
438            request.as_mut().set_chain_id(chain_id.to());
439
440            let estimated_gas =
441                self.estimate_gas_at(request.clone(), BlockId::pending(), None).await?;
442            let gas_limit = estimated_gas;
443            request.as_mut().set_gas_limit(gas_limit.to());
444
445            let transaction = self.sign_request(&from, request).await?.with_signer(from);
446
447            let pool_transaction =
448                <<Self as RpcNodeCore>::Pool as TransactionPool>::Transaction::try_from_consensus(
449                    transaction,
450                )
451                .map_err(|e| {
452                    Self::Error::from_eth_err(TransactionConversionError::Other(e.to_string()))
453                })?;
454
455            // submit the transaction to the pool with a `Local` origin
456            let AddedTransactionOutcome { hash, .. } = self
457                .pool()
458                .add_transaction(TransactionOrigin::Local, pool_transaction)
459                .await
460                .map_err(Self::Error::from_eth_err)?;
461
462            Ok(hash)
463        }
464    }
465
466    /// Fills the defaults on a given unsigned transaction.
467    fn fill_transaction(
468        &self,
469        mut request: RpcTxReq<Self::NetworkTypes>,
470    ) -> impl Future<Output = Result<FillTransaction<TxTy<Self::Primitives>>, Self::Error>> + Send
471    where
472        Self: EthApiSpec + LoadBlock + EstimateCall + LoadFee,
473    {
474        async move {
475            let from = match request.as_ref().from() {
476                Some(from) => from,
477                None => return Err(SignError::NoAccount.into_eth_err()),
478            };
479
480            if request.as_ref().value().is_none() {
481                request.as_mut().set_value(U256::ZERO);
482            }
483
484            if request.as_ref().nonce().is_none() {
485                let nonce = self.next_available_nonce(from).await?;
486                request.as_mut().set_nonce(nonce);
487            }
488
489            let chain_id = self.chain_id();
490            request.as_mut().set_chain_id(chain_id.to());
491
492            if request.as_ref().has_eip4844_fields() &&
493                request.as_ref().max_fee_per_blob_gas().is_none()
494            {
495                let blob_fee = self.blob_base_fee().await?;
496                request.as_mut().set_max_fee_per_blob_gas(blob_fee.to());
497            }
498
499            // Use `sidecar.is_some()` instead of `blob_sidecar().is_some()` to handle
500            // both EIP-4844 (v0) and EIP-7594 (v1) sidecar formats
501            if request.as_ref().sidecar.is_some() &&
502                request.as_ref().blob_versioned_hashes.is_none()
503            {
504                request.as_mut().populate_blob_hashes();
505            }
506
507            if request.as_ref().gas_limit().is_none() {
508                let estimated_gas =
509                    self.estimate_gas_at(request.clone(), BlockId::pending(), None).await?;
510                request.as_mut().set_gas_limit(estimated_gas.to());
511            }
512
513            if request.as_ref().gas_price().is_none() {
514                let tip = if let Some(tip) = request.as_ref().max_priority_fee_per_gas() {
515                    tip
516                } else {
517                    let tip = self.suggested_priority_fee().await?.to::<u128>();
518                    request.as_mut().set_max_priority_fee_per_gas(tip);
519                    tip
520                };
521                if request.as_ref().max_fee_per_gas().is_none() {
522                    let header =
523                        self.provider().latest_header().map_err(Self::Error::from_eth_err)?;
524                    let base_fee = header.and_then(|h| h.base_fee_per_gas()).unwrap_or_default();
525                    request.as_mut().set_max_fee_per_gas(base_fee as u128 + tip);
526                }
527            }
528
529            let tx = self.converter().build_simulate_v1_transaction(request)?;
530
531            let raw = tx.encoded_2718().into();
532
533            Ok(FillTransaction { raw, tx })
534        }
535    }
536
537    /// Signs a transaction, with configured signers.
538    fn sign_request(
539        &self,
540        from: &Address,
541        txn: RpcTxReq<Self::NetworkTypes>,
542    ) -> impl Future<Output = Result<ProviderTx<Self::Provider>, Self::Error>> + Send {
543        async move {
544            self.find_signer(from)?
545                .sign_transaction(txn, from)
546                .await
547                .map_err(Self::Error::from_eth_err)
548        }
549    }
550
551    /// Signs given message. Returns the signature.
552    fn sign(
553        &self,
554        account: Address,
555        message: Bytes,
556    ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send {
557        async move {
558            Ok(self
559                .find_signer(&account)?
560                .sign(account, &message)
561                .await
562                .map_err(Self::Error::from_eth_err)?
563                .as_bytes()
564                .into())
565        }
566    }
567
568    /// Signs a transaction request using the given account in request
569    /// Returns the EIP-2718 encoded signed transaction.
570    fn sign_transaction(
571        &self,
572        request: RpcTxReq<Self::NetworkTypes>,
573    ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send {
574        async move {
575            let from = match request.as_ref().from() {
576                Some(from) => from,
577                None => return Err(SignError::NoAccount.into_eth_err()),
578            };
579
580            Ok(self.sign_request(&from, request).await?.encoded_2718().into())
581        }
582    }
583
584    /// Encodes and signs the typed data according EIP-712. Payload must implement Eip712 trait.
585    fn sign_typed_data(&self, data: &TypedData, account: Address) -> Result<Bytes, Self::Error> {
586        Ok(self
587            .find_signer(&account)?
588            .sign_typed_data(account, data)
589            .map_err(Self::Error::from_eth_err)?
590            .as_bytes()
591            .into())
592    }
593
594    /// Returns the signer for the given account, if found in configured signers.
595    #[expect(clippy::type_complexity)]
596    fn find_signer(
597        &self,
598        account: &Address,
599    ) -> Result<
600        Box<dyn EthSigner<ProviderTx<Self::Provider>, RpcTxReq<Self::NetworkTypes>> + 'static>,
601        Self::Error,
602    > {
603        self.signers()
604            .read()
605            .iter()
606            .find(|signer| signer.is_signer_for(account))
607            .map(|signer| dyn_clone::clone_box(&**signer))
608            .ok_or_else(|| SignError::NoAccount.into_eth_err())
609    }
610}
611
612/// Loads a transaction from database.
613///
614/// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` transactions RPC
615/// methods.
616pub trait LoadTransaction: SpawnBlocking + FullEthApiTypes + RpcNodeCoreExt {
617    /// Returns the transaction by hash.
618    ///
619    /// Checks the pool and state.
620    ///
621    /// Returns `Ok(None)` if no matching transaction was found.
622    #[expect(clippy::complexity)]
623    fn transaction_by_hash(
624        &self,
625        hash: B256,
626    ) -> impl Future<
627        Output = Result<Option<TransactionSource<ProviderTx<Self::Provider>>>, Self::Error>,
628    > + Send {
629        async move {
630            // First, try the RPC cache
631            if let Some(cached) = self.cache().get_transaction_by_hash(hash).await &&
632                let Some(tx) = cached.recovered_transaction()
633            {
634                return Ok(Some(TransactionSource::Block {
635                    transaction: tx.cloned(),
636                    index: cached.tx_index as u64,
637                    block_hash: cached.block.hash(),
638                    block_number: cached.block.number(),
639                    base_fee: cached.block.base_fee_per_gas(),
640                }));
641            }
642
643            // Cache miss - try to find the transaction on disk
644            if let Some((tx, meta)) = self
645                .spawn_blocking_io(move |this| {
646                    this.provider()
647                        .transaction_by_hash_with_meta(hash)
648                        .map_err(Self::Error::from_eth_err)
649                })
650                .await?
651            {
652                // Note: we assume this transaction is valid, because it's mined (or
653                // part of pending block) and already. We don't need to
654                // check for pre EIP-2 because this transaction could be pre-EIP-2.
655                let transaction = tx
656                    .try_into_recovered_unchecked()
657                    .map_err(|_| EthApiError::InvalidTransactionSignature)?;
658
659                return Ok(Some(TransactionSource::Block {
660                    transaction,
661                    index: meta.index,
662                    block_hash: meta.block_hash,
663                    block_number: meta.block_number,
664                    base_fee: meta.base_fee,
665                }));
666            }
667
668            // tx not found on disk, check pool
669            if let Some(tx) = self.pool().get(&hash).map(|tx| tx.transaction.clone_into_consensus())
670            {
671                return Ok(Some(TransactionSource::Pool(tx.into())));
672            }
673
674            Ok(None)
675        }
676    }
677
678    /// Returns the transaction by including its corresponding [`BlockId`].
679    ///
680    /// Note: this supports pending transactions
681    #[expect(clippy::type_complexity)]
682    fn transaction_by_hash_at(
683        &self,
684        transaction_hash: B256,
685    ) -> impl Future<
686        Output = Result<
687            Option<(TransactionSource<ProviderTx<Self::Provider>>, BlockId)>,
688            Self::Error,
689        >,
690    > + Send {
691        async move {
692            Ok(self.transaction_by_hash(transaction_hash).await?.map(|tx| match tx {
693                tx @ TransactionSource::Pool(_) => (tx, BlockId::pending()),
694                tx @ TransactionSource::Block { block_hash, .. } => {
695                    (tx, BlockId::Hash(block_hash.into()))
696                }
697            }))
698        }
699    }
700
701    /// Fetches the transaction and the transaction's block
702    #[expect(clippy::type_complexity)]
703    fn transaction_and_block(
704        &self,
705        hash: B256,
706    ) -> impl Future<
707        Output = Result<
708            Option<(
709                TransactionSource<ProviderTx<Self::Provider>>,
710                Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>,
711            )>,
712            Self::Error,
713        >,
714    > + Send {
715        async move {
716            let (transaction, at) = match self.transaction_by_hash_at(hash).await? {
717                None => return Ok(None),
718                Some(res) => res,
719            };
720
721            // Note: this is always either hash or pending
722            let block_hash = match at {
723                BlockId::Hash(hash) => hash.block_hash,
724                _ => return Ok(None),
725            };
726            let block = self
727                .cache()
728                .get_recovered_block(block_hash)
729                .await
730                .map_err(Self::Error::from_eth_err)?;
731            Ok(block.map(|block| (transaction, block)))
732        }
733    }
734}