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