Skip to main content

cast/
tx.rs

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    /// Only print the transaction hash and exit immediately.
41    #[arg(id = "async", long = "async", alias = "cast-async", env = "CAST_ASYNC")]
42    pub cast_async: bool,
43
44    /// Wait for transaction receipt synchronously instead of polling.
45    /// Note: uses `eth_sendTransactionSync` or `eth_sendRawTransactionSync`, which may not be
46    /// supported by all clients.
47    #[arg(long, conflicts_with = "async")]
48    pub sync: bool,
49
50    /// The number of confirmations until the receipt is fetched.
51    #[arg(long, default_value = "1")]
52    pub confirmations: u64,
53
54    /// Timeout for sending the transaction.
55    #[arg(long, env = "ETH_TIMEOUT")]
56    pub timeout: Option<u64>,
57
58    /// Polling interval for transaction receipts (in seconds).
59    #[arg(long, alias = "poll-interval", env = "ETH_POLL_INTERVAL")]
60    pub poll_interval: Option<u64>,
61
62    /// Ethereum options
63    #[command(flatten)]
64    pub eth: EthereumOpts,
65
66    /// Browser wallet options
67    #[command(flatten)]
68    pub browser: BrowserWalletOpts,
69}
70
71/// Applies the `--poll-interval` (in seconds) to a provider's receipt polling when one was given.
72pub(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/// Transaction options shared across cast commands that submit on-chain transactions.
79#[derive(Debug, Clone, Args)]
80#[command(next_help_heading = "Transaction options")]
81pub struct TxParams {
82    /// Gas limit for the transaction.
83    #[arg(long, env = "ETH_GAS_LIMIT")]
84    pub gas_limit: Option<U256>,
85
86    /// Gas price for legacy transactions, or max fee per gas for EIP1559 transactions, either
87    /// specified in wei, or as a string with a unit type.
88    ///
89    /// Examples: 1ether, 10gwei, 0.01ether
90    #[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    /// Max priority fee per gas for EIP1559 transactions.
99    #[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    /// Nonce for the transaction.
108    #[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    /// Converts the shared compact transaction options into the full `cast send` options.
124    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
142/// Different sender kinds used by [`CastTxBuilder`].
143pub enum SenderKind<'a> {
144    /// An address without signer. Used for read-only calls and transactions sent through unlocked
145    /// accounts.
146    Address(Address),
147    /// A reference to a signer.
148    Signer(&'a WalletSigner),
149    /// An owned signer.
150    OwnedSigner(Box<WalletSigner>),
151}
152
153impl SenderKind<'_> {
154    /// Resolves the name to an Ethereum Address.
155    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    /// Resolves the sender from the wallet options.
164    ///
165    /// Returns `from` when set, unless a Tempo access key is set or an address-based authorization
166    /// needs a signer. Otherwise returns the configured signer (or Tempo wallet account), falling
167    /// back to the zero address.
168    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    /// Returns the signer if available.
190    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
217/// Resolves the sender of a read-only request: the browser wallet address when `--browser` is
218/// set, otherwise the wallet options. Also returns whether the browser wallet was used.
219pub(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
236/// Validates that `sender` can resolve every EIP-7702 authorization.
237pub(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
261/// Resolves the sending signer, falling back to the wallet options, and validates it against an
262/// explicit `--from`.
263pub(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
276/// Prevents a misconfigured hwlib from sending a transaction that defies user-specified --from
277pub 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/// Initial state.
296#[derive(Debug)]
297pub struct InitState;
298
299/// State with known [TxKind].
300#[derive(Debug)]
301pub struct ToState {
302    to: Option<Address>,
303}
304
305/// State with known input for the transaction.
306#[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    /// Creates a new Cast instance responsible for sending transactions.
324    pub const fn new(provider: P) -> Self {
325        Self { provider, _phantom: PhantomData }
326    }
327
328    /// Sends a transaction and waits for receipt synchronously
329    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    /// Sends a transaction and returns the pending transaction handle.
335    pub async fn send(&self, tx: N::TransactionRequest) -> Result<PendingTransactionBuilder<N>> {
336        Ok(self.provider.send_transaction(tx).await?)
337    }
338
339    /// Sends a raw RLP-encoded transaction and waits for its receipt synchronously.
340    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    /// Prints the transaction hash (if async) or waits for the receipt and prints it.
346    ///
347    /// This is the shared "output" path used by both the normal send flow and the browser wallet
348    /// flow (which sends the transaction out-of-band and only has a tx hash).
349    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    /// Waits for the receipt of a transaction that was already sent, and formats it.
366    ///
367    /// On failure the error names the hash, so that the transaction can be looked up instead of
368    /// sent again.
369    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    /// Fetches the receipt of `tx_hash`, polling for it unless `cast_async` is set, and formats
378    /// it (or the requested `field`).
379    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    /// Waits for a pending transaction to be mined and confirmed `confs` times.
398    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    /// Waits until an already-mined transaction has `confs` confirmations.
412    ///
413    /// The pending transaction watcher only sees blocks mined after it starts, so it cannot
414    /// confirm a transaction that is already mined: this polls the chain head and receipt
415    /// instead. A reorg may move the transaction to an earlier or later block, or remove it.
416    /// Its current inclusion must have enough confirmations, within the same timeout.
417    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    /// Attaches the revert reason (best effort) and formats the receipt.
445    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            // to_value first to sort json object keys
458            serde_json::to_value(&receipt)?.to_string()
459        } else {
460            receipt.pretty()
461        };
462        Ok((tx_hash, formatted))
463    }
464}
465
466/// Builder type constructing generic TransactionRequest from cast send/mktx inputs.
467///
468/// It is implemented as a stateful builder with expected state transition of [InitState] ->
469/// [ToState] -> [InputState].
470#[derive(Debug)]
471pub struct CastTxBuilder<N: Network, P, S> {
472    inner: TxBuilderInner<N, P>,
473    state: S,
474}
475
476/// The state-independent part of [`CastTxBuilder`].
477#[derive(Debug)]
478struct TxBuilderInner<N: Network, P> {
479    provider: P,
480    tx: N::TransactionRequest,
481    /// Whether the transaction should be sent as a legacy transaction.
482    legacy: bool,
483    blob: bool,
484    /// Whether the blob transaction should use EIP-4844 (legacy) format instead of EIP-7594.
485    eip4844: bool,
486    /// Whether to fill gas, fees and nonce. Set to `false` for read-only calls
487    /// (eth_call, eth_estimateGas, eth_createAccessList).
488    fill: bool,
489    /// Whether the filled transaction will be submitted through a browser wallet.
490    browser: bool,
491    /// The preset used when estimating EIP-1559 fees.
492    eip1559_fee_estimate: Eip1559FeeEstimatePreset,
493    /// Optional percentage applied to provider gas estimates.
494    gas_estimate_multiplier: Option<u64>,
495    /// Whether a Tempo fee payer will sponsor the transaction.
496    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    /// Returns the resolved chain for this builder.
506    pub const fn chain(&self) -> Chain {
507        self.inner.chain
508    }
509
510    /// Returns the Etherscan API key and URL resolved for this builder's chain.
511    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    /// Returns the transaction request being built.
516    pub(crate) const fn tx_mut(&mut self) -> &mut N::TransactionRequest {
517        &mut self.inner.tx
518    }
519
520    /// Marks this transaction as destined for browser wallet submission.
521    pub const fn with_browser_wallet(mut self) -> Self {
522        self.inner.browser = true;
523        self
524    }
525
526    /// Applies a percentage multiplier to provider gas estimates.
527    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    /// Returns whether this builder contains any EIP-7702 authorizations.
533    pub(crate) const fn has_auth(&self) -> bool {
534        !self.inner.auth.is_empty()
535    }
536
537    /// Validates that the configured sender can resolve all EIP-7702 authorizations.
538    pub(crate) fn validate_auth(&self, sender: &SenderKind<'_>) -> Result<()> {
539        validate_authorizations(&self.inner.auth, sender)
540    }
541
542    /// Returns whether building this request will disclose an EIP-7702 authorization to an RPC
543    /// endpoint.
544    pub(crate) fn will_disclose_auth_during_build(&self) -> bool {
545        // Generating an access list or estimating gas sends the authorization-bearing request
546        // to the RPC.
547        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    /// Creates a new instance of [CastTxBuilder] filling transaction with fields present in
562    /// provided [TransactionOpts].
563    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        // mark it as legacy if requested or the chain is legacy and no 7702 is provided.
571        let legacy = tx_opts.legacy || (chain.is_legacy() && tx_opts.auth.is_empty());
572
573        tx_opts.apply::<N>(&mut tx, legacy);
574        // The curl transport answers every request with a placeholder, so there is nothing to
575        // check against.
576        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    /// Sets [TxKind] for this builder and changes state to [ToState].
603    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    /// Accepts user-provided code, sig and args params and constructs calldata for the transaction.
617    /// If code is present, input will be set to code + encoded constructor arguments. If no code is
618    /// present, input is set to just provided arguments.
619    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        // We only allow user to omit the recipient address if transaction is an EIP-7702 tx
643        // without a value. The sender is used as the destination in that case, see `build`.
644        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    /// Builds the TransactionRequest. Fills gas, fees and nonce unless [`raw`](Self::raw) was
665    /// called.
666    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    /// Builds a transaction that will be signed by a Tempo access key.
674    ///
675    /// The access-key id is set before gas estimation. If the access key needs on-chain
676    /// provisioning, its authorization is embedded before access-list/gas estimation and before
677    /// any sponsor digest can be computed.
678    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    /// Populates the blob sidecar for the transaction if any blob data was provided.
689    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    /// Skips gas, fee and nonce filling. Use for read-only calls
703    /// (eth_call, eth_estimateGas, eth_createAccessList).
704    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        // An EIP-7702 transaction can't be a CREATE. If the recipient was omitted, the sender
724        // itself is the destination, which is the common case for self-delegation.
725        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        // We set both fields to the same value because some nodes only accept the legacy
731        // `data` field: https://github.com/foundry-rs/foundry/issues/7764#issuecomment-2210453249
732        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        // For batch transactions with calls, clear `to` and `value` so the node correctly
738        // identifies this as an AA batch transaction. The `calls` field determines the actual
739        // targets. If `to` is set, `build_aa()` would add a spurious extra call.
740        self.tx.clear_batch_to();
741
742        // Read-only calls do not need a nonce unless it is required to sign an authorization.
743        // Avoid an otherwise unused `eth_getTransactionCount` request for raw transactions.
744        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        // Fetch the access list from the provider if `--access-list` was passed without a value.
818        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    /// Resolves the transaction nonce. Returns the existing nonce or fetches one from the provider.
846    ///
847    /// A Tempo nonce key other than the protocol key `0` selects a 2D nonce lane with its own
848    /// counter in the Nonce Manager precompile. From T1 on, the expiring nonce key has no counter:
849    /// its nonce is a discriminator that defaults to `0`. Before T1 it is an ordinary lane.
850    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    /// Parses the passed --auth values and sets the authorization list on the transaction.
881    ///
882    /// If a signer is available in `sender`, address-based auths will be signed.
883    /// If no signer is available, all auths must be pre-signed.
884    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                    // Authorizations apply after the transaction's nonce. Only a protocol-nonce
898                    // transaction bumps the sender's account nonce first; a Tempo nonce lane or
899                    // expiring nonce leaves it unchanged.
900                    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    /// Fills gas price, EIP-1559 fees, and blob fees from the provider.
920    ///
921    /// Only fills values that haven't been explicitly set by the user.
922    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    /// Estimate tx gas from provider call. Tries to decode custom error if execution reverted.
937    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 execution reverted with code 3 during provider gas estimation then try to decode
951        // custom errors and append it to the error message.
952        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
964/// Fills gas price or EIP-1559 fee fields from the provider and validates the final pair.
965pub(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        // Only honor the browser-suggested tip when the user has not pinned a
986        // priority fee; `resolve_broadcast_eip1559_fees` ignores a lower tip.
987        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        // User `--gas-price`/`--priority-gas-price` overrides are already applied
994        // to `tx`; pass `None` so they are not double-applied here.
995        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
1016/// Tries to decode a custom error name and inputs from revert data.
1017pub(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    /// A successful receipt of a transfer mined in block 5.
1095    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            // Confirm the current inclusion, even if a reorg moved it earlier or later.
1121            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            // The old inclusion has three confirmations, but the new one has only one.
1175            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    /// Builds a transaction to [`TO`] from the given `cast send` style arguments.
1198    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        // Fee resolution happens after building and can change the submission type to Tempo AA.
1283        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        // No responses are queued, so any RPC request would fail this test. In particular, this
1292        // guards against restoring the unused `eth_getTransactionCount` request.
1293        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}