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::{TransactionMeta, TxHashRef},
12    BlockHeader, Transaction,
13};
14use alloy_dyn_abi::TypedData;
15use alloy_eip7928::bal::DecodedBal;
16use alloy_eips::{eip2718::Encodable2718, BlockId};
17use alloy_network::{TransactionBuilder, TransactionBuilder4844};
18use alloy_primitives::{Address, Bytes, TxHash, B256, U256};
19use alloy_rpc_types_eth::{state::EvmOverrides, TransactionInfo, TransactionRequest};
20use evm2::evm::Bal as EvmBal;
21use futures::{Future, StreamExt};
22use reth_chain_state::CanonStateSubscriptions;
23use reth_primitives_traits::{
24    BlockBody, Recovered, RecoveredBlock, SignedTransaction, TxTy, WithEncoded,
25};
26use reth_rpc_convert::{transaction::RpcConvert, RpcTxReq, TransactionConversionError};
27use reth_rpc_eth_types::{
28    block::convert_transaction_receipt,
29    utils::{binary_search, decode_raw_transaction},
30    EthApiError::{self, TransactionConfirmationTimeout},
31    EthResult, FillTransaction, SignError, TransactionSource,
32};
33use reth_storage_api::{
34    BlockNumReader, BlockReaderIdExt, ProviderBlock, ProviderReceipt, ProviderTx,
35    TransactionsProvider,
36};
37use reth_transaction_pool::{
38    AddedTransactionOutcome, PoolPooledTx, PoolTransaction, PoolTx, TransactionOrigin,
39    TransactionPool,
40};
41use std::{sync::Arc, time::Duration};
42
43/// Transaction related functions for the [`EthApiServer`](crate::EthApiServer) trait in
44/// the `eth_` namespace.
45///
46/// This includes utilities for transaction tracing, transacting and inspection.
47///
48/// Async functions that are spawned onto the
49/// [`BlockingTaskPool`](reth_tasks::pool::BlockingTaskPool) begin with `spawn_`
50///
51/// ## Calls
52///
53/// There are subtle differences between when transacting [`RpcTxReq`]:
54///
55/// The endpoints `eth_call` and `eth_estimateGas` and `eth_createAccessList` should always
56/// __disable__ the base fee check in the EVM environment.
57///
58/// The behaviour for tracing endpoints is not consistent across clients.
59/// Geth also disables the basefee check for tracing: <https://github.com/ethereum/go-ethereum/blob/bc0b87ca196f92e5af49bd33cc190ef0ec32b197/eth/tracers/api.go#L955-L955>
60/// Erigon does not: <https://github.com/ledgerwatch/erigon/blob/aefb97b07d1c4fd32a66097a24eddd8f6ccacae0/turbo/transactions/tracing.go#L209-L209>
61///
62/// See also <https://github.com/paradigmxyz/reth/issues/6240>
63///
64/// This implementation follows the behaviour of Geth and disables the basefee check for tracing.
65pub trait EthTransactions: LoadTransaction<Provider: BlockReaderIdExt> {
66    /// Returns a handle for signing data.
67    ///
68    /// Signer access in default (L1) trait method implementations.
69    fn signers(&self) -> &SignersForRpc<Self::Provider, Self::NetworkTypes>;
70
71    /// Returns a list of addresses owned by provider.
72    fn accounts(&self) -> Vec<Address> {
73        self.signers().read().iter().flat_map(|s| s.accounts()).collect()
74    }
75
76    /// Returns the timeout duration for `send_raw_transaction_sync` RPC method.
77    fn send_raw_transaction_sync_timeout(&self) -> Duration {
78        self.eth_api_settings().send_raw_transaction_sync_timeout
79    }
80
81    /// Decodes and recovers the transaction and submits it to the pool.
82    ///
83    /// Returns the hash of the transaction.
84    fn send_raw_transaction(
85        &self,
86        tx: Bytes,
87    ) -> impl Future<Output = Result<B256, Self::Error>> + Send {
88        async move {
89            let pool_transaction = self.recover_raw_pool_transaction(&tx)?;
90            self.send_pool_transaction(
91                TransactionOrigin::Local,
92                WithEncoded::new(tx, pool_transaction),
93            )
94            .await
95        }
96    }
97
98    /// Decodes and recovers a raw pool transaction, sharing sender recovery when configured.
99    fn recover_raw_pool_transaction(&self, tx: &[u8]) -> Result<PoolTx<Self::Pool>, Self::Error> {
100        match self.eth_api_settings().sender_recovery_cache.as_ref() {
101            Some(cache) => {
102                <PoolTx<Self::Pool> as PoolTransaction>::recover_raw_transaction_with_cache(
103                    tx, cache,
104                )
105            }
106            None => <PoolTx<Self::Pool> as PoolTransaction>::recover_raw_transaction(tx),
107        }
108        .map_err(Self::Error::from_eth_err)
109    }
110
111    /// Submits the transaction to the pool with the given [`TransactionOrigin`].
112    fn send_transaction(
113        &self,
114        origin: TransactionOrigin,
115        tx: WithEncoded<Recovered<PoolPooledTx<Self::Pool>>>,
116    ) -> impl Future<Output = Result<B256, Self::Error>> + Send {
117        async move {
118            let (encoded, recovered) = tx.split();
119            let pool_transaction =
120                <Self::Pool as TransactionPool>::Transaction::from_pooled(recovered);
121
122            self.send_pool_transaction(origin, WithEncoded::new(encoded, pool_transaction)).await
123        }
124    }
125
126    /// Submits the pool transaction to the pool with the given [`TransactionOrigin`].
127    fn send_pool_transaction(
128        &self,
129        origin: TransactionOrigin,
130        tx: WithEncoded<PoolTx<Self::Pool>>,
131    ) -> impl Future<Output = Result<B256, Self::Error>> + Send;
132
133    /// Decodes and recovers the transaction and submits it to the pool.
134    ///
135    /// And awaits the receipt.
136    fn send_raw_transaction_sync(
137        &self,
138        tx: Bytes,
139        timeout_ms: Option<u64>,
140    ) -> impl Future<Output = Result<RpcReceipt<Self::NetworkTypes>, Self::Error>> + Send
141    where
142        Self: LoadReceipt,
143    {
144        let this = self.clone();
145        let configured_timeout = self.send_raw_transaction_sync_timeout();
146        let timeout_duration = timeout_ms
147            .filter(|timeout_ms| *timeout_ms > 0)
148            .map(Duration::from_millis)
149            .map(|timeout| timeout.min(configured_timeout))
150            .unwrap_or(configured_timeout);
151        async move {
152            let mut stream = this.provider().canonical_state_stream();
153            let hash = EthTransactions::send_raw_transaction(&this, tx).await?;
154            tokio::time::timeout(timeout_duration, async {
155                while let Some(notification) = stream.next().await {
156                    let chain = notification.committed();
157                    if let Some((block, tx, receipt, all_receipts)) =
158                        chain.find_transaction_and_receipt_by_hash(hash) &&
159                        let Some(receipt) = convert_transaction_receipt(
160                            block,
161                            all_receipts,
162                            tx,
163                            receipt,
164                            this.converter(),
165                        )
166                        .transpose()?
167                    {
168                        return Ok(receipt);
169                    }
170                }
171                Err(Self::Error::from_eth_err(TransactionConfirmationTimeout {
172                    hash,
173                    duration: timeout_duration,
174                }))
175            })
176            .await
177            .unwrap_or_else(|_elapsed| {
178                Err(Self::Error::from_eth_err(TransactionConfirmationTimeout {
179                    hash,
180                    duration: timeout_duration,
181                }))
182            })
183        }
184    }
185
186    /// Returns the transaction by hash.
187    ///
188    /// Checks the pool and state.
189    ///
190    /// Returns `Ok(None)` if no matching transaction was found.
191    #[expect(clippy::complexity)]
192    fn transaction_by_hash(
193        &self,
194        hash: B256,
195    ) -> impl Future<
196        Output = Result<Option<TransactionSource<ProviderTx<Self::Provider>>>, Self::Error>,
197    > + Send {
198        LoadTransaction::transaction_by_hash(self, hash)
199    }
200
201    /// Returns all transactions from the local pending pool.
202    fn pending_transactions(&self) -> Result<Vec<RpcTransaction<Self::NetworkTypes>>, Self::Error> {
203        self.pool()
204            .pending_transactions()
205            .into_iter()
206            .map(|tx| self.converter().fill_pending(tx.transaction.clone_into_consensus()))
207            .collect::<Result<Vec<_>, _>>()
208            .map_err(Self::Error::from)
209    }
210
211    /// Get all transactions in the block with the given hash.
212    ///
213    /// Returns `None` if block does not exist.
214    #[expect(clippy::type_complexity)]
215    fn transactions_by_block(
216        &self,
217        block: B256,
218    ) -> impl Future<Output = Result<Option<Vec<ProviderTx<Self::Provider>>>, Self::Error>> + Send
219    {
220        async move {
221            self.cache()
222                .get_recovered_block(block)
223                .await
224                .map(|b| b.map(|b| b.body().transactions().to_vec()))
225                .map_err(Self::Error::from_eth_err)
226        }
227    }
228
229    /// Returns the EIP-2718 encoded transaction by hash.
230    ///
231    /// If this is a pooled EIP-4844 transaction, the blob sidecar is included.
232    ///
233    /// Checks the pool and state.
234    ///
235    /// Returns `Ok(None)` if no matching transaction was found.
236    fn raw_transaction_by_hash(
237        &self,
238        hash: B256,
239    ) -> impl Future<Output = Result<Option<Bytes>, Self::Error>> + Send {
240        async move {
241            // Note: this is mostly used to fetch pooled transactions so we check the pool first
242            if let Some(tx) =
243                self.pool().get_pooled_transaction_element(hash).map(|tx| tx.encoded_2718().into())
244            {
245                return Ok(Some(tx))
246            }
247
248            self.spawn_blocking_io(move |ref this| {
249                Ok(this
250                    .provider()
251                    .transaction_by_hash(hash)
252                    .map_err(Self::Error::from_eth_err)?
253                    .map(|tx| tx.encoded_2718().into()))
254            })
255            .await
256        }
257    }
258
259    /// Returns the _historical_ transaction and the block it was mined in
260    #[expect(clippy::type_complexity)]
261    fn historical_transaction_by_hash_at(
262        &self,
263        hash: B256,
264    ) -> impl Future<
265        Output = Result<Option<(TransactionSource<ProviderTx<Self::Provider>>, B256)>, Self::Error>,
266    > + Send {
267        async move {
268            match self.transaction_by_hash_at(hash).await? {
269                None => Ok(None),
270                Some((tx, at)) => Ok(at.as_block_hash().map(|hash| (tx, hash))),
271            }
272        }
273    }
274
275    /// Returns the transaction receipt for the given hash.
276    ///
277    /// Returns None if the transaction does not exist or is pending
278    /// Note: The tx receipt is not available for pending transactions.
279    fn transaction_receipt(
280        &self,
281        hash: B256,
282    ) -> impl Future<Output = Result<Option<RpcReceipt<Self::NetworkTypes>>, Self::Error>> + Send
283    where
284        Self: LoadReceipt,
285    {
286        async move {
287            match self.load_transaction_and_receipt(hash).await? {
288                Some((tx, meta, receipt, all_receipts, block)) => self
289                    .build_transaction_receipt(tx, meta, receipt, all_receipts, block)
290                    .await
291                    .map(Some),
292                None => Ok(None),
293            }
294        }
295    }
296
297    /// Helper method that loads a transaction and its receipt.
298    ///
299    /// The returned transaction has its sender already recovered.
300    #[expect(clippy::complexity)]
301    fn load_transaction_and_receipt(
302        &self,
303        hash: TxHash,
304    ) -> impl Future<
305        Output = Result<
306            Option<(
307                Recovered<ProviderTx<Self::Provider>>,
308                TransactionMeta,
309                ProviderReceipt<Self::Provider>,
310                Option<Arc<Vec<ProviderReceipt<Self::Provider>>>>,
311                Option<Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>>,
312            )>,
313            Self::Error,
314        >,
315    > + Send
316    where
317        Self: 'static,
318    {
319        async move {
320            if let Some(cached) = self.cache().get_transaction_by_hash(hash).await &&
321                let Some(tx) = cached.recovered_transaction().map(|tx| tx.cloned())
322            {
323                let meta = cached.transaction_meta(hash);
324
325                // Best case: receipts are also cached.
326                if let Some(all_receipts) = cached.receipts.clone() &&
327                    let Some(receipt) = all_receipts.get(cached.tx_index).cloned()
328                {
329                    return Ok(Some((tx, meta, receipt, Some(all_receipts), Some(cached.block))));
330                }
331
332                // Block still cached but receipts evicted — fetch via cache since
333                // `build_transaction_receipt` needs all receipts for gas accounting
334                // anyway.
335                if let Some(receipts) = self
336                    .cache()
337                    .get_receipts(cached.block.hash())
338                    .await
339                    .map_err(Self::Error::from_eth_err)? &&
340                    let Some(receipt) = receipts.get(cached.tx_index).cloned()
341                {
342                    return Ok(Some((tx, meta, receipt, Some(receipts), Some(cached.block))));
343                }
344            }
345
346            // Full cache miss — fetch the transaction from provider.
347            let Some((tx, meta)) = self
348                .spawn_blocking_io(move |this| this.mined_transaction_by_hash_with_meta(hash))
349                .await?
350            else {
351                return Ok(None);
352            };
353
354            // Take the receipt from the block's receipts, which `build_transaction_receipt` needs
355            // for gas accounting anyway. They are missing if pruned.
356            let Some(all_receipts) = self
357                .cache()
358                .get_receipts(meta.block_hash)
359                .await
360                .map_err(Self::Error::from_eth_err)?
361            else {
362                return Ok(None);
363            };
364            let Some(receipt) = all_receipts.get(meta.index as usize).cloned() else {
365                return Ok(None);
366            };
367
368            Ok(Some((tx, meta, receipt, Some(all_receipts), None)))
369        }
370    }
371
372    /// Get transaction by [`BlockId`] and index of transaction within that block.
373    ///
374    /// Returns `Ok(None)` if the block does not exist, or index is out of range.
375    fn transaction_by_block_and_tx_index(
376        &self,
377        block_id: BlockId,
378        index: usize,
379    ) -> impl Future<Output = Result<Option<RpcTransaction<Self::NetworkTypes>>, Self::Error>> + Send
380    where
381        Self: LoadBlock,
382    {
383        async move {
384            if let Some(block) = self.recovered_block(block_id).await? {
385                let block_hash = block.hash();
386                let block_number = block.number();
387                let block_timestamp = block.timestamp();
388                let base_fee_per_gas = block.base_fee_per_gas();
389                if let Some((signer, tx)) = block.transactions_with_sender().nth(index) {
390                    let tx_info = TransactionInfo {
391                        hash: Some(*tx.tx_hash()),
392                        block_hash: Some(block_hash),
393                        block_number: Some(block_number),
394                        block_timestamp: Some(block_timestamp),
395                        base_fee: base_fee_per_gas,
396                        index: Some(index as u64),
397                    };
398
399                    return Ok(Some(
400                        self.converter().fill(tx.clone().with_signer(*signer), tx_info)?,
401                    ))
402                }
403            }
404
405            Ok(None)
406        }
407    }
408
409    /// Find a transaction by sender's address and nonce.
410    fn get_transaction_by_sender_and_nonce(
411        &self,
412        sender: Address,
413        nonce: u64,
414        include_pending: bool,
415    ) -> impl Future<Output = Result<Option<RpcTransaction<Self::NetworkTypes>>, Self::Error>> + Send
416    where
417        Self: LoadBlock + LoadState,
418    {
419        async move {
420            // Check the pool first
421            if include_pending &&
422                let Some(tx) =
423                    RpcNodeCore::pool(self).get_transaction_by_sender_and_nonce(sender, nonce)
424            {
425                let transaction = tx.transaction.clone_into_consensus();
426                return Ok(Some(self.converter().fill_pending(transaction)?));
427            }
428
429            // Note: we can't optimize for contracts (account with code) and cannot shortcircuit if
430            // the address has code, because with 7702 EOAs can also have code
431
432            let highest = self.transaction_count(sender, None).await?.saturating_to::<u64>();
433
434            // If the nonce is higher or equal to the highest nonce, the transaction is pending or
435            // not exists.
436            if nonce >= highest {
437                return Ok(None);
438            }
439
440            let high = self.provider().best_block_number().map_err(Self::Error::from_eth_err)?;
441
442            // Perform a binary search over the block range to find the block in which the sender's
443            // nonce reached the requested nonce.
444            let num = binary_search::<_, _, Self::Error>(1, high, |mid| async move {
445                let mid_nonce =
446                    self.transaction_count(sender, Some(mid.into())).await?.saturating_to::<u64>();
447
448                Ok(mid_nonce > nonce)
449            })
450            .await?;
451
452            let block_id = num.into();
453            let Some(block) = self.recovered_block(block_id).await? else {
454                return Err(EthApiError::HeaderNotFound(block_id).into())
455            };
456
457            let block_hash = block.hash();
458            let block_number = block.number();
459            let block_timestamp = block.timestamp();
460            let base_fee_per_gas = block.base_fee_per_gas();
461
462            // EIP-7702 authorizations can consume the account's nonce without a transaction
463            // from that sender, so an existing block may contain no matching transaction.
464            block
465                .transactions_with_sender()
466                .enumerate()
467                .find(|(_, (signer, tx))| **signer == sender && (*tx).nonce() == nonce)
468                .map(|(index, (signer, tx))| {
469                    let tx_info = TransactionInfo {
470                        hash: Some(*tx.tx_hash()),
471                        block_hash: Some(block_hash),
472                        block_number: Some(block_number),
473                        block_timestamp: Some(block_timestamp),
474                        base_fee: base_fee_per_gas,
475                        index: Some(index as u64),
476                    };
477                    Ok(self.converter().fill(tx.clone().with_signer(*signer), tx_info)?)
478                })
479                .transpose()
480        }
481    }
482
483    /// Get transaction, as raw bytes, by [`BlockId`] and index of transaction within that block.
484    ///
485    /// Returns `Ok(None)` if the block does not exist, or index is out of range.
486    fn raw_transaction_by_block_and_tx_index(
487        &self,
488        block_id: BlockId,
489        index: usize,
490    ) -> impl Future<Output = Result<Option<Bytes>, Self::Error>> + Send
491    where
492        Self: LoadBlock,
493    {
494        async move {
495            if let Some(block) = self.recovered_block(block_id).await? &&
496                let Some(tx) = block.body().transactions().get(index)
497            {
498                return Ok(Some(tx.encoded_2718().into()))
499            }
500
501            Ok(None)
502        }
503    }
504
505    /// Signs transaction with a matching signer, if any and submits the transaction to the pool.
506    /// Returns the hash of the signed transaction.
507    ///
508    /// Rejects requests that mix legacy and EIP-1559 fee fields.
509    fn send_transaction_request(
510        &self,
511        mut request: RpcTxReq<Self::NetworkTypes>,
512    ) -> impl Future<Output = Result<B256, Self::Error>> + Send
513    where
514        Self: EthApiSpec + EstimateCall + LoadFee,
515    {
516        async move {
517            ensure_no_conflicting_fee_fields(request.as_ref())?;
518
519            let from = match request.as_ref().from() {
520                Some(from) => from,
521                None => return Err(SignError::NoAccount.into_eth_err()),
522            };
523
524            let signer = self.find_signer(&from)?;
525
526            // Held until the pool insert below, so a concurrent request from this account reads
527            // the pool only after this transaction is in it.
528            let _nonce_guard = match signer.nonce_lock() {
529                Some(lock) if request.as_ref().nonce().is_none() => Some(lock.lock_owned().await),
530                _ => None,
531            };
532
533            // set nonce if not already set before
534            if request.as_ref().nonce().is_none() {
535                let nonce = self.next_available_nonce_for(&request).await?;
536                request.as_mut().set_nonce(nonce);
537            }
538
539            let chain_id = self.chain_id();
540            // A caller that pins `chainId` is asserting which chain it means to sign for.
541            // Silently rewriting it would sign and submit on a different chain than asked
542            // for, so reject the mismatch instead. Matches geth's `setDefaults`.
543            if let Some(request_chain_id) = request.as_ref().chain_id() &&
544                request_chain_id != chain_id.to::<u64>()
545            {
546                return Err(EthApiError::InvalidParams(format!(
547                    "chainId does not match node's (have={request_chain_id}, want={})",
548                    chain_id.to::<u64>()
549                ))
550                .into())
551            }
552            request.as_mut().set_chain_id(chain_id.to());
553
554            // set fee defaults if not already set before, same as `fill_transaction`
555            if request.as_ref().gas_price().is_none() {
556                let tip = if let Some(tip) = request.as_ref().max_priority_fee_per_gas() {
557                    tip
558                } else {
559                    let tip = self.suggested_priority_fee().await?.to::<u128>();
560                    request.as_mut().set_max_priority_fee_per_gas(tip);
561                    tip
562                };
563                if request.as_ref().max_fee_per_gas().is_none() {
564                    let header =
565                        self.provider().latest_header().map_err(Self::Error::from_eth_err)?;
566                    let base_fee = header.and_then(|h| h.base_fee_per_gas()).unwrap_or_default();
567                    request.as_mut().set_max_fee_per_gas(base_fee as u128 * 2 + tip);
568                }
569            }
570
571            if request.as_ref().gas_limit().is_none() {
572                // Taken after the nonce lock, so requests queued on that lock hold no permit.
573                let _permit = self
574                    .acquire_owned_blocking_io()
575                    .await
576                    .map_err(|_| EthApiError::InternalEthError)?;
577                let estimated_gas = self
578                    .estimate_gas_at(request.clone(), BlockId::pending(), EvmOverrides::default())
579                    .await?;
580                request.as_mut().set_gas_limit(estimated_gas.to());
581            }
582
583            let transaction = self.sign_request(&from, request).await?.with_signer(from);
584
585            let pool_transaction =
586                <<Self as RpcNodeCore>::Pool as TransactionPool>::Transaction::try_from_consensus(
587                    transaction,
588                )
589                .map_err(|e| {
590                    Self::Error::from_eth_err(TransactionConversionError::Other(e.to_string()))
591                })?;
592
593            // submit the transaction to the pool with a `Local` origin
594            let AddedTransactionOutcome { hash, .. } = self
595                .pool()
596                .add_transaction(TransactionOrigin::Local, pool_transaction)
597                .await
598                .map_err(Self::Error::from_eth_err)?;
599
600            Ok(hash)
601        }
602    }
603
604    /// Fills the defaults on a given unsigned transaction.
605    ///
606    /// Rejects requests that mix legacy and EIP-1559 fee fields.
607    fn fill_transaction(
608        &self,
609        mut request: RpcTxReq<Self::NetworkTypes>,
610    ) -> impl Future<Output = Result<FillTransaction<TxTy<Self::Primitives>>, Self::Error>> + Send
611    where
612        Self: EthApiSpec + EstimateCall + LoadFee,
613    {
614        async move {
615            ensure_no_conflicting_fee_fields(request.as_ref())?;
616
617            if request.as_ref().value().is_none() {
618                request.as_mut().set_value(U256::ZERO);
619            }
620
621            if request.as_ref().nonce().is_none() {
622                let nonce = self.next_available_nonce_for(&request).await?;
623                request.as_mut().set_nonce(nonce);
624            }
625
626            let chain_id = self.chain_id();
627            // A caller that pins `chainId` is asserting which chain it means to sign for.
628            // Silently rewriting it would sign and submit on a different chain than asked
629            // for, so reject the mismatch instead. Matches geth's `setDefaults`.
630            if let Some(request_chain_id) = request.as_ref().chain_id() &&
631                request_chain_id != chain_id.to::<u64>()
632            {
633                return Err(EthApiError::InvalidParams(format!(
634                    "chainId does not match node's (have={request_chain_id}, want={})",
635                    chain_id.to::<u64>()
636                ))
637                .into())
638            }
639            request.as_mut().set_chain_id(chain_id.to());
640
641            if request.as_ref().has_eip4844_fields() &&
642                request.as_ref().max_fee_per_blob_gas().is_none()
643            {
644                let blob_fee = self.blob_base_fee().await?;
645                request.as_mut().set_max_fee_per_blob_gas(blob_fee.to());
646            }
647
648            // Use `sidecar.is_some()` instead of `blob_sidecar().is_some()` to handle
649            // both EIP-4844 (v0) and EIP-7594 (v1) sidecar formats
650            if request.as_ref().sidecar.is_some() &&
651                request.as_ref().blob_versioned_hashes.is_none()
652            {
653                request.as_mut().populate_blob_hashes();
654            }
655
656            if request.as_ref().gas_limit().is_none() {
657                let estimated_gas = self
658                    .estimate_gas_at(request.clone(), BlockId::pending(), EvmOverrides::default())
659                    .await?;
660                request.as_mut().set_gas_limit(estimated_gas.to());
661            }
662
663            if request.as_ref().gas_price().is_none() {
664                let tip = if let Some(tip) = request.as_ref().max_priority_fee_per_gas() {
665                    tip
666                } else {
667                    let tip = self.suggested_priority_fee().await?.to::<u128>();
668                    request.as_mut().set_max_priority_fee_per_gas(tip);
669                    tip
670                };
671                if request.as_ref().max_fee_per_gas().is_none() {
672                    let header =
673                        self.provider().latest_header().map_err(Self::Error::from_eth_err)?;
674                    let base_fee = header.and_then(|h| h.base_fee_per_gas()).unwrap_or_default();
675                    // Use `2 * base_fee` as headroom, matching go-ethereum's
676                    // `setLondonFeeDefaults`, so the transaction does not
677                    // become invalid if the base fee rises before it is
678                    // included. This does not increase the effective price the sender pays:
679                    // `max_fee_per_gas` is only an upper bound and the sender still pays
680                    // `base_fee + min(tip, max_fee_per_gas - base_fee)`.
681                    request.as_mut().set_max_fee_per_gas(base_fee as u128 * 2 + tip);
682                }
683            }
684
685            let tx = self.converter().build_simulate_v1_transaction(request)?;
686
687            let raw = tx.encoded_2718().into();
688
689            Ok(FillTransaction { raw, tx })
690        }
691    }
692
693    /// Signs a transaction, with configured signers.
694    fn sign_request(
695        &self,
696        from: &Address,
697        txn: RpcTxReq<Self::NetworkTypes>,
698    ) -> impl Future<Output = Result<ProviderTx<Self::Provider>, Self::Error>> + Send {
699        async move {
700            self.find_signer(from)?
701                .sign_transaction(txn, from)
702                .await
703                .map_err(Self::Error::from_eth_err)
704        }
705    }
706
707    /// Signs given message. Returns the signature.
708    fn sign(
709        &self,
710        account: Address,
711        message: Bytes,
712    ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send {
713        async move {
714            Ok(self
715                .find_signer(&account)?
716                .sign(account, &message)
717                .await
718                .map_err(Self::Error::from_eth_err)?
719                .as_bytes()
720                .into())
721        }
722    }
723
724    /// Signs a transaction request using the given account in request
725    /// Returns the EIP-2718 encoded signed transaction.
726    ///
727    /// Rejects requests that mix legacy and EIP-1559 fee fields.
728    fn sign_transaction(
729        &self,
730        request: RpcTxReq<Self::NetworkTypes>,
731    ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send {
732        async move {
733            ensure_no_conflicting_fee_fields(request.as_ref())?;
734
735            let from = match request.as_ref().from() {
736                Some(from) => from,
737                None => return Err(SignError::NoAccount.into_eth_err()),
738            };
739
740            Ok(self.sign_request(&from, request).await?.encoded_2718().into())
741        }
742    }
743
744    /// Encodes and signs the typed data according EIP-712. Payload must implement Eip712 trait.
745    fn sign_typed_data(&self, data: &TypedData, account: Address) -> Result<Bytes, Self::Error> {
746        Ok(self
747            .find_signer(&account)?
748            .sign_typed_data(account, data)
749            .map_err(Self::Error::from_eth_err)?
750            .as_bytes()
751            .into())
752    }
753
754    /// Returns the signer for the given account, if found in configured signers.
755    #[expect(clippy::type_complexity)]
756    fn find_signer(
757        &self,
758        account: &Address,
759    ) -> Result<
760        Box<dyn EthSigner<ProviderTx<Self::Provider>, RpcTxReq<Self::NetworkTypes>> + 'static>,
761        Self::Error,
762    > {
763        self.signers()
764            .read()
765            .iter()
766            .find(|signer| signer.is_signer_for(account))
767            .map(|signer| dyn_clone::clone_box(&**signer))
768            .ok_or_else(|| SignError::NoAccount.into_eth_err())
769    }
770}
771
772/// Loads a transaction from database.
773///
774/// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` transactions RPC
775/// methods.
776pub trait LoadTransaction: SpawnBlocking + FullEthApiTypes + RpcNodeCoreExt {
777    /// Decodes and recovers a raw transaction, sharing sender recovery when configured.
778    fn recover_raw_transaction<T: SignedTransaction>(&self, tx: &[u8]) -> EthResult<Recovered<T>> {
779        let transaction = decode_raw_transaction::<T>(tx)?;
780        let signer = match self.eth_api_settings().sender_recovery_cache.as_ref() {
781            Some(cache) => cache.recover(&transaction),
782            None => transaction.try_recover(),
783        }
784        .map_err(|_| EthApiError::InvalidTransactionSignature)?;
785        Ok(Recovered::new_unchecked(transaction, signer))
786    }
787
788    /// Decodes and recovers raw transactions in order, stopping at the first error.
789    ///
790    /// Uses [`Self::recover_raw_transaction`] to share sender recovery when configured.
791    fn recover_raw_transactions<T: SignedTransaction>(
792        &self,
793        txs: impl IntoIterator<Item = impl AsRef<[u8]>>,
794    ) -> EthResult<Vec<Recovered<T>>> {
795        txs.into_iter().map(|tx| self.recover_raw_transaction(tx.as_ref())).collect()
796    }
797
798    /// Decodes and recovers a raw transaction in the pool's pooled format.
799    ///
800    /// Used by RPC methods that execute raw transactions a client could also submit to the pool,
801    /// such as `eth_callBundle`, `mev_simBundle` and `trace_rawTransaction`. The default delegates
802    /// to [`Self::recover_raw_transaction`]; implementations can override it to customize decoding
803    /// or recovery for their pooled transaction type.
804    fn recover_raw_pooled_transaction(
805        &self,
806        tx: &[u8],
807    ) -> EthResult<Recovered<PoolPooledTx<Self::Pool>>> {
808        self.recover_raw_transaction(tx)
809    }
810
811    /// Decodes and recovers raw pooled transactions in order, stopping at the first error.
812    ///
813    /// Uses [`Self::recover_raw_pooled_transaction`] for each transaction.
814    fn recover_raw_pooled_transactions(
815        &self,
816        txs: impl IntoIterator<Item = impl AsRef<[u8]>>,
817    ) -> EthResult<Vec<Recovered<PoolPooledTx<Self::Pool>>>> {
818        txs.into_iter().map(|tx| self.recover_raw_pooled_transaction(tx.as_ref())).collect()
819    }
820
821    /// Recovers the sender of a mined transaction, reusing a cached sender when configured.
822    ///
823    /// Mined transactions can predate EIP-2, so recovery does not reject high-s signatures. A
824    /// sender recovered on a cache miss is not cached: lookups of mined transactions rarely
825    /// repeat, and caching them would evict senders that ingress and payload execution still need.
826    fn recover_mined_transaction<T: SignedTransaction>(&self, tx: T) -> EthResult<Recovered<T>> {
827        let cached = self
828            .eth_api_settings()
829            .sender_recovery_cache
830            .as_ref()
831            .and_then(|cache| cache.get(tx.tx_hash()));
832        let signer = match cached {
833            Some(signer) => signer,
834            None => tx
835                .recover_signer_unchecked()
836                .map_err(|_| EthApiError::InvalidTransactionSignature)?,
837        };
838        Ok(Recovered::new_unchecked(tx, signer))
839    }
840
841    /// Returns the mined transaction with the given hash and the metadata of its block.
842    ///
843    /// Uses the stored sender, and falls back to [`Self::recover_mined_transaction`] if senders are
844    /// pruned. Reads from the provider, so this must run on a blocking task.
845    ///
846    /// Returns `Ok(None)` if the transaction was not found.
847    #[expect(clippy::type_complexity)]
848    fn mined_transaction_by_hash_with_meta(
849        &self,
850        hash: TxHash,
851    ) -> Result<Option<(Recovered<ProviderTx<Self::Provider>>, TransactionMeta)>, Self::Error> {
852        let Some((tx, meta, signer)) = self
853            .provider()
854            .transaction_by_hash_with_meta_and_sender(hash)
855            .map_err(Self::Error::from_eth_err)?
856        else {
857            return Ok(None)
858        };
859        let tx = match signer {
860            Some(signer) => tx.with_signer(signer),
861            None => self.recover_mined_transaction(tx).map_err(Self::Error::from_eth_err)?,
862        };
863        Ok(Some((tx, meta)))
864    }
865
866    /// Returns the transaction by hash.
867    ///
868    /// Checks the pool and state.
869    ///
870    /// Returns `Ok(None)` if no matching transaction was found.
871    #[expect(clippy::complexity)]
872    fn transaction_by_hash(
873        &self,
874        hash: B256,
875    ) -> impl Future<
876        Output = Result<Option<TransactionSource<ProviderTx<Self::Provider>>>, Self::Error>,
877    > + Send {
878        async move {
879            // First, try the RPC cache
880            if let Some(cached) = self.cache().get_transaction_by_hash(hash).await &&
881                let Some(source) = cached.to_transaction_source()
882            {
883                return Ok(Some(source));
884            }
885
886            // Cache miss - try to find the transaction on disk
887            if let Some((transaction, meta)) = self
888                .spawn_blocking_io(move |this| this.mined_transaction_by_hash_with_meta(hash))
889                .await?
890            {
891                return Ok(Some(TransactionSource::Block {
892                    transaction,
893                    index: meta.index,
894                    block_hash: meta.block_hash,
895                    block_number: meta.block_number,
896                    block_timestamp: meta.timestamp,
897                    base_fee: meta.base_fee,
898                }));
899            }
900
901            // tx not found on disk, check pool
902            if let Some(tx) = self.pool().get(&hash).map(|tx| tx.transaction.clone_into_consensus())
903            {
904                return Ok(Some(TransactionSource::Pool(tx.into())));
905            }
906
907            Ok(None)
908        }
909    }
910
911    /// Returns the transaction by including its corresponding [`BlockId`].
912    ///
913    /// Note: this supports pending transactions
914    #[expect(clippy::type_complexity)]
915    fn transaction_by_hash_at(
916        &self,
917        transaction_hash: B256,
918    ) -> impl Future<
919        Output = Result<
920            Option<(TransactionSource<ProviderTx<Self::Provider>>, BlockId)>,
921            Self::Error,
922        >,
923    > + Send {
924        async move {
925            Ok(self.transaction_by_hash(transaction_hash).await?.map(|tx| match tx {
926                tx @ TransactionSource::Pool(_) => (tx, BlockId::pending()),
927                tx @ TransactionSource::Block { block_hash, .. } => (tx, BlockId::hash(block_hash)),
928            }))
929        }
930    }
931
932    /// Fetches the transaction and the transaction's block
933    #[expect(clippy::type_complexity)]
934    fn transaction_and_block(
935        &self,
936        hash: B256,
937    ) -> impl Future<
938        Output = Result<
939            Option<(
940                TransactionSource<ProviderTx<Self::Provider>>,
941                Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>,
942            )>,
943            Self::Error,
944        >,
945    > + Send {
946        async move {
947            Ok(self
948                .transaction_and_block_and_maybe_bal(hash)
949                .await?
950                .map(|(transaction, block, _)| (transaction, block)))
951        }
952    }
953
954    /// Fetches the transaction and the transaction's block, together with the block's cached
955    /// block access list, if any.
956    ///
957    /// The BAL is only returned if it is already cached, it is never fetched from the BAL store.
958    #[expect(clippy::type_complexity)]
959    fn transaction_and_block_and_maybe_bal(
960        &self,
961        hash: B256,
962    ) -> impl Future<
963        Output = Result<
964            Option<(
965                TransactionSource<ProviderTx<Self::Provider>>,
966                Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>,
967                Option<Arc<DecodedBal<Arc<EvmBal>>>>,
968            )>,
969            Self::Error,
970        >,
971    > + Send {
972        async move {
973            let (transaction, at) = match self.transaction_by_hash_at(hash).await? {
974                None => return Ok(None),
975                Some(res) => res,
976            };
977
978            // Note: this is always either hash or pending
979            let block_hash = match at {
980                BlockId::Hash(hash) => hash.block_hash,
981                _ => return Ok(None),
982            };
983            let block_and_bal = self
984                .cache()
985                .get_recovered_block_and_maybe_bal(block_hash)
986                .await
987                .map_err(Self::Error::from_eth_err)?;
988            Ok(block_and_bal.map(|(block, bal)| (transaction, block, bal)))
989        }
990    }
991}
992
993/// Rejects legacy gas prices combined with EIP-1559 fee fields before transaction construction.
994const fn ensure_no_conflicting_fee_fields(request: &TransactionRequest) -> EthResult<()> {
995    if request.gas_price.is_some() && request.has_eip1559_fields() {
996        return Err(EthApiError::ConflictingFeeFieldsInRequest)
997    }
998    Ok(())
999}