reth_rpc_eth_api/helpers/
transaction.rs1use 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::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
40pub trait EthTransactions: LoadTransaction<Provider: BlockReaderIdExt> {
63 fn signers(&self) -> &SignersForRpc<Self::Provider, Self::NetworkTypes>;
67
68 fn accounts(&self) -> Vec<Address> {
70 self.signers().read().iter().flat_map(|s| s.accounts()).collect()
71 }
72
73 fn send_raw_transaction_sync_timeout(&self) -> Duration;
75
76 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 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 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 #[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 #[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 fn raw_transaction_by_hash(
186 &self,
187 hash: B256,
188 ) -> impl Future<Output = Result<Option<Bytes>, Self::Error>> + Send {
189 async move {
190 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 #[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 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, all_receipts)) => {
238 self.build_transaction_receipt(tx, meta, receipt, all_receipts).await.map(Some)
239 }
240 None => Ok(None),
241 }
242 }
243 }
244
245 #[expect(clippy::complexity)]
249 fn load_transaction_and_receipt(
250 &self,
251 hash: TxHash,
252 ) -> impl Future<
253 Output = Result<
254 Option<(
255 Recovered<ProviderTx<Self::Provider>>,
256 TransactionMeta,
257 ProviderReceipt<Self::Provider>,
258 Option<Arc<Vec<ProviderReceipt<Self::Provider>>>>,
259 )>,
260 Self::Error,
261 >,
262 > + Send
263 where
264 Self: 'static,
265 {
266 async move {
267 if let Some(cached) = self.cache().get_transaction_by_hash(hash).await &&
268 let Some(tx) = cached.recovered_transaction().map(|tx| tx.cloned())
269 {
270 let meta = cached.transaction_meta(hash);
271
272 if let Some(all_receipts) = cached.receipts.clone() &&
274 let Some(receipt) = all_receipts.get(cached.tx_index).cloned()
275 {
276 return Ok(Some((tx, meta, receipt, Some(all_receipts))));
277 }
278
279 if let Some(receipts) = self
283 .cache()
284 .get_receipts(cached.block.hash())
285 .await
286 .map_err(Self::Error::from_eth_err)? &&
287 let Some(receipt) = receipts.get(cached.tx_index).cloned()
288 {
289 return Ok(Some((tx, meta, receipt, Some(receipts))));
290 }
291 }
292
293 self.spawn_blocking_io(move |this| {
295 let provider = this.provider();
296 let Some((tx, meta)) = provider
297 .transaction_by_hash_with_meta(hash)
298 .map_err(Self::Error::from_eth_err)?
299 else {
300 return Ok(None);
301 };
302
303 let tx = tx.try_into_recovered_unchecked().map_err(Self::Error::from_eth_err)?;
304
305 let receipt = provider.receipt_by_hash(hash).map_err(Self::Error::from_eth_err)?;
306
307 Ok(receipt.map(|receipt| (tx, meta, receipt, None)))
308 })
309 .await
310 }
311 }
312
313 fn transaction_by_block_and_tx_index(
317 &self,
318 block_id: BlockId,
319 index: usize,
320 ) -> impl Future<Output = Result<Option<RpcTransaction<Self::NetworkTypes>>, Self::Error>> + Send
321 where
322 Self: LoadBlock,
323 {
324 async move {
325 if let Some(block) = self.recovered_block(block_id).await? {
326 let block_hash = block.hash();
327 let block_number = block.number();
328 let base_fee_per_gas = block.base_fee_per_gas();
329 if let Some((signer, tx)) = block.transactions_with_sender().nth(index) {
330 let tx_info = TransactionInfo {
331 hash: Some(*tx.tx_hash()),
332 block_hash: Some(block_hash),
333 block_number: Some(block_number),
334 base_fee: base_fee_per_gas,
335 index: Some(index as u64),
336 ..Default::default()
337 };
338
339 return Ok(Some(
340 self.converter().fill(tx.clone().with_signer(*signer), tx_info)?,
341 ))
342 }
343 }
344
345 Ok(None)
346 }
347 }
348
349 fn get_transaction_by_sender_and_nonce(
351 &self,
352 sender: Address,
353 nonce: u64,
354 include_pending: bool,
355 ) -> impl Future<Output = Result<Option<RpcTransaction<Self::NetworkTypes>>, Self::Error>> + Send
356 where
357 Self: LoadBlock + LoadState,
358 {
359 async move {
360 if include_pending &&
362 let Some(tx) =
363 RpcNodeCore::pool(self).get_transaction_by_sender_and_nonce(sender, nonce)
364 {
365 let transaction = tx.transaction.clone_into_consensus();
366 return Ok(Some(self.converter().fill_pending(transaction)?));
367 }
368
369 let highest = self.transaction_count(sender, None).await?.saturating_to::<u64>();
373
374 if nonce >= highest {
377 return Ok(None);
378 }
379
380 let high = self.provider().best_block_number().map_err(Self::Error::from_eth_err)?;
381
382 let num = binary_search::<_, _, Self::Error>(1, high, |mid| async move {
385 let mid_nonce =
386 self.transaction_count(sender, Some(mid.into())).await?.saturating_to::<u64>();
387
388 Ok(mid_nonce > nonce)
389 })
390 .await?;
391
392 let block_id = num.into();
393 self.recovered_block(block_id)
394 .await?
395 .and_then(|block| {
396 let block_hash = block.hash();
397 let block_number = block.number();
398 let base_fee_per_gas = block.base_fee_per_gas();
399
400 block
401 .transactions_with_sender()
402 .enumerate()
403 .find(|(_, (signer, tx))| **signer == sender && (*tx).nonce() == nonce)
404 .map(|(index, (signer, tx))| {
405 let tx_info = TransactionInfo {
406 hash: Some(*tx.tx_hash()),
407 block_hash: Some(block_hash),
408 block_number: Some(block_number),
409 base_fee: base_fee_per_gas,
410 index: Some(index as u64),
411 ..Default::default()
412 };
413 Ok(self.converter().fill(tx.clone().with_signer(*signer), tx_info)?)
414 })
415 })
416 .ok_or(EthApiError::HeaderNotFound(block_id))?
417 .map(Some)
418 }
419 }
420
421 fn raw_transaction_by_block_and_tx_index(
425 &self,
426 block_id: BlockId,
427 index: usize,
428 ) -> impl Future<Output = Result<Option<Bytes>, Self::Error>> + Send
429 where
430 Self: LoadBlock,
431 {
432 async move {
433 if let Some(block) = self.recovered_block(block_id).await? &&
434 let Some(tx) = block.body().transactions().get(index)
435 {
436 return Ok(Some(tx.encoded_2718().into()))
437 }
438
439 Ok(None)
440 }
441 }
442
443 fn send_transaction_request(
446 &self,
447 mut request: RpcTxReq<Self::NetworkTypes>,
448 ) -> impl Future<Output = Result<B256, Self::Error>> + Send
449 where
450 Self: EthApiSpec + LoadBlock + EstimateCall,
451 {
452 async move {
453 let from = match request.as_ref().from() {
454 Some(from) => from,
455 None => return Err(SignError::NoAccount.into_eth_err()),
456 };
457
458 if self.find_signer(&from).is_err() {
459 return Err(SignError::NoAccount.into_eth_err())
460 }
461
462 if request.as_ref().nonce().is_none() {
464 let nonce = self.next_available_nonce_for(&request).await?;
465 request.as_mut().set_nonce(nonce);
466 }
467
468 let chain_id = self.chain_id();
469 request.as_mut().set_chain_id(chain_id.to());
470
471 let estimated_gas =
472 self.estimate_gas_at(request.clone(), BlockId::pending(), None).await?;
473 let gas_limit = estimated_gas;
474 request.as_mut().set_gas_limit(gas_limit.to());
475
476 let transaction = self.sign_request(&from, request).await?.with_signer(from);
477
478 let pool_transaction =
479 <<Self as RpcNodeCore>::Pool as TransactionPool>::Transaction::try_from_consensus(
480 transaction,
481 )
482 .map_err(|e| {
483 Self::Error::from_eth_err(TransactionConversionError::Other(e.to_string()))
484 })?;
485
486 let AddedTransactionOutcome { hash, .. } = self
488 .pool()
489 .add_transaction(TransactionOrigin::Local, pool_transaction)
490 .await
491 .map_err(Self::Error::from_eth_err)?;
492
493 Ok(hash)
494 }
495 }
496
497 fn fill_transaction(
499 &self,
500 mut request: RpcTxReq<Self::NetworkTypes>,
501 ) -> impl Future<Output = Result<FillTransaction<TxTy<Self::Primitives>>, Self::Error>> + Send
502 where
503 Self: EthApiSpec + LoadBlock + EstimateCall + LoadFee,
504 {
505 async move {
506 if request.as_ref().value().is_none() {
507 request.as_mut().set_value(U256::ZERO);
508 }
509
510 if request.as_ref().nonce().is_none() {
511 let nonce = self.next_available_nonce_for(&request).await?;
512 request.as_mut().set_nonce(nonce);
513 }
514
515 let chain_id = self.chain_id();
516 request.as_mut().set_chain_id(chain_id.to());
517
518 if request.as_ref().has_eip4844_fields() &&
519 request.as_ref().max_fee_per_blob_gas().is_none()
520 {
521 let blob_fee = self.blob_base_fee().await?;
522 request.as_mut().set_max_fee_per_blob_gas(blob_fee.to());
523 }
524
525 if request.as_ref().sidecar.is_some() &&
528 request.as_ref().blob_versioned_hashes.is_none()
529 {
530 request.as_mut().populate_blob_hashes();
531 }
532
533 if request.as_ref().gas_limit().is_none() {
534 let estimated_gas =
535 self.estimate_gas_at(request.clone(), BlockId::pending(), None).await?;
536 request.as_mut().set_gas_limit(estimated_gas.to());
537 }
538
539 if request.as_ref().gas_price().is_none() {
540 let tip = if let Some(tip) = request.as_ref().max_priority_fee_per_gas() {
541 tip
542 } else {
543 let tip = self.suggested_priority_fee().await?.to::<u128>();
544 request.as_mut().set_max_priority_fee_per_gas(tip);
545 tip
546 };
547 if request.as_ref().max_fee_per_gas().is_none() {
548 let header =
549 self.provider().latest_header().map_err(Self::Error::from_eth_err)?;
550 let base_fee = header.and_then(|h| h.base_fee_per_gas()).unwrap_or_default();
551 request.as_mut().set_max_fee_per_gas(base_fee as u128 + tip);
552 }
553 }
554
555 let tx = self.converter().build_simulate_v1_transaction(request)?;
556
557 let raw = tx.encoded_2718().into();
558
559 Ok(FillTransaction { raw, tx })
560 }
561 }
562
563 fn sign_request(
565 &self,
566 from: &Address,
567 txn: RpcTxReq<Self::NetworkTypes>,
568 ) -> impl Future<Output = Result<ProviderTx<Self::Provider>, Self::Error>> + Send {
569 async move {
570 self.find_signer(from)?
571 .sign_transaction(txn, from)
572 .await
573 .map_err(Self::Error::from_eth_err)
574 }
575 }
576
577 fn sign(
579 &self,
580 account: Address,
581 message: Bytes,
582 ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send {
583 async move {
584 Ok(self
585 .find_signer(&account)?
586 .sign(account, &message)
587 .await
588 .map_err(Self::Error::from_eth_err)?
589 .as_bytes()
590 .into())
591 }
592 }
593
594 fn sign_transaction(
597 &self,
598 request: RpcTxReq<Self::NetworkTypes>,
599 ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send {
600 async move {
601 let from = match request.as_ref().from() {
602 Some(from) => from,
603 None => return Err(SignError::NoAccount.into_eth_err()),
604 };
605
606 Ok(self.sign_request(&from, request).await?.encoded_2718().into())
607 }
608 }
609
610 fn sign_typed_data(&self, data: &TypedData, account: Address) -> Result<Bytes, Self::Error> {
612 Ok(self
613 .find_signer(&account)?
614 .sign_typed_data(account, data)
615 .map_err(Self::Error::from_eth_err)?
616 .as_bytes()
617 .into())
618 }
619
620 #[expect(clippy::type_complexity)]
622 fn find_signer(
623 &self,
624 account: &Address,
625 ) -> Result<
626 Box<dyn EthSigner<ProviderTx<Self::Provider>, RpcTxReq<Self::NetworkTypes>> + 'static>,
627 Self::Error,
628 > {
629 self.signers()
630 .read()
631 .iter()
632 .find(|signer| signer.is_signer_for(account))
633 .map(|signer| dyn_clone::clone_box(&**signer))
634 .ok_or_else(|| SignError::NoAccount.into_eth_err())
635 }
636}
637
638pub trait LoadTransaction: SpawnBlocking + FullEthApiTypes + RpcNodeCoreExt {
643 #[expect(clippy::complexity)]
649 fn transaction_by_hash(
650 &self,
651 hash: B256,
652 ) -> impl Future<
653 Output = Result<Option<TransactionSource<ProviderTx<Self::Provider>>>, Self::Error>,
654 > + Send {
655 async move {
656 if let Some(cached) = self.cache().get_transaction_by_hash(hash).await &&
658 let Some(source) = cached.to_transaction_source()
659 {
660 return Ok(Some(source));
661 }
662
663 if let Some((tx, meta)) = self
665 .spawn_blocking_io(move |this| {
666 this.provider()
667 .transaction_by_hash_with_meta(hash)
668 .map_err(Self::Error::from_eth_err)
669 })
670 .await?
671 {
672 let transaction = tx
676 .try_into_recovered_unchecked()
677 .map_err(|_| EthApiError::InvalidTransactionSignature)?;
678
679 return Ok(Some(TransactionSource::Block {
680 transaction,
681 index: meta.index,
682 block_hash: meta.block_hash,
683 block_number: meta.block_number,
684 base_fee: meta.base_fee,
685 }));
686 }
687
688 if let Some(tx) = self.pool().get(&hash).map(|tx| tx.transaction.clone_into_consensus())
690 {
691 return Ok(Some(TransactionSource::Pool(tx.into())));
692 }
693
694 Ok(None)
695 }
696 }
697
698 #[expect(clippy::type_complexity)]
702 fn transaction_by_hash_at(
703 &self,
704 transaction_hash: B256,
705 ) -> impl Future<
706 Output = Result<
707 Option<(TransactionSource<ProviderTx<Self::Provider>>, BlockId)>,
708 Self::Error,
709 >,
710 > + Send {
711 async move {
712 Ok(self.transaction_by_hash(transaction_hash).await?.map(|tx| match tx {
713 tx @ TransactionSource::Pool(_) => (tx, BlockId::pending()),
714 tx @ TransactionSource::Block { block_hash, .. } => {
715 (tx, BlockId::Hash(block_hash.into()))
716 }
717 }))
718 }
719 }
720
721 #[expect(clippy::type_complexity)]
723 fn transaction_and_block(
724 &self,
725 hash: B256,
726 ) -> impl Future<
727 Output = Result<
728 Option<(
729 TransactionSource<ProviderTx<Self::Provider>>,
730 Arc<RecoveredBlock<ProviderBlock<Self::Provider>>>,
731 )>,
732 Self::Error,
733 >,
734 > + Send {
735 async move {
736 let (transaction, at) = match self.transaction_by_hash_at(hash).await? {
737 None => return Ok(None),
738 Some(res) => res,
739 };
740
741 let block_hash = match at {
743 BlockId::Hash(hash) => hash.block_hash,
744 _ => return Ok(None),
745 };
746 let block = self
747 .cache()
748 .get_recovered_block(block_hash)
749 .await
750 .map_err(Self::Error::from_eth_err)?;
751 Ok(block.map(|block| (transaction, block)))
752 }
753 }
754}