1use crate::traces::identifier::SignaturesIdentifier;
2use alloy_consensus::{SidecarBuilder, SimpleCoder};
3use alloy_dyn_abi::ErrorExt;
4use alloy_ens::NameOrAddress;
5use alloy_json_abi::Function;
6use alloy_network::{Network, ReceiptResponse, TransactionBuilder};
7use alloy_primitives::{Address, B256, Bytes, TxHash, TxKind, U64, U256, hex};
8use alloy_provider::{PendingTransactionBuilder, Provider};
9use alloy_rpc_types::{AccessList, Authorization, TransactionInputKind};
10use alloy_signer::Signer;
11use alloy_sol_types::SolCall;
12use alloy_transport::TransportError;
13use clap::Args;
14use eyre::{Result, WrapErr};
15use foundry_cli::{
16 opts::{CliAuthorizationList, EthereumOpts, TempoOpts, TransactionOpts},
17 utils::{self, apply_gas_estimate_multiplier, parse_ether_value, parse_function_args},
18};
19use foundry_common::{
20 FoundryTransactionBuilder, TransactionReceiptWithRevertReason,
21 fmt::*,
22 get_pretty_receipt_w_reason_attr,
23 provider::fee::{estimate_eip1559_fees, resolve_broadcast_eip1559_fees},
24 shell,
25 tempo::{
26 ensure_expiring_nonce_discriminator_active, is_tempo_hardfork_active,
27 mark_sponsored_gas_estimation,
28 },
29};
30use foundry_config::{Chain, Config, Eip1559FeeEstimatePreset};
31use foundry_wallets::{BrowserWalletOpts, WalletOpts, WalletSigner};
32use itertools::Itertools;
33use std::{fmt::Write, marker::PhantomData, str::FromStr, time::Duration};
34use tempo_alloy::{accounts::TempoAccountsWallet, chainspec::hardfork::TempoHardfork};
35use tempo_contracts::precompiles::{INonce, NONCE_PRECOMPILE_ADDRESS};
36use tempo_primitives::transaction::TEMPO_EXPIRING_NONCE_KEY;
37
38#[derive(Debug, Clone, Args)]
39pub struct SendTxOpts {
40 #[arg(id = "async", long = "async", alias = "cast-async", env = "CAST_ASYNC")]
42 pub cast_async: bool,
43
44 #[arg(long, conflicts_with = "async")]
48 pub sync: bool,
49
50 #[arg(long, default_value = "1")]
52 pub confirmations: u64,
53
54 #[arg(long, env = "ETH_TIMEOUT")]
56 pub timeout: Option<u64>,
57
58 #[arg(long, alias = "poll-interval", env = "ETH_POLL_INTERVAL")]
60 pub poll_interval: Option<u64>,
61
62 #[command(flatten)]
64 pub eth: EthereumOpts,
65
66 #[command(flatten)]
68 pub browser: BrowserWalletOpts,
69}
70
71pub(crate) fn apply_poll_interval<N: Network>(provider: &impl Provider<N>, interval: Option<u64>) {
73 if let Some(interval) = interval {
74 provider.client().set_poll_interval(Duration::from_secs(interval));
75 }
76}
77
78#[derive(Debug, Clone, Args)]
80#[command(next_help_heading = "Transaction options")]
81pub struct TxParams {
82 #[arg(long, env = "ETH_GAS_LIMIT")]
84 pub gas_limit: Option<U256>,
85
86 #[arg(
91 long,
92 env = "ETH_GAS_PRICE",
93 value_parser = parse_ether_value,
94 value_name = "PRICE"
95 )]
96 pub gas_price: Option<U256>,
97
98 #[arg(
100 long,
101 env = "ETH_PRIORITY_GAS_PRICE",
102 value_parser = parse_ether_value,
103 value_name = "PRICE"
104 )]
105 pub priority_gas_price: Option<U256>,
106
107 #[arg(long)]
109 pub nonce: Option<U64>,
110
111 #[command(flatten)]
112 pub tempo: TempoOpts,
113}
114
115impl TxParams {
116 pub(crate) fn apply<N: Network>(&self, tx: &mut N::TransactionRequest, legacy: bool)
117 where
118 N::TransactionRequest: FoundryTransactionBuilder<N>,
119 {
120 self.clone().into_transaction_opts().apply::<N>(tx, legacy);
121 }
122
123 pub(crate) fn into_transaction_opts(self) -> TransactionOpts {
125 TransactionOpts {
126 gas_limit: self.gas_limit,
127 gas_price: self.gas_price,
128 priority_gas_price: self.priority_gas_price,
129 value: None,
130 nonce: self.nonce,
131 legacy: false,
132 blob: false,
133 eip4844: false,
134 blob_gas_price: None,
135 auth: Vec::new(),
136 access_list: None,
137 tempo: self.tempo,
138 }
139 }
140}
141
142pub enum SenderKind<'a> {
144 Address(Address),
147 Signer(&'a WalletSigner),
149 OwnedSigner(Box<WalletSigner>),
151}
152
153impl SenderKind<'_> {
154 pub fn address(&self) -> Address {
156 match self {
157 Self::Address(addr) => *addr,
158 Self::Signer(signer) => signer.address(),
159 Self::OwnedSigner(signer) => signer.address(),
160 }
161 }
162
163 pub async fn from_wallet_opts(
169 mut opts: WalletOpts,
170 authorizations: &[CliAuthorizationList],
171 ) -> Result<Self> {
172 let from = opts.from.take();
173 if let Some(from) = from
174 && opts.tempo_access_key.is_none()
175 && !authorizations.iter().any(|auth| matches!(auth, CliAuthorizationList::Address(_)))
176 {
177 return Ok(from.into());
178 }
179 let (signer, tempo_wallet) = foundry_common::tempo::maybe_signer(&opts, None).await?;
180 Ok(if let Some(signer) = signer {
181 signer.into()
182 } else if let Some(tempo_wallet) = tempo_wallet {
183 tempo_wallet.account().into()
184 } else {
185 from.unwrap_or_default().into()
186 })
187 }
188
189 pub fn as_signer(&self) -> Option<&WalletSigner> {
191 match self {
192 Self::Signer(signer) => Some(signer),
193 Self::OwnedSigner(signer) => Some(signer.as_ref()),
194 Self::Address(_) => None,
195 }
196 }
197}
198
199impl From<Address> for SenderKind<'_> {
200 fn from(addr: Address) -> Self {
201 Self::Address(addr)
202 }
203}
204
205impl<'a> From<&'a WalletSigner> for SenderKind<'a> {
206 fn from(signer: &'a WalletSigner) -> Self {
207 Self::Signer(signer)
208 }
209}
210
211impl From<WalletSigner> for SenderKind<'_> {
212 fn from(signer: WalletSigner) -> Self {
213 Self::OwnedSigner(Box::new(signer))
214 }
215}
216
217pub(crate) async fn read_only_sender<N: Network>(
220 browser: &BrowserWalletOpts,
221 wallet: WalletOpts,
222 tx: &TransactionOpts,
223 chain_id: u64,
224) -> Result<(SenderKind<'static>, bool)> {
225 crate::tempo::ensure_session_not_browser(&tx.tempo, browser.browser)?;
226 if let Some(session) = tx.tempo.session_signer_for_wallet(&wallet, chain_id)? {
227 return Ok((session.access_key.account().into(), false));
228 }
229
230 Ok(match browser.run::<N>().await? {
231 Some(browser) => (browser.address().into(), true),
232 None => (SenderKind::from_wallet_opts(wallet, &tx.auth).await?, false),
233 })
234}
235
236pub(crate) fn validate_authorizations(
238 authorizations: &[CliAuthorizationList],
239 sender: &SenderKind<'_>,
240) -> Result<()> {
241 let address_auth_count = authorizations
242 .iter()
243 .filter(|auth| matches!(auth, CliAuthorizationList::Address(_)))
244 .count();
245 if address_auth_count > 1 {
246 eyre::bail!(
247 "Multiple address-based authorizations provided. Only one address can be specified; \
248 use pre-signed authorizations (hex-encoded) for multiple authorizations."
249 );
250 }
251 if address_auth_count == 1 && sender.as_signer().is_none() {
252 eyre::bail!(
253 "No signer available to sign authorization. \
254 Provide a pre-signed authorization (hex-encoded) instead."
255 );
256 }
257
258 Ok(())
259}
260
261pub(crate) async fn resolve_send_signer(
264 pre_resolved: Option<WalletSigner>,
265 eth: &EthereumOpts,
266) -> Result<(WalletSigner, Address)> {
267 let signer = match pre_resolved {
268 Some(signer) => signer,
269 None => eth.wallet.signer().await?,
270 };
271 let from = signer.address();
272 validate_from_address(eth.wallet.from, from)?;
273 Ok((signer, from))
274}
275
276pub fn validate_from_address(
278 specified_from: Option<Address>,
279 signer_address: Address,
280) -> Result<()> {
281 if let Some(specified_from) = specified_from
282 && specified_from != signer_address
283 {
284 eyre::bail!(
285 "\
286The specified sender via CLI/env vars does not match the sender configured via
287the hardware wallet's HD Path.
288Please use the `--hd-path <PATH>` parameter to specify the BIP32 Path which
289corresponds to the sender, or let foundry automatically detect it by not specifying any sender address."
290 );
291 }
292 Ok(())
293}
294
295#[derive(Debug)]
297pub struct InitState;
298
299#[derive(Debug)]
301pub struct ToState {
302 to: Option<Address>,
303}
304
305#[derive(Debug)]
307pub struct InputState {
308 kind: TxKind,
309 input: Vec<u8>,
310 func: Option<Function>,
311}
312
313pub struct CastTxSender<N, P> {
314 provider: P,
315 _phantom: PhantomData<N>,
316}
317
318impl<N: Network, P: Provider<N>> CastTxSender<N, P>
319where
320 N::TransactionRequest: FoundryTransactionBuilder<N>,
321 N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
322{
323 pub const fn new(provider: P) -> Self {
325 Self { provider, _phantom: PhantomData }
326 }
327
328 pub async fn send_sync(&self, tx: N::TransactionRequest) -> Result<(B256, String)> {
330 let receipt = self.provider.send_transaction_sync(tx).await?;
331 self.finish(receipt, None).await
332 }
333
334 pub async fn send(&self, tx: N::TransactionRequest) -> Result<PendingTransactionBuilder<N>> {
336 Ok(self.provider.send_transaction(tx).await?)
337 }
338
339 pub async fn send_raw_sync(&self, raw_tx: &[u8]) -> Result<(B256, String)> {
341 let receipt = self.provider.send_raw_transaction_sync(raw_tx).await?;
342 self.finish(receipt, None).await
343 }
344
345 pub async fn print_tx_result(
350 &self,
351 tx_hash: B256,
352 cast_async: bool,
353 confs: u64,
354 timeout: u64,
355 ) -> Result<()> {
356 if cast_async {
357 sh_println!("{tx_hash:#x}")?;
358 } else {
359 let receipt = self.sent_tx_receipt(tx_hash, confs, timeout).await?;
360 sh_println!("{receipt}")?;
361 }
362 Ok(())
363 }
364
365 pub async fn sent_tx_receipt(&self, tx_hash: B256, confs: u64, timeout: u64) -> Result<String> {
370 self.receipt(format!("{tx_hash:#x}"), None, confs, Some(timeout), false)
371 .await
372 .wrap_err_with(|| {
373 format!("transaction {tx_hash:#x} was sent, but waiting for its receipt failed")
374 })
375 }
376
377 pub async fn receipt(
380 &self,
381 tx_hash: String,
382 field: Option<String>,
383 confs: u64,
384 timeout: Option<u64>,
385 cast_async: bool,
386 ) -> Result<String> {
387 let tx_hash = TxHash::from_str(&tx_hash).wrap_err("invalid tx hash")?;
388 let receipt = match self.provider.get_transaction_receipt(tx_hash).await? {
389 Some(receipt) if cast_async || confs <= 1 => receipt,
390 Some(_) => self.confirm_mined(tx_hash, confs, timeout).await?,
391 None if cast_async => eyre::bail!("tx not found: {tx_hash:?}"),
392 None => self.pending_receipt(tx_hash, confs, timeout).await?,
393 };
394 Ok(self.finish(receipt, field).await?.1)
395 }
396
397 async fn pending_receipt(
399 &self,
400 tx_hash: TxHash,
401 confs: u64,
402 timeout: Option<u64>,
403 ) -> Result<N::ReceiptResponse> {
404 Ok(PendingTransactionBuilder::<N>::new(self.provider.root().clone(), tx_hash)
405 .with_required_confirmations(confs)
406 .with_timeout(timeout.map(Duration::from_secs))
407 .get_receipt()
408 .await?)
409 }
410
411 async fn confirm_mined(
418 &self,
419 tx_hash: TxHash,
420 confs: u64,
421 timeout: Option<u64>,
422 ) -> Result<N::ReceiptResponse> {
423 let confirm = async {
424 let mut poll = tokio::time::interval(self.provider.client().poll_interval());
425 loop {
426 poll.tick().await;
427 let head = self.provider.get_block_number().await?;
428 if let Some(receipt) = self.provider.get_transaction_receipt(tx_hash).await?
429 && let Some(mined) = receipt.block_number()
430 && head >= mined.saturating_add(confs - 1)
431 {
432 break Ok(receipt);
433 }
434 }
435 };
436 match timeout {
437 Some(timeout) => tokio::time::timeout(Duration::from_secs(timeout), confirm)
438 .await
439 .map_err(|_| eyre::eyre!("transaction was not confirmed within the timeout"))?,
440 None => confirm.await,
441 }
442 }
443
444 async fn finish(
446 &self,
447 receipt: N::ReceiptResponse,
448 field: Option<String>,
449 ) -> Result<(B256, String)> {
450 let mut receipt = TransactionReceiptWithRevertReason::<N> { receipt, revert_reason: None };
451 let tx_hash = receipt.receipt.transaction_hash();
452 let _ = receipt.update_revert_reason(&self.provider).await;
453 let formatted = if let Some(field) = field {
454 get_pretty_receipt_w_reason_attr(&receipt, &field)
455 .ok_or_else(|| eyre::eyre!("invalid receipt field: {field}"))?
456 } else if shell::is_json() {
457 serde_json::to_value(&receipt)?.to_string()
459 } else {
460 receipt.pretty()
461 };
462 Ok((tx_hash, formatted))
463 }
464}
465
466#[derive(Debug)]
471pub struct CastTxBuilder<N: Network, P, S> {
472 inner: TxBuilderInner<N, P>,
473 state: S,
474}
475
476#[derive(Debug)]
478struct TxBuilderInner<N: Network, P> {
479 provider: P,
480 tx: N::TransactionRequest,
481 legacy: bool,
483 blob: bool,
484 eip4844: bool,
486 fill: bool,
489 browser: bool,
491 eip1559_fee_estimate: Eip1559FeeEstimatePreset,
493 gas_estimate_multiplier: Option<u64>,
495 sponsored: bool,
497 auth: Vec<CliAuthorizationList>,
498 chain: Chain,
499 etherscan_api_key: Option<String>,
500 etherscan_api_url: Option<String>,
501 access_list: Option<Option<AccessList>>,
502}
503
504impl<N: Network, P, S> CastTxBuilder<N, P, S> {
505 pub const fn chain(&self) -> Chain {
507 self.inner.chain
508 }
509
510 pub(crate) fn etherscan_api(&self) -> (Option<&str>, Option<&str>) {
512 (self.inner.etherscan_api_key.as_deref(), self.inner.etherscan_api_url.as_deref())
513 }
514
515 pub(crate) const fn tx_mut(&mut self) -> &mut N::TransactionRequest {
517 &mut self.inner.tx
518 }
519
520 pub const fn with_browser_wallet(mut self) -> Self {
522 self.inner.browser = true;
523 self
524 }
525
526 pub const fn with_gas_estimate_multiplier(mut self, multiplier: Option<u64>) -> Self {
528 self.inner.gas_estimate_multiplier = multiplier;
529 self
530 }
531
532 pub(crate) const fn has_auth(&self) -> bool {
534 !self.inner.auth.is_empty()
535 }
536
537 pub(crate) fn validate_auth(&self, sender: &SenderKind<'_>) -> Result<()> {
539 validate_authorizations(&self.inner.auth, sender)
540 }
541
542 pub(crate) fn will_disclose_auth_during_build(&self) -> bool {
545 self.has_auth()
548 && (matches!(self.inner.access_list, Some(None))
549 || (self.inner.fill && self.inner.tx.gas_limit().is_none()))
550 }
551
552 fn with_state<S2>(self, state: S2) -> CastTxBuilder<N, P, S2> {
553 CastTxBuilder { inner: self.inner, state }
554 }
555}
556
557impl<N: Network, P: Provider<N>> CastTxBuilder<N, P, InitState>
558where
559 N::TransactionRequest: FoundryTransactionBuilder<N>,
560{
561 pub async fn new(provider: P, tx_opts: TransactionOpts, config: &Config) -> Result<Self> {
564 let mut tx = N::TransactionRequest::default();
565
566 let chain = utils::get_chain(config.chain, &provider).await?;
567 let etherscan_config = config.get_etherscan_config_with_chain(Some(chain)).ok().flatten();
568 let etherscan_api_key = etherscan_config.as_ref().map(|c| c.key.clone());
569 let etherscan_api_url = etherscan_config.map(|c| c.api_url);
570 let legacy = tx_opts.legacy || (chain.is_legacy() && tx_opts.auth.is_empty());
572
573 tx_opts.apply::<N>(&mut tx, legacy);
574 if !config.eth_rpc_curl {
577 ensure_expiring_nonce_discriminator_active(&provider, &tx).await?;
578 }
579
580 Ok(Self {
581 inner: TxBuilderInner {
582 provider,
583 tx,
584 legacy,
585 blob: tx_opts.blob,
586 eip4844: tx_opts.eip4844,
587 fill: true,
588 browser: false,
589 eip1559_fee_estimate: config.eip1559_fee_estimate,
590 gas_estimate_multiplier: None,
591 sponsored: tx_opts.tempo.is_sponsored(),
592 chain,
593 etherscan_api_key,
594 etherscan_api_url,
595 auth: tx_opts.auth,
596 access_list: tx_opts.access_list,
597 },
598 state: InitState,
599 })
600 }
601
602 pub async fn with_to(self, to: Option<NameOrAddress>) -> Result<CastTxBuilder<N, P, ToState>> {
604 let to = match to {
605 Some(to) => Some(to.resolve(&self.inner.provider).await?),
606 None => None,
607 };
608 Ok(self.with_state(ToState { to }))
609 }
610}
611
612impl<N: Network, P: Provider<N>> CastTxBuilder<N, P, ToState>
613where
614 N::TransactionRequest: FoundryTransactionBuilder<N>,
615{
616 pub async fn with_code_sig_and_args(
620 self,
621 code: Option<String>,
622 sig: Option<String>,
623 args: Vec<String>,
624 ) -> Result<CastTxBuilder<N, P, InputState>> {
625 let to = self.state.to;
626 let (mut args, func) = if let Some(sig) = sig {
627 let (key, url) = self.etherscan_api();
628 parse_function_args(&sig, args, to, self.chain(), &self.inner.provider, key, url)
629 .await?
630 } else {
631 (Vec::new(), None)
632 };
633
634 let input = if let Some(code) = &code {
635 let mut code = hex::decode(code)?;
636 code.append(&mut args);
637 code
638 } else {
639 args
640 };
641
642 if to.is_none()
645 && code.is_none()
646 && (!self.has_auth() || self.inner.tx.value().is_some_and(|v| !v.is_zero()))
647 {
648 eyre::bail!("Must specify a recipient address or contract code to deploy");
649 }
650 if to.is_none() && code.is_some() && self.has_auth() {
651 eyre::bail!(
652 "EIP-7702 transactions can't be CREATE transactions and require a destination address"
653 );
654 }
655
656 Ok(self.with_state(InputState { kind: to.into(), input, func }))
657 }
658}
659
660impl<N: Network, P: Provider<N>> CastTxBuilder<N, P, InputState>
661where
662 N::TransactionRequest: FoundryTransactionBuilder<N>,
663{
664 pub async fn build(
667 self,
668 sender: impl Into<SenderKind<'_>>,
669 ) -> Result<(N::TransactionRequest, Option<Function>)> {
670 self.inner.build(self.state, &sender.into(), None).await
671 }
672
673 pub async fn build_with_tempo_wallet(
679 self,
680 wallet: &TempoAccountsWallet,
681 ) -> Result<(N::TransactionRequest, Option<Function>, TempoAccountsWallet)> {
682 let mut prepared = wallet.clone();
683 let (tx, func) =
684 self.inner.build(self.state, &wallet.account().into(), Some(&mut prepared)).await?;
685 Ok((tx, func, prepared))
686 }
687
688 pub fn with_blob_data(mut self, blob_data: Option<Vec<u8>>) -> Result<Self> {
690 let Some(blob_data) = blob_data else { return Ok(self) };
691
692 let mut coder = SidecarBuilder::<SimpleCoder>::default();
693 coder.ingest(&blob_data);
694 if self.inner.eip4844 {
695 self.inner.tx.set_blob_sidecar_4844(coder.build_4844()?);
696 } else {
697 self.inner.tx.set_blob_sidecar_7594(coder.build_7594()?);
698 }
699 Ok(self)
700 }
701
702 pub const fn raw(mut self) -> Self {
705 self.inner.fill = false;
706 self
707 }
708}
709
710impl<N: Network, P: Provider<N>> TxBuilderInner<N, P>
711where
712 N::TransactionRequest: FoundryTransactionBuilder<N>,
713{
714 async fn build(
715 mut self,
716 state: InputState,
717 sender: &SenderKind<'_>,
718 tempo_wallet: Option<&mut TempoAccountsWallet>,
719 ) -> Result<(N::TransactionRequest, Option<Function>)> {
720 let fill = self.fill;
721 let from = sender.address();
722
723 let kind = match state.kind {
726 TxKind::Create if !self.auth.is_empty() => TxKind::Call(from),
727 kind => kind,
728 };
729 self.tx.set_kind(kind);
730 self.tx.set_input_kind(state.input, TransactionInputKind::Both);
733 if !from.is_zero() {
734 self.tx.set_from(from);
735 }
736 self.tx.set_chain_id(self.chain.id());
737 self.tx.clear_batch_to();
741
742 let resolve_in_parallel =
745 fill && self.auth.is_empty() && tempo_wallet.is_none() && !self.chain.is_tempo();
746 let tx_nonce = if resolve_in_parallel {
747 let fees_are_complete = if self.legacy {
748 self.tx.gas_price().is_some()
749 } else {
750 matches!(
751 (self.tx.max_fee_per_gas(), self.tx.max_priority_fee_per_gas()),
752 (Some(max_fee), Some(priority_fee)) if priority_fee <= max_fee
753 )
754 } && (!self.blob || self.tx.max_fee_per_blob_gas().is_some());
755 let gas_request =
756 (fees_are_complete && self.access_list.is_none() && self.tx.gas_limit().is_none())
757 .then(|| self.tx.clone());
758 let (blob, legacy, browser, eip1559_fee_estimate, gas_estimate_multiplier, sponsored) = (
759 self.blob,
760 self.legacy,
761 self.browser,
762 self.eip1559_fee_estimate,
763 self.gas_estimate_multiplier,
764 self.sponsored,
765 );
766 let Self { provider, tx, .. } = &mut self;
767 let provider = &*provider;
768 let (tx_nonce, (), gas_limit) = tokio::try_join!(
769 Self::resolve_nonce(provider, from, tx.nonce(), tx.nonce_key()),
770 Self::fill_fees(provider, tx, blob, legacy, browser, eip1559_fee_estimate),
771 async {
772 match gas_request {
773 Some(request) => Self::estimate_gas(
774 provider,
775 request,
776 gas_estimate_multiplier,
777 sponsored,
778 )
779 .await
780 .map(Some),
781 None => Ok(None),
782 }
783 },
784 )?;
785 if let Some(gas_limit) = gas_limit {
786 self.tx.set_gas_limit(gas_limit);
787 }
788 Some(tx_nonce)
789 } else if fill || !self.auth.is_empty() {
790 Some(
791 Self::resolve_nonce(&self.provider, from, self.tx.nonce(), self.tx.nonce_key())
792 .await?,
793 )
794 } else {
795 None
796 };
797 if let Some(tx_nonce) = tx_nonce {
798 if fill {
799 self.tx.set_nonce(tx_nonce);
800 }
801 self.resolve_auth(sender, tx_nonce).await?;
802 }
803 if let Some(wallet) = tempo_wallet {
804 *wallet = self.tx.prepare_with_tempo_wallet(&self.provider, wallet).await?;
805 }
806 if fill && !resolve_in_parallel {
807 Self::fill_fees(
808 &self.provider,
809 &mut self.tx,
810 self.blob,
811 self.legacy,
812 self.browser,
813 self.eip1559_fee_estimate,
814 )
815 .await?;
816 }
817 let access_list = match self.access_list.take() {
819 None => None,
820 Some(None) => Some(self.provider.create_access_list(&self.tx).await?.access_list),
821 Some(Some(access_list)) => Some(access_list),
822 };
823 if let Some(access_list) = access_list {
824 self.tx.set_access_list(access_list);
825 }
826 if fill && self.tx.gas_limit().is_none() {
827 let request = if self.browser {
828 self.tx.browser_wallet_gas_estimation_request()
829 } else {
830 self.tx.clone()
831 };
832 let estimated = Self::estimate_gas(
833 &self.provider,
834 request,
835 self.gas_estimate_multiplier,
836 self.sponsored,
837 )
838 .await?;
839 self.tx.set_gas_limit(estimated);
840 }
841
842 Ok((self.tx, state.func))
843 }
844
845 async fn resolve_nonce(
851 provider: &P,
852 from: Address,
853 nonce: Option<u64>,
854 nonce_key: Option<U256>,
855 ) -> Result<u64> {
856 if let Some(nonce) = nonce {
857 return Ok(nonce);
858 }
859 match nonce_key {
860 Some(TEMPO_EXPIRING_NONCE_KEY)
861 if !matches!(
862 is_tempo_hardfork_active(provider, TempoHardfork::T1).await,
863 Ok(false)
864 ) =>
865 {
866 Ok(0)
867 }
868 Some(nonce_key) if !nonce_key.is_zero() => {
869 let call = INonce::getNonceCall { account: from, nonceKey: nonce_key };
870 let request = N::TransactionRequest::default()
871 .with_to(NONCE_PRECOMPILE_ADDRESS)
872 .with_input(call.abi_encode());
873 let output = provider.call(request).await?;
874 Ok(INonce::getNonceCall::abi_decode_returns(&output)?)
875 }
876 _ => Ok(provider.get_transaction_count(from).await?),
877 }
878 }
879
880 async fn resolve_auth(&mut self, sender: &SenderKind<'_>, tx_nonce: u64) -> Result<()> {
885 if self.auth.is_empty() {
886 return Ok(());
887 }
888 validate_authorizations(&self.auth, sender)?;
889
890 let mut signed_auths = Vec::with_capacity(self.auth.len());
891 for auth in std::mem::take(&mut self.auth) {
892 signed_auths.push(match auth {
893 CliAuthorizationList::Address(address) => {
894 let signer =
895 sender.as_signer().expect("address-based authorization requires a signer");
896 let authority = signer.address();
897 let nonce = if authority == sender.address()
901 && self.tx.nonce_key().is_none_or(|key| key.is_zero())
902 {
903 tx_nonce + 1
904 } else {
905 self.provider.get_transaction_count(authority).await?
906 };
907 let auth =
908 Authorization { chain_id: U256::from(self.chain.id()), nonce, address };
909 let signature = signer.sign_hash(&auth.signature_hash()).await?;
910 auth.into_signed(signature)
911 }
912 CliAuthorizationList::Signed(auth) => auth,
913 });
914 }
915 self.tx.set_authorization_list(signed_auths);
916 Ok(())
917 }
918
919 async fn fill_fees(
923 provider: &P,
924 tx: &mut N::TransactionRequest,
925 blob: bool,
926 legacy: bool,
927 browser: bool,
928 eip1559_fee_estimate: Eip1559FeeEstimatePreset,
929 ) -> Result<()> {
930 if blob && tx.max_fee_per_blob_gas().is_none() {
931 tx.set_max_fee_per_blob_gas(provider.get_blob_base_fee().await?)
932 }
933 fill_transaction_gas_fees(provider, tx, legacy, browser, eip1559_fee_estimate).await
934 }
935
936 async fn estimate_gas(
938 provider: &P,
939 mut request: N::TransactionRequest,
940 multiplier: Option<u64>,
941 sponsored: bool,
942 ) -> Result<u64> {
943 if sponsored {
944 mark_sponsored_gas_estimation(provider, &mut request).await;
945 }
946 let err = match provider.estimate_gas(request).await {
947 Ok(estimated) => return apply_gas_estimate_multiplier(estimated, multiplier),
948 Err(err) => err,
949 };
950 if let TransportError::ErrorResp(payload) = &err
953 && payload.code == 3
954 && let Some(data) = &payload.data
955 && let Ok(data) = serde_json::from_str::<Bytes>(data.get())
956 && let Ok(Some(decoded_error)) = decode_custom_error(&data).await
957 {
958 eyre::bail!("Failed to estimate gas: {err}: {decoded_error}");
959 }
960 eyre::bail!("Failed to estimate gas: {err}");
961 }
962}
963
964pub(crate) async fn fill_transaction_gas_fees<N: Network, P: Provider<N>>(
966 provider: &P,
967 tx: &mut N::TransactionRequest,
968 legacy: bool,
969 browser: bool,
970 eip1559_fee_estimate: Eip1559FeeEstimatePreset,
971) -> Result<()>
972where
973 N::TransactionRequest: FoundryTransactionBuilder<N>,
974{
975 if legacy {
976 if tx.gas_price().is_none() {
977 tx.set_gas_price(provider.get_gas_price().await?);
978 }
979 return Ok(());
980 }
981
982 if tx.max_fee_per_gas().is_none() || tx.max_priority_fee_per_gas().is_none() {
983 let estimate = estimate_eip1559_fees(provider, eip1559_fee_estimate).await?;
984
985 let browser_suggested_tip = if browser && tx.max_priority_fee_per_gas().is_none() {
988 provider.get_max_priority_fee_per_gas().await.ok()
989 } else {
990 None
991 };
992
993 let estimate = resolve_broadcast_eip1559_fees(estimate, None, None, browser_suggested_tip)?;
996
997 if tx.max_fee_per_gas().is_none() {
998 tx.set_max_fee_per_gas(estimate.max_fee_per_gas);
999 }
1000
1001 if tx.max_priority_fee_per_gas().is_none() {
1002 tx.set_max_priority_fee_per_gas(estimate.max_priority_fee_per_gas);
1003 }
1004 }
1005
1006 if let (Some(max_fee), Some(priority)) = (tx.max_fee_per_gas(), tx.max_priority_fee_per_gas()) {
1007 eyre::ensure!(
1008 priority <= max_fee,
1009 "max priority fee per gas ({priority}) cannot exceed max fee per gas ({max_fee})"
1010 );
1011 }
1012
1013 Ok(())
1014}
1015
1016pub(crate) async fn decode_custom_error(data: &[u8]) -> Result<Option<String>> {
1018 let Some(selector) = data.get(..4) else { return Ok(None) };
1019 let Some(known_error) =
1020 SignaturesIdentifier::new(false)?.identify_error(selector.try_into().unwrap()).await
1021 else {
1022 return Ok(None);
1023 };
1024 let mut decoded_error = known_error.name.clone();
1025 if !known_error.inputs.is_empty()
1026 && let Ok(error) = known_error.decode_error(data)
1027 {
1028 write!(decoded_error, "({})", format_tokens(&error.body).format(", "))?;
1029 }
1030 Ok(Some(decoded_error))
1031}
1032
1033#[cfg(test)]
1034mod tests {
1035 use super::*;
1036 use alloy_json_rpc::{RequestPacket, ResponsePacket};
1037 use alloy_network::{AnyNetwork, Ethereum, NetworkTransactionBuilder};
1038 use alloy_provider::{ProviderBuilder, mock::Asserter};
1039 use alloy_rpc_client::RpcClient;
1040 use alloy_sol_types::SolValue;
1041 use alloy_transport::{TransportFut, mock::MockTransport};
1042 use clap::Parser;
1043 use foundry_common::tempo::resolve_and_set_fee_token;
1044 use std::{
1045 sync::{Arc, Mutex},
1046 task::{Context, Poll},
1047 };
1048 use tempo_alloy::TempoNetwork;
1049 use tokio::{sync::Barrier, time::timeout};
1050 use tower::Service;
1051
1052 #[derive(Clone)]
1053 struct BarrierTransport {
1054 inner: MockTransport,
1055 barrier: Arc<Barrier>,
1056 fill_methods: Arc<Mutex<Vec<String>>>,
1057 }
1058
1059 impl Service<RequestPacket> for BarrierTransport {
1060 type Response = ResponsePacket;
1061 type Error = TransportError;
1062 type Future = TransportFut<'static>;
1063
1064 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1065 self.inner.poll_ready(cx)
1066 }
1067
1068 fn call(&mut self, req: RequestPacket) -> Self::Future {
1069 let fill_method = match &req {
1070 RequestPacket::Single(req)
1071 if matches!(
1072 req.method(),
1073 "eth_getTransactionCount" | "eth_gasPrice" | "eth_estimateGas"
1074 ) =>
1075 {
1076 Some(req.method().to_string())
1077 }
1078 _ => None,
1079 };
1080 let Some(fill_method) = fill_method else {
1081 return self.inner.call(req);
1082 };
1083 self.fill_methods.lock().unwrap().push(fill_method);
1084
1085 let barrier = self.barrier.clone();
1086 let mut inner = self.inner.clone();
1087 Box::pin(async move {
1088 barrier.wait().await;
1089 inner.call(req).await
1090 })
1091 }
1092 }
1093
1094 fn mined_receipt(tx_hash: TxHash) -> serde_json::Value {
1096 serde_json::json!({
1097 "type": "0x2",
1098 "status": "0x1",
1099 "cumulativeGasUsed": "0x5208",
1100 "logs": [],
1101 "logsBloom": format!("0x{}", "00".repeat(256)),
1102 "transactionHash": tx_hash,
1103 "transactionIndex": "0x0",
1104 "blockHash": B256::repeat_byte(0x05),
1105 "blockNumber": "0x5",
1106 "gasUsed": "0x5208",
1107 "effectiveGasPrice": "0x1",
1108 "from": Address::repeat_byte(0x22),
1109 "to": TO,
1110 "contractAddress": null
1111 })
1112 }
1113
1114 #[tokio::test]
1115 async fn receipt_of_mined_tx_waits_for_confirmations() {
1116 for (inclusion, heads) in [(5u64, vec![5, 6, 7]), (4, vec![6]), (7, vec![7, 8, 9])] {
1117 let tx_hash = B256::repeat_byte(0xaa);
1118 let asserter = Asserter::new();
1119 asserter.push_success(&mined_receipt(tx_hash));
1120 let mut receipt = mined_receipt(tx_hash);
1122 receipt["blockNumber"] = serde_json::json!(U64::from(inclusion));
1123 receipt["blockHash"] = serde_json::json!(B256::repeat_byte(inclusion as u8));
1124 for head in heads {
1125 asserter.push_success(&U64::from(head));
1126 asserter.push_success(&receipt);
1127 }
1128 let provider = ProviderBuilder::<_, _, AnyNetwork>::default().connect_client(
1129 RpcClient::mocked(asserter.clone()).with_poll_interval(Duration::from_millis(1)),
1130 );
1131 let sender = CastTxSender::new(&provider);
1132
1133 let block = sender
1134 .receipt(format!("{tx_hash:#x}"), Some("blockNumber".into()), 3, Some(5), false)
1135 .await
1136 .unwrap();
1137
1138 assert_eq!(block, inclusion.to_string());
1139 assert!(asserter.read_q().is_empty(), "returned before the third confirmation");
1140 }
1141 }
1142
1143 #[tokio::test]
1144 async fn receipt_of_mined_tx_times_out_without_confirmations() {
1145 let tx_hash = B256::repeat_byte(0xaa);
1146 let asserter = Asserter::new();
1147 asserter.push_success(&mined_receipt(tx_hash));
1148 for _ in 0..10_000 {
1149 asserter.push_success(&U64::from(5));
1150 asserter.push_success(&mined_receipt(tx_hash));
1151 }
1152 let provider = ProviderBuilder::<_, _, AnyNetwork>::default().connect_client(
1153 RpcClient::mocked(asserter).with_poll_interval(Duration::from_millis(1)),
1154 );
1155 let sender = CastTxSender::new(&provider);
1156
1157 let err =
1158 sender.receipt(format!("{tx_hash:#x}"), None, 3, Some(1), false).await.unwrap_err();
1159
1160 assert_eq!(err.to_string(), "transaction was not confirmed within the timeout");
1161 }
1162
1163 #[tokio::test]
1164 async fn receipt_of_remined_tx_times_out_without_confirmations() {
1165 for disappears in [false, true] {
1166 let tx_hash = B256::repeat_byte(0xaa);
1167 let asserter = Asserter::new();
1168 asserter.push_success(&mined_receipt(tx_hash));
1169 asserter.push_success(&U64::from(7));
1170 if disappears {
1171 asserter.push_success(&serde_json::Value::Null);
1172 asserter.push_success(&U64::from(7));
1173 }
1174 let mut remined = mined_receipt(tx_hash);
1176 remined["blockNumber"] = serde_json::json!("0x7");
1177 remined["blockHash"] = serde_json::json!(B256::repeat_byte(0x07));
1178 asserter.push_success(&remined);
1179 for _ in 0..10_000 {
1180 asserter.push_success(&U64::from(7));
1181 asserter.push_success(&remined);
1182 }
1183 let provider = ProviderBuilder::<_, _, AnyNetwork>::default().connect_client(
1184 RpcClient::mocked(asserter).with_poll_interval(Duration::from_millis(1)),
1185 );
1186 let sender = CastTxSender::new(&provider);
1187
1188 let err =
1189 sender.receipt(format!("{tx_hash:#x}"), None, 3, Some(1), false).await.unwrap_err();
1190
1191 assert_eq!(err.to_string(), "transaction was not confirmed within the timeout");
1192 }
1193 }
1194
1195 const TO: Address = Address::repeat_byte(0x11);
1196
1197 async fn builder<P: Provider<Ethereum>>(
1199 provider: P,
1200 args: &[&str],
1201 ) -> CastTxBuilder<Ethereum, P, InputState> {
1202 let config = Config { chain: Some(Chain::mainnet()), ..Default::default() };
1203 let opts = TransactionOpts::parse_from([&["test"], args].concat());
1204 CastTxBuilder::new(provider, opts, &config)
1205 .await
1206 .unwrap()
1207 .with_to(Some(TO.into()))
1208 .await
1209 .unwrap()
1210 .with_code_sig_and_args(None, None, Vec::new())
1211 .await
1212 .unwrap()
1213 }
1214
1215 #[tokio::test]
1216 async fn filled_build_applies_multiplier_to_concurrent_gas_estimate() {
1217 let asserter = Asserter::new();
1218 for _ in 0..2 {
1219 asserter.push_success(&U64::from(100));
1220 }
1221 let fill_methods = Arc::new(Mutex::new(Vec::new()));
1222 let transport = BarrierTransport {
1223 inner: MockTransport::new(asserter),
1224 barrier: Arc::new(Barrier::new(2)),
1225 fill_methods: fill_methods.clone(),
1226 };
1227 let provider = ProviderBuilder::new_with_network::<Ethereum>()
1228 .connect_client(RpcClient::new(transport, true));
1229
1230 let builder = builder(&provider, &["--legacy", "--gas-price", "1"])
1231 .await
1232 .with_gas_estimate_multiplier(Some(150));
1233 let (tx, _) = timeout(Duration::from_secs(1), builder.build(Address::repeat_byte(0x22)))
1234 .await
1235 .expect("nonce and gas requests were not in flight together")
1236 .unwrap();
1237
1238 assert_eq!(tx.nonce, Some(100));
1239 assert_eq!(tx.gas_price, Some(1));
1240 assert_eq!(tx.gas, Some(150));
1241 let mut fill_methods = fill_methods.lock().unwrap().clone();
1242 fill_methods.sort();
1243 assert_eq!(fill_methods, ["eth_estimateGas", "eth_getTransactionCount"]);
1244 }
1245
1246 #[tokio::test]
1247 async fn browser_submission_resolves_type_after_tempo_fee_token() {
1248 let asserter = Asserter::new();
1249 let token = Address::repeat_byte(0x42);
1250 asserter.push_success(&token.abi_encode());
1251 let provider =
1252 ProviderBuilder::new_with_network::<TempoNetwork>().connect_mocked_client(asserter);
1253 let chain = Chain::from_id(4217);
1254 let config = Config { chain: Some(chain), ..Default::default() };
1255 let opts = TransactionOpts::parse_from([
1256 "test",
1257 "--gas-limit",
1258 "21000",
1259 "--nonce",
1260 "0",
1261 "--gas-price",
1262 "1",
1263 "--priority-gas-price",
1264 "1",
1265 ]);
1266 let (mut tx, _) = CastTxBuilder::new(&provider, opts, &config)
1267 .await
1268 .unwrap()
1269 .with_browser_wallet()
1270 .with_to(Some(TO.into()))
1271 .await
1272 .unwrap()
1273 .with_code_sig_and_args(None, None, Vec::new())
1274 .await
1275 .unwrap()
1276 .build(Address::repeat_byte(0x22))
1277 .await
1278 .unwrap();
1279 assert_eq!(tx.inner.transaction_type, None);
1280 assert_eq!(tx.fee_token, None);
1281
1282 resolve_and_set_fee_token(Some(&provider), &mut tx, None).await.unwrap();
1284 tx.prep_for_submission();
1285 assert_eq!(tx.inner.transaction_type, Some(0x76));
1286 assert_eq!(tx.fee_token, Some(token));
1287 }
1288
1289 #[tokio::test]
1290 async fn raw_build_skips_nonce_request() {
1291 let provider =
1294 ProviderBuilder::new_with_network::<Ethereum>().connect_mocked_client(Asserter::new());
1295 builder(&provider, &[]).await.raw().build(Address::repeat_byte(0x22)).await.unwrap();
1296 }
1297
1298 #[tokio::test]
1299 async fn detects_auth_rpc_disclosure() {
1300 let provider =
1301 ProviderBuilder::new_with_network::<Ethereum>().connect_mocked_client(Asserter::new());
1302 let auth = TO.to_string();
1303
1304 let no_auth = builder(&provider, &["--gas-limit", "21000"]).await.raw();
1305 assert!(!no_auth.has_auth());
1306 assert!(!no_auth.will_disclose_auth_during_build());
1307
1308 let rpc_call = builder(&provider, &["--auth", &auth, "--gas-limit", "21000"]).await.raw();
1309 assert!(rpc_call.has_auth());
1310 assert!(!rpc_call.will_disclose_auth_during_build());
1311
1312 let generated_access_list = builder(&provider, &["--auth", &auth, "--access-list"]).await;
1313 assert!(generated_access_list.raw().will_disclose_auth_during_build());
1314
1315 let explicit_access_list =
1316 builder(&provider, &["--auth", &auth, "--access-list", "[]"]).await;
1317 assert!(!explicit_access_list.raw().will_disclose_auth_during_build());
1318
1319 let estimated_gas = builder(&provider, &["--auth", &auth]).await;
1320 assert!(estimated_gas.will_disclose_auth_during_build());
1321 }
1322
1323 #[test]
1324 fn tx_params_parses_gas_price_units() {
1325 #[derive(Parser)]
1326 struct Cli {
1327 #[command(flatten)]
1328 tx: TxParams,
1329 }
1330
1331 let cli =
1332 Cli::try_parse_from(["test", "--gas-price", "10gwei", "--priority-gas-price", "2gwei"])
1333 .unwrap();
1334 assert_eq!(cli.tx.gas_price, Some(U256::from(10_000_000_000u64)));
1335 assert_eq!(cli.tx.priority_gas_price, Some(U256::from(2_000_000_000u64)));
1336
1337 let cli = Cli::try_parse_from(["test", "--gas-price", "100", "--priority-gas-price", "2"])
1338 .unwrap();
1339 assert_eq!(cli.tx.gas_price, Some(U256::from(100)));
1340 assert_eq!(cli.tx.priority_gas_price, Some(U256::from(2)));
1341 }
1342}