Skip to main content

cast/cmd/
send.rs

1use crate::{
2    cmd::{
3        auth::{confirm_and_build, confirm_and_build_with_tempo_wallet},
4        confirm_continue,
5        tip20::iso4217_warning_message,
6    },
7    tempo,
8    tx::{self, CastTxBuilder, CastTxSender, SendTxOpts, TxParams, apply_poll_interval},
9};
10use alloy_consensus::{SignableTransaction, Signed};
11use alloy_ens::NameOrAddress;
12use alloy_network::{Ethereum, EthereumWallet, Network, NetworkTransactionBuilder};
13use alloy_primitives::{Address, B256, hex};
14use alloy_provider::{Provider, ProviderBuilder as AlloyProviderBuilder};
15use alloy_signer::{Signature, Signer};
16use clap::Parser;
17use eyre::{Result, eyre};
18use foundry_cli::{
19    opts::TransactionOpts,
20    utils::{LoadConfig, get_chain, resolve_lane},
21};
22use foundry_common::{
23    FoundryTransactionBuilder,
24    fmt::{UIfmt, UIfmtReceiptExt},
25    provider::ProviderBuilder,
26    tempo::{configurable_account::ConfigurableAccountSigner, maybe_print_fee_token},
27};
28use foundry_config::Config;
29use foundry_wallets::{WalletSigner, wallet_browser::signer::BrowserSigner};
30use std::{path::PathBuf, str::FromStr};
31use tempo_alloy::{TempoNetwork, accounts::TempoAccountsWallet};
32use tempo_contracts::precompiles::{TIP20_FACTORY_ADDRESS, is_iso4217_currency};
33use tempo_primitives::transaction::FEE_PAYER_SIGNATURE_MARKER;
34use url::Url;
35
36#[cfg(feature = "base")]
37use base_common_network::Base;
38
39/// CLI arguments for `cast send`.
40#[derive(Debug, Parser)]
41pub struct SendTxArgs {
42    /// The destination of the transaction.
43    ///
44    /// If not provided, you must use cast send --create.
45    #[arg(value_parser = NameOrAddress::from_str)]
46    to: Option<NameOrAddress>,
47
48    /// The signature of the function to call.
49    sig: Option<String>,
50
51    /// The arguments of the function to call.
52    #[arg(allow_negative_numbers = true)]
53    args: Vec<String>,
54
55    /// Raw hex-encoded data for the transaction. Used instead of `SIG` and `ARGS`.
56    #[arg(
57        long,
58        conflicts_with_all = &["sig", "args"]
59    )]
60    data: Option<String>,
61
62    #[command(flatten)]
63    send_tx: SendTxOpts,
64
65    #[command(subcommand)]
66    command: Option<SendTxSubcommands>,
67
68    /// Send via `eth_sendTransaction` using the `--from` argument or $ETH_FROM as sender
69    #[arg(long, requires = "from")]
70    unlocked: bool,
71
72    /// Skip confirmation prompts (e.g. non-ISO 4217 currency warnings).
73    #[arg(long)]
74    force: bool,
75
76    /// Relative percentage to multiply the gas estimate by.
77    #[arg(long, value_name = "PERCENT", help_heading = "Transaction options")]
78    gas_estimate_multiplier: Option<u64>,
79
80    #[command(flatten)]
81    tx: TransactionOpts,
82
83    /// The path of blob data to be sent.
84    #[arg(
85        long,
86        value_name = "BLOB_DATA_PATH",
87        conflicts_with = "legacy",
88        requires = "blob",
89        help_heading = "Transaction options"
90    )]
91    path: Option<PathBuf>,
92}
93
94#[derive(Debug, Parser)]
95pub enum SendTxSubcommands {
96    /// Use to deploy raw contract bytecode.
97    #[command(name = "--create")]
98    Create {
99        /// The bytecode of the contract to deploy.
100        code: String,
101
102        /// The signature of the function to call.
103        sig: Option<String>,
104
105        /// The arguments of the function to call.
106        #[arg(allow_negative_numbers = true)]
107        args: Vec<String>,
108    },
109}
110
111impl SendTxArgs {
112    /// Creates a `cast send` invocation for pre-encoded contract calldata.
113    pub(crate) fn contract_call(
114        to: NameOrAddress,
115        data: Vec<u8>,
116        send_tx: SendTxOpts,
117        tx: TxParams,
118    ) -> Self {
119        Self {
120            to: Some(to),
121            sig: None,
122            args: Vec::new(),
123            data: Some(hex::encode_prefixed(data)),
124            send_tx,
125            command: None,
126            unlocked: false,
127            force: false,
128            gas_estimate_multiplier: None,
129            tx: tx.into_transaction_opts(),
130            path: None,
131        }
132    }
133
134    pub async fn run(self) -> Result<()> {
135        // Tempo rejects keychain transactions whose first call is a CREATE.
136        eyre::ensure!(
137            self.tx.tempo.configurable_access_key.is_none()
138                || !matches!(self.command, Some(SendTxSubcommands::Create { .. })),
139            "--tempo.configurable-access-key cannot deploy: Tempo access keys cannot sign CREATE"
140        );
141        if self.to.is_none() && matches!(self.command, Some(SendTxSubcommands::Create { .. })) {
142            if !self.tx.auth.is_empty() {
143                eyre::bail!(
144                    "EIP-7702 transactions can't be CREATE transactions and require a destination address"
145                );
146            }
147            if self.path.is_some() {
148                eyre::bail!(
149                    "EIP-4844 transactions can't be CREATE transactions and require a destination address"
150                );
151            }
152        }
153
154        let (network, signer, tempo_access_key) =
155            tempo::resolve_transaction_network_and_signer(&self.tx.tempo, &self.send_tx.eth)
156                .await?;
157
158        if network.is_tempo() {
159            return self.run_generic::<TempoNetwork>(signer, tempo_access_key).await;
160        }
161
162        #[cfg(feature = "base")]
163        if network.is_base() {
164            super::validate_base_transaction_options(&self.tx)?;
165            return self.run_generic::<Base>(signer, None).await;
166        }
167
168        self.run_generic::<Ethereum>(signer, None).await
169    }
170
171    /// Runs a contract call with an already resolved browser signer.
172    pub(crate) async fn run_generic_with_browser<N: Network>(
173        self,
174        browser: BrowserSigner<N>,
175    ) -> Result<()>
176    where
177        N::TxEnvelope: From<Signed<N::UnsignedTx>>,
178        N::UnsignedTx: SignableTransaction<Signature>,
179        N::TransactionRequest: FoundryTransactionBuilder<N>,
180        N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
181    {
182        self.run_generic_inner::<N>(None, None, Some(browser)).await
183    }
184
185    pub(crate) async fn run_generic<N: Network>(
186        self,
187        pre_resolved_signer: Option<WalletSigner>,
188        access_key: Option<TempoAccountsWallet>,
189    ) -> Result<()>
190    where
191        N::TxEnvelope: From<Signed<N::UnsignedTx>>,
192        N::UnsignedTx: SignableTransaction<Signature>,
193        N::TransactionRequest: FoundryTransactionBuilder<N>,
194        N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
195    {
196        self.run_generic_inner::<N>(pre_resolved_signer, access_key, None).await
197    }
198
199    async fn run_generic_inner<N: Network>(
200        self,
201        mut pre_resolved_signer: Option<WalletSigner>,
202        mut access_key: Option<TempoAccountsWallet>,
203        pre_resolved_browser: Option<BrowserSigner<N>>,
204    ) -> Result<()>
205    where
206        N::TxEnvelope: From<Signed<N::UnsignedTx>>,
207        N::UnsignedTx: SignableTransaction<Signature>,
208        N::TransactionRequest: FoundryTransactionBuilder<N>,
209        N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
210    {
211        let Self {
212            to,
213            mut sig,
214            mut args,
215            data,
216            send_tx,
217            mut tx,
218            command,
219            unlocked,
220            force,
221            gas_estimate_multiplier,
222            path,
223        } = self;
224
225        let has_session = tx.tempo.session_id()?.is_some();
226        if has_session && unlocked {
227            eyre::bail!("--tempo.session/TEMPO_SESSION_ID cannot be combined with --unlocked");
228        }
229        tempo::ensure_session_not_browser(&tx.tempo, send_tx.browser.browser)?;
230
231        let print_sponsor_hash = tx.tempo.print_sponsor_hash;
232        let sponsor_url = tx.tempo.sponsor_url.clone();
233        let sponsor_fee_payer = tx.tempo.sponsor;
234        let expires_at = tx.tempo.resolve_expires();
235        let tempo_sponsor = if print_sponsor_hash || sponsor_url.is_some() {
236            None
237        } else {
238            tx.tempo.sponsor_config().await?
239        };
240
241        let blob_data = path.map(std::fs::read).transpose()?;
242
243        if let Some(data) = data {
244            sig = Some(data);
245        }
246
247        let code = if let Some(SendTxSubcommands::Create {
248            code,
249            sig: constructor_sig,
250            args: constructor_args,
251        }) = command
252        {
253            sig = constructor_sig;
254            args = constructor_args;
255            Some(code)
256        } else {
257            None
258        };
259
260        // Validate ISO 4217 currency code for TIP20Factory createToken calls.
261        if let Some(to_addr) = &to {
262            let is_factory = match to_addr {
263                NameOrAddress::Address(addr) => *addr == TIP20_FACTORY_ADDRESS,
264                NameOrAddress::Name(name) => {
265                    Address::from_str(name).ok() == Some(TIP20_FACTORY_ADDRESS)
266                }
267            };
268
269            if !force
270                && is_factory
271                && let Some(sig_str) = &sig
272                && sig_str.starts_with("createToken")
273                && let Some(currency) = args.get(2)
274                && !is_iso4217_currency(currency)
275            {
276                sh_warn!("{}", iso4217_warning_message(currency))?;
277                if !confirm_continue()? {
278                    return Ok(());
279                }
280            }
281        }
282
283        let config = send_tx.eth.load_config()?;
284        let provider = ProviderBuilder::<N>::from_config(&config)?.build()?;
285        // The provider is not consulted for fee tokens in `--curl` mode.
286        let fee_provider = (!config.eth_rpc_curl).then_some(&provider);
287
288        let resolved_lane = resolve_lane(&mut tx.tempo, &config.root)?;
289        let lane = resolved_lane.as_ref();
290
291        apply_poll_interval(&provider, send_tx.poll_interval);
292
293        if has_session || access_key.is_some() {
294            let chain = get_chain(config.chain, &provider).await?;
295            access_key =
296                tempo::resolve_session_or_wallet_signer(&tx.tempo, &send_tx.eth.wallet, chain.id())
297                    .await?
298                    .1;
299        }
300
301        // Inject access key ID into TempoOpts so it's set before gas estimation.
302        if let Some(ak) = &access_key {
303            tx.tempo.key_id = Some(ak.key_id()?);
304        }
305
306        // A configurable account sender signs with its owners, which the RPC, a browser wallet or
307        // an access key cannot do.
308        let configurable_account = if access_key.is_some()
309            || unlocked
310            || send_tx.browser.browser
311            || pre_resolved_browser.is_some()
312        {
313            eyre::ensure!(
314                !tx.tempo.has_configurable_account_options(),
315                "Tempo configurable accounts cannot be combined with --unlocked, --browser or an \
316                 access key"
317            );
318            None
319        } else {
320            tempo::resolve_configurable_account::<N>(
321                &tx.tempo,
322                &config,
323                &send_tx.eth.wallet,
324                &mut pre_resolved_signer,
325            )
326            .await?
327        };
328
329        let mut builder = CastTxBuilder::new(&provider, tx, &config)
330            .await?
331            .with_gas_estimate_multiplier(gas_estimate_multiplier)
332            .with_to(to)
333            .await?
334            .with_code_sig_and_args(code, sig, args)
335            .await?
336            .with_blob_data(blob_data)?;
337        let chain = builder.chain();
338        if let Some(account) = &configurable_account {
339            account.prepare_request::<N>(builder.tx_mut());
340        }
341
342        // If --tempo.print-sponsor-hash was passed, build the tx, print the hash, and exit.
343        if print_sponsor_hash {
344            // The sponsor hash commits to the sender, so resolve the actual sender first.
345            let (mut tx, from) = if let Some(ak) = &access_key {
346                let Some((tx, prepared)) =
347                    confirm_and_build_with_tempo_wallet(builder, ak, force, None).await?
348                else {
349                    return Ok(());
350                };
351                (tx, prepared.account())
352            } else if let Some(account) = &configurable_account {
353                let Some(tx) =
354                    confirm_and_build(builder, account.sender(), force, None, false).await?
355                else {
356                    return Ok(());
357                };
358                (tx, account.sender())
359            } else {
360                let signer = pre_resolved_signer.as_ref().ok_or_else(|| {
361                    eyre!("--tempo.print-sponsor-hash requires a signer (e.g. --private-key)")
362                })?;
363                let Some(tx) = confirm_and_build(builder, signer, force, None, false).await? else {
364                    return Ok(());
365                };
366                (tx, signer.address())
367            };
368            let hash = tempo::sponsor_hash(fee_provider, &mut tx, from, sponsor_fee_payer).await?;
369            sh_println!("{hash:?}")?;
370            return Ok(());
371        }
372
373        tempo::print_expires(expires_at)?;
374
375        // Without a sponsor the fee token is resolved for the sender while sending.
376        let send_opts = SendOptions::new(&send_tx, &config);
377        let fee_send_opts = send_opts.resolving_fee_token(tempo_sponsor.is_none(), &config);
378
379        // --sponsor-url is valid with local signers and Tempo access keys. Bail early rather than
380        // silently ignoring it in signing paths that cannot produce a raw transaction locally.
381        if let Some(url) = &sponsor_url {
382            validate_sponsor_url(url)?;
383            if unlocked {
384                eyre::bail!("--sponsor-url cannot be combined with --unlocked");
385            }
386            if send_tx.browser.browser {
387                eyre::bail!("--sponsor-url cannot be combined with --browser");
388            }
389        }
390
391        // Launch a browser signer if one was not already resolved by the caller.
392        let browser = if let Some(browser) = pre_resolved_browser {
393            Some(browser)
394        } else {
395            send_tx.browser.run::<N>().await?
396        };
397
398        // Case 1:
399        // Default to sending via eth_sendTransaction if the --unlocked flag is passed.
400        // This should be the only way this RPC method is used as it requires a local node
401        // or remote RPC with unlocked accounts.
402        if unlocked && browser.is_none() {
403            // Switch chain if the current chain id is not the one specified in the config.
404            if let Some(config_chain) = config.chain {
405                let config_chain_id = config_chain.id();
406                if config_chain_id != provider.get_chain_id().await? {
407                    sh_warn!("Switching to chain {}", config_chain)?;
408                    provider
409                        .raw_request::<_, ()>(
410                            "wallet_switchEthereumChain".into(),
411                            [serde_json::json!({
412                                "chainId": format!("{config_chain_id:#x}"),
413                            })],
414                        )
415                        .await?;
416                }
417            }
418
419            let Some(mut tx_request) =
420                confirm_and_build(builder, config.sender, force, lane, false).await?
421            else {
422                return Ok(());
423            };
424            tempo::maybe_attach_sponsor(
425                tempo_sponsor.as_ref(),
426                fee_provider,
427                &mut tx_request,
428                config.sender,
429            )
430            .await?;
431
432            cast_send(provider, tx_request, &fee_send_opts).await?;
433        // Case 2:
434        // Browser wallet signs and sends the transaction in one step.
435        } else if let Some(browser) = browser {
436            let from = browser.address();
437            let Some(mut tx_request) =
438                confirm_and_build(builder.with_browser_wallet(), from, force, lane, false).await?
439            else {
440                return Ok(());
441            };
442            tempo::apply_fee_payment::<N, _>(
443                tempo_sponsor.as_ref(),
444                fee_provider,
445                &mut tx_request,
446                from,
447            )
448            .await?;
449
450            if chain.id() != browser.chain_id() {
451                sh_warn!("Switching browser wallet to chain {}", chain)?;
452                browser.switch_chain(chain.id()).await?;
453            }
454
455            tx_request.prep_for_submission();
456            let tx_hash = browser.send_transaction_via_browser(tx_request).await?;
457            send_opts.print_tx_result(&provider, tx_hash).await?;
458        // Case 3: Tempo access-key wallet.
459        } else if let Some(ak) = access_key {
460            let Some((mut tx_request, prepared)) =
461                confirm_and_build_with_tempo_wallet(builder, &ak, force, lane).await?
462            else {
463                return Ok(());
464            };
465            tempo::maybe_attach_sponsor(
466                tempo_sponsor.as_ref(),
467                fee_provider,
468                &mut tx_request,
469                prepared.account(),
470            )
471            .await?;
472            if let Some(sponsor_url) = sponsor_url.as_deref() {
473                cast_send_with_tempo_wallet_via_sponsor(
474                    &provider,
475                    tx_request,
476                    &prepared,
477                    sponsor_url,
478                    &send_opts,
479                )
480                .await?;
481            } else {
482                cast_send_with_tempo_wallet(&provider, tx_request, &prepared, &fee_send_opts)
483                    .await?;
484            }
485        // Case 4: a Tempo configurable account signed by its local owners.
486        } else if let Some(account) = configurable_account {
487            let from = account.sender();
488            let Some(mut tx_request) = confirm_and_build(builder, from, force, lane, false).await?
489            else {
490                return Ok(());
491            };
492            if let Some(sponsor_url) = sponsor_url.as_deref() {
493                // The relay selects the fee token and adds its fee-payer signature.
494                tx_request.set_fee_payer_signature(FEE_PAYER_SIGNATURE_MARKER);
495                let connector = tempo::sponsor_relay_connector(&provider, sponsor_url)?;
496                let sponsor_provider =
497                    AlloyProviderBuilder::<_, _, N>::default().connect_with(&connector).await?;
498                cast_send_with_configurable_account(
499                    &sponsor_provider,
500                    tx_request,
501                    &account,
502                    &send_opts,
503                )
504                .await?;
505            } else {
506                tempo::maybe_attach_sponsor(
507                    tempo_sponsor.as_ref(),
508                    fee_provider,
509                    &mut tx_request,
510                    from,
511                )
512                .await?;
513                cast_send_with_configurable_account(
514                    &provider,
515                    tx_request,
516                    &account,
517                    &fee_send_opts,
518                )
519                .await?;
520            }
521        // Case 5: a local signer.
522        // If we cannot successfully instantiate a local signer, then we will assume we don't have
523        // enough information to sign and we must bail.
524        } else {
525            let (signer, from) = tx::resolve_send_signer(pre_resolved_signer, &send_tx.eth).await?;
526            let Some(mut tx_request) =
527                confirm_and_build(builder, &signer, force, lane, false).await?
528            else {
529                return Ok(());
530            };
531            let wallet_provider = AlloyProviderBuilder::<_, _, N>::default();
532
533            if let Some(sponsor_url) = sponsor_url {
534                // Sign locally, ask the sponsor service for a fee-payer signature, then submit the
535                // fully-sponsored tx to the regular RPC.
536                tx_request.set_fee_payer_signature(FEE_PAYER_SIGNATURE_MARKER);
537                let connector = tempo::sponsor_relay_connector(&provider, &sponsor_url)?;
538                let provider = wallet_provider
539                    .wallet(EthereumWallet::from(signer))
540                    .connect_with(&connector)
541                    .await?;
542                cast_send(provider, tx_request, &send_opts).await?;
543            } else {
544                tempo::maybe_attach_sponsor(
545                    tempo_sponsor.as_ref(),
546                    fee_provider,
547                    &mut tx_request,
548                    from,
549                )
550                .await?;
551                let provider = wallet_provider
552                    .wallet(EthereumWallet::from(signer))
553                    .connect_provider(&provider);
554                cast_send(provider, tx_request, &fee_send_opts).await?;
555            }
556        }
557
558        Ok(())
559    }
560}
561
562/// How a transaction is submitted and its result reported.
563#[derive(Clone, Copy, Debug)]
564pub(crate) struct SendOptions {
565    /// Only print the transaction hash instead of waiting for the receipt.
566    cast_async: bool,
567    /// Submit with the synchronous RPC methods and print the returned receipt.
568    sync: bool,
569    confirmations: u64,
570    timeout: u64,
571    /// How the Tempo fee token is handled before sending.
572    fee_token: FeeTokenMode,
573}
574
575/// How [`cast_send`] handles the Tempo fee token of a transaction before sending it.
576#[derive(Clone, Copy, Debug, PartialEq, Eq)]
577enum FeeTokenMode {
578    /// Leave the fee token as built, e.g. when a sponsor already selected it, and print it
579    /// without querying the provider.
580    AsBuilt,
581    /// Resolve a missing fee token for the sender, querying the provider for the stored fee token
582    /// and its symbol.
583    Resolve,
584    /// Resolve a missing fee token for the sender without querying the provider, e.g. when the
585    /// request is only rendered as `curl`.
586    ResolveOffline,
587}
588
589impl FeeTokenMode {
590    /// Whether the provider may be queried for the stored fee token and its symbol.
591    const fn queries_provider(self) -> bool {
592        matches!(self, Self::Resolve)
593    }
594}
595
596impl SendOptions {
597    /// Submission options from the CLI flags and config, without fee token resolution.
598    pub(crate) fn new(send_tx: &SendTxOpts, config: &Config) -> Self {
599        Self {
600            cast_async: send_tx.cast_async,
601            sync: send_tx.sync,
602            confirmations: send_tx.confirmations,
603            timeout: send_tx.timeout.unwrap_or(config.transaction_timeout),
604            fee_token: FeeTokenMode::AsBuilt,
605        }
606    }
607
608    /// Resolves the sender's fee token before sending when `resolve` is set, querying the RPC
609    /// unless the request is only rendered as `curl`.
610    pub(crate) const fn resolving_fee_token(self, resolve: bool, config: &Config) -> Self {
611        let fee_token = if !resolve {
612            FeeTokenMode::AsBuilt
613        } else if config.eth_rpc_curl {
614            FeeTokenMode::ResolveOffline
615        } else {
616            FeeTokenMode::Resolve
617        };
618        Self { fee_token, ..self }
619    }
620
621    /// Prints the hash of a submitted transaction, or its receipt unless `--async` was passed.
622    pub(crate) async fn print_tx_result<N: Network, P: Provider<N>>(
623        &self,
624        provider: P,
625        tx_hash: B256,
626    ) -> Result<()>
627    where
628        N::TransactionRequest: FoundryTransactionBuilder<N>,
629        N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
630    {
631        CastTxSender::new(provider)
632            .print_tx_result(tx_hash, self.cast_async, self.confirmations, self.timeout)
633            .await
634    }
635
636    /// Prints a sync receipt, or the hash / polled receipt of a pending transaction.
637    pub(crate) async fn print_send_result<N: Network, P: Provider<N>>(
638        &self,
639        provider: P,
640        tx_hash: B256,
641        receipt: Option<String>,
642    ) -> Result<B256>
643    where
644        N::TransactionRequest: FoundryTransactionBuilder<N>,
645        N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
646    {
647        match receipt {
648            Some(receipt) => sh_println!("{receipt}")?,
649            None => self.print_tx_result(provider, tx_hash).await?,
650        }
651        Ok(tx_hash)
652    }
653
654    async fn resolve_and_print_fee_token<N: Network, P: Provider<N>>(
655        &self,
656        provider: &P,
657        tx: &mut N::TransactionRequest,
658    ) -> Result<()>
659    where
660        N::TransactionRequest: FoundryTransactionBuilder<N>,
661    {
662        let provider = self.fee_token.queries_provider().then_some(provider);
663        match self.fee_token {
664            FeeTokenMode::AsBuilt => maybe_print_fee_token(provider, tx.fee_token()).await,
665            FeeTokenMode::Resolve | FeeTokenMode::ResolveOffline => {
666                tempo::resolve_and_print_fee_token(provider, tx, None).await
667            }
668        }
669    }
670}
671
672/// Sends a transaction through `provider`, which signs it (a wallet-filled provider or an
673/// unlocked RPC account).
674pub(crate) async fn cast_send<N: Network, P: Provider<N>>(
675    provider: P,
676    mut tx: N::TransactionRequest,
677    opts: &SendOptions,
678) -> Result<B256>
679where
680    N::TransactionRequest: FoundryTransactionBuilder<N>,
681    N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
682{
683    opts.resolve_and_print_fee_token(&provider, &mut tx).await?;
684    let (tx_hash, receipt) = if opts.sync {
685        // JSON envelope not supported: N::ReceiptResponse is generic over Display but not
686        // Serialize; adding Serialize would ripple across all network-generic callers.
687        let (tx_hash, receipt) = CastTxSender::new(&provider).send_sync(tx).await?;
688        (tx_hash, Some(receipt))
689    } else {
690        (*CastTxSender::new(&provider).send(tx).await?.tx_hash(), None)
691    };
692    opts.print_send_result(provider, tx_hash, receipt).await
693}
694
695/// Sends a raw transaction using the RPC method selected by `sync`.
696pub(crate) async fn cast_send_raw<N: Network, P: Provider<N>>(
697    provider: &P,
698    raw_tx: &[u8],
699    sync: bool,
700) -> Result<(B256, Option<String>)>
701where
702    N::TransactionRequest: FoundryTransactionBuilder<N>,
703    N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
704{
705    if sync {
706        let (tx_hash, receipt) = CastTxSender::new(provider).send_raw_sync(raw_tx).await?;
707        Ok((tx_hash, Some(receipt)))
708    } else {
709        Ok((*provider.send_raw_transaction(raw_tx).await?.tx_hash(), None))
710    }
711}
712
713/// Signs a prepared transaction with a Tempo wallet and sends it as a raw transaction.
714pub(crate) async fn cast_send_with_tempo_wallet<N: Network, P: Provider<N>>(
715    provider: &P,
716    mut tx: N::TransactionRequest,
717    wallet: &TempoAccountsWallet,
718    opts: &SendOptions,
719) -> Result<B256>
720where
721    N::TransactionRequest: FoundryTransactionBuilder<N>,
722    N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
723{
724    opts.resolve_and_print_fee_token(provider, &mut tx).await?;
725    let raw_tx = tx.sign_with_tempo_wallet(wallet).await?;
726    let (tx_hash, receipt) = cast_send_raw(provider, &raw_tx, opts.sync).await?;
727    opts.print_send_result(provider, tx_hash, receipt).await
728}
729
730/// Signs a prepared transaction as a Tempo configurable account with its owners' approvals and
731/// sends it as a raw transaction.
732pub(crate) async fn cast_send_with_configurable_account<N: Network, P: Provider<N>>(
733    provider: &P,
734    mut tx: N::TransactionRequest,
735    account: &ConfigurableAccountSigner,
736    opts: &SendOptions,
737) -> Result<B256>
738where
739    N::TransactionRequest: FoundryTransactionBuilder<N>,
740    N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
741{
742    opts.resolve_and_print_fee_token(provider, &mut tx).await?;
743    let raw_tx = tx.sign_with_configurable_account(account).await?;
744    let (tx_hash, receipt) = cast_send_raw(provider, &raw_tx, opts.sync).await?;
745    opts.print_send_result(provider, tx_hash, receipt).await
746}
747
748/// Signs a prepared transaction with a Tempo wallet, obtains a remote fee-payer signature, and
749/// broadcasts the sponsored transaction through the original provider transport. The relay
750/// selects the fee token, so `opts` must not resolve one.
751pub(crate) async fn cast_send_with_tempo_wallet_via_sponsor<N: Network, P: Provider<N>>(
752    provider: &P,
753    mut tx: N::TransactionRequest,
754    wallet: &TempoAccountsWallet,
755    sponsor_url: &str,
756    opts: &SendOptions,
757) -> Result<B256>
758where
759    N::TransactionRequest: FoundryTransactionBuilder<N>,
760    N::ReceiptResponse: UIfmt + UIfmtReceiptExt,
761{
762    tx.set_fee_payer_signature(FEE_PAYER_SIGNATURE_MARKER);
763    let connector = tempo::sponsor_relay_connector(provider, sponsor_url)?;
764    let sponsor_provider =
765        AlloyProviderBuilder::<_, _, N>::default().connect_with(&connector).await?;
766    cast_send_with_tempo_wallet(&sponsor_provider, tx, wallet, opts).await
767}
768
769/// Validates that a sponsor URL uses https:// (localhost/127.0.0.1 may use http://).
770pub(crate) fn validate_sponsor_url(raw: &str) -> Result<()> {
771    let url = Url::parse(raw)
772        .map_err(|e| eyre::eyre!("--sponsor-url is not a valid URL ({raw}): {e}"))?;
773    match url.scheme() {
774        "https" => Ok(()),
775        "http" if matches!(url.host_str(), Some("localhost" | "127.0.0.1")) => Ok(()),
776        "http" => eyre::bail!(
777            "--sponsor-url must use https:// for non-local endpoints (got {raw}). \
778             The sponsor relay is a trusted third party; use an encrypted channel."
779        ),
780        _ => eyre::bail!(
781            "--sponsor-url must start with https:// (got {raw}). \
782             The sponsor relay is a trusted third party; use an encrypted channel."
783        ),
784    }
785}
786
787#[cfg(test)]
788mod tests {
789    use super::*;
790    use alloy_json_rpc::{RequestPacket, ResponsePacket};
791    use alloy_provider::mock::Asserter;
792    use alloy_rpc_client::RpcClient;
793    use alloy_rpc_types::TransactionRequest;
794    use alloy_transport::{TransportError, TransportFut, mock::MockTransport};
795    use foundry_wallets::utils::create_local_signer;
796    use std::{
797        sync::{Arc, Mutex},
798        task::{Context, Poll},
799    };
800    use tempo_alloy::rpc::TempoTransactionRequest;
801    use tower::Service;
802
803    #[derive(Clone)]
804    struct RecordingTransport {
805        inner: MockTransport,
806        methods: Arc<Mutex<Vec<String>>>,
807    }
808
809    impl Service<RequestPacket> for RecordingTransport {
810        type Response = ResponsePacket;
811        type Error = TransportError;
812        type Future = TransportFut<'static>;
813
814        fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
815            self.inner.poll_ready(cx)
816        }
817
818        fn call(&mut self, req: RequestPacket) -> Self::Future {
819            if let RequestPacket::Single(req) = &req {
820                self.methods.lock().unwrap().push(req.method().to_string());
821            }
822            self.inner.call(req)
823        }
824    }
825
826    #[test]
827    fn test_validate_sponsor_url() {
828        // accepted
829        assert!(validate_sponsor_url("https://sponsor.tempo.xyz/tp_abc").is_ok());
830        assert!(validate_sponsor_url("http://localhost:8545").is_ok());
831        assert!(validate_sponsor_url("http://127.0.0.1:8545").is_ok());
832
833        // rejected
834        assert!(validate_sponsor_url("http://sponsor.tempo.xyz").is_err());
835        assert!(validate_sponsor_url("not-a-url").is_err());
836        // bypass attempts that fooled the old starts_with check
837        assert!(validate_sponsor_url("http://localhost.evil.com").is_err());
838        assert!(validate_sponsor_url("http://127.0.0.1.evil.com").is_err());
839    }
840
841    #[tokio::test]
842    async fn tempo_wallet_sync_send_uses_sync_rpc_method() {
843        let asserter = Asserter::new();
844        let tx_hash = B256::repeat_byte(0x11);
845        asserter.push_success(&serde_json::json!({
846            "type": "0x76",
847            "status": "0x1",
848            "cumulativeGasUsed": "0x5208",
849            "logs": [],
850            "logsBloom": format!("0x{}", "00".repeat(256)),
851            "transactionHash": tx_hash,
852            "transactionIndex": "0x0",
853            "blockHash": B256::repeat_byte(0x22),
854            "blockNumber": "0x1",
855            "gasUsed": "0x5208",
856            "effectiveGasPrice": "0x1",
857            "from": Address::ZERO,
858            "to": Address::ZERO,
859            "contractAddress": null,
860            "feeToken": Address::repeat_byte(0x55),
861            "feePayer": Address::ZERO,
862        }));
863        let methods = Arc::new(Mutex::new(Vec::new()));
864        let transport =
865            RecordingTransport { inner: MockTransport::new(asserter), methods: methods.clone() };
866        let provider = AlloyProviderBuilder::new_with_network::<TempoNetwork>()
867            .connect_client(RpcClient::new(transport, true));
868        let root = Address::repeat_byte(0x33);
869        let access_key = create_local_signer(
870            "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d",
871        )
872        .unwrap();
873        let wallet =
874            TempoAccountsWallet::from_secp256k1(root, access_key, None).with_chain_id(4217);
875        let tx = TempoTransactionRequest {
876            inner: TransactionRequest {
877                to: Some(Address::repeat_byte(0x44).into()),
878                nonce: Some(0),
879                gas: Some(100_000),
880                max_fee_per_gas: Some(1),
881                max_priority_fee_per_gas: Some(1),
882                chain_id: Some(4217),
883                ..Default::default()
884            },
885            ..Default::default()
886        };
887
888        let opts = SendOptions {
889            cast_async: false,
890            sync: true,
891            confirmations: 1,
892            timeout: 1,
893            fee_token: FeeTokenMode::AsBuilt,
894        };
895        let actual_hash = cast_send_with_tempo_wallet(&provider, tx, &wallet, &opts).await.unwrap();
896
897        assert_eq!(actual_hash, tx_hash);
898        assert_eq!(methods.lock().unwrap().as_slice(), ["eth_sendRawTransactionSync"]);
899    }
900}