Skip to main content

cast/cmd/
mktx.rs

1use super::{
2    auth::{confirm_and_build, confirm_and_build_with_tempo_wallet},
3    wallet::configurable_account,
4};
5use crate::{
6    tempo,
7    tx::{self, CastTxBuilder},
8};
9use alloy_consensus::{SignableTransaction, Signed};
10use alloy_eips::Encodable2718;
11use alloy_ens::NameOrAddress;
12use alloy_network::{Ethereum, EthereumWallet, Network, NetworkTransactionBuilder};
13use alloy_primitives::{Address, U256, hex};
14use alloy_provider::Provider;
15use alloy_signer::{Signature, Signer};
16use clap::Parser;
17use eyre::Result;
18use foundry_cli::{
19    json::{print_json_success, print_scalar},
20    opts::{EthereumOpts, TransactionOpts},
21    utils::{LoadConfig, resolve_lane},
22};
23use foundry_common::{FoundryTransactionBuilder, provider::ProviderBuilder, shell};
24use foundry_wallets::WalletSigner;
25use serde_json::json;
26use std::{path::PathBuf, str::FromStr};
27use tempo_alloy::{TempoNetwork, accounts::TempoAccountsWallet};
28use tempo_primitives::transaction::configurable_account_digest;
29
30#[cfg(feature = "base")]
31use base_common_network::Base;
32
33/// CLI arguments for `cast mktx`.
34#[derive(Debug, Parser)]
35pub struct MakeTxArgs {
36    /// The destination of the transaction.
37    ///
38    /// If not provided, you must use `cast mktx --create`.
39    #[arg(value_parser = NameOrAddress::from_str)]
40    to: Option<NameOrAddress>,
41
42    /// The signature of the function to call.
43    sig: Option<String>,
44
45    /// The arguments of the function to call.
46    #[arg(allow_negative_numbers = true)]
47    args: Vec<String>,
48
49    #[command(subcommand)]
50    command: Option<MakeTxSubcommands>,
51
52    #[command(flatten)]
53    tx: TransactionOpts,
54
55    /// Skip the EIP-7702 authorization disclosure confirmation.
56    #[arg(long)]
57    force: bool,
58
59    /// The path of blob data to be sent.
60    #[arg(
61        long,
62        value_name = "BLOB_DATA_PATH",
63        conflicts_with = "legacy",
64        requires = "blob",
65        help_heading = "Transaction options"
66    )]
67    path: Option<PathBuf>,
68
69    #[command(flatten)]
70    eth: EthereumOpts,
71
72    /// Generate a raw RLP-encoded unsigned transaction.
73    ///
74    /// Relaxes the wallet requirement.
75    #[arg(long)]
76    raw_unsigned: bool,
77
78    /// Also print the digest that the owners of the Tempo configurable account `--from` sign.
79    ///
80    /// Prints the unsigned transaction and the digest, separated by a tab. Each owner signs the
81    /// digest with `cast wallet sign --no-hash <DIGEST>` (or a passkey in a browser), and
82    /// `cast wallet assemble` combines the signatures into the signed transaction.
83    ///
84    /// Gas estimation models the largest owner quorum the account accepts (at most eight
85    /// approvals), each a maximum-size WebAuthn signature. An account that is not registered yet
86    /// needs `--gas-limit`, since only its owners know its configuration.
87    #[arg(long = "tempo.digest", requires_all = ["raw_unsigned", "from"])]
88    tempo_digest: bool,
89
90    /// Call `eth_signTransaction` using the `--from` argument or $ETH_FROM as sender
91    #[arg(long, requires = "from", conflicts_with = "raw_unsigned")]
92    ethsign: bool,
93
94    /// Generate a raw signed transaction using the provided 65-byte signature.
95    #[arg(
96        long,
97        value_name = "SIGNATURE",
98        requires = "from",
99        conflicts_with_all = ["raw_unsigned", "ethsign"]
100    )]
101    signature: Option<Signature>,
102}
103
104#[derive(Debug, Parser)]
105pub enum MakeTxSubcommands {
106    /// Use to deploy raw contract bytecode.
107    #[command(name = "--create")]
108    Create {
109        /// The initialization bytecode of the contract to deploy.
110        code: String,
111
112        /// The signature of the constructor.
113        sig: Option<String>,
114
115        /// The constructor arguments.
116        #[arg(allow_negative_numbers = true)]
117        args: Vec<String>,
118    },
119}
120
121impl MakeTxArgs {
122    pub async fn run(self) -> Result<()> {
123        if self.tx.tempo.sponsor_url.is_some() {
124            eyre::bail!(
125                "--sponsor-url is not supported by cast mktx; use --tempo.sponsor with \
126                 --tempo.sponsor-signer or --tempo.sponsor-sig"
127            );
128        }
129        // Tempo rejects keychain transactions whose first call is a CREATE.
130        eyre::ensure!(
131            self.tx.tempo.configurable_access_key.is_none()
132                || !matches!(self.command, Some(MakeTxSubcommands::Create { .. })),
133            "--tempo.configurable-access-key cannot deploy: Tempo access keys cannot sign CREATE"
134        );
135
136        let (network, signer, access_key) =
137            tempo::resolve_transaction_network_and_signer(&self.tx.tempo, &self.eth).await?;
138        eyre::ensure!(
139            !self.tempo_digest || network.is_tempo(),
140            "--tempo.digest requires a Tempo network"
141        );
142        // `cast wallet assemble` cannot rebuild a sponsored transaction from its signing encoding,
143        // which omits the sponsor signature.
144        eyre::ensure!(
145            !self.tempo_digest || !self.tx.tempo.has_sponsor_submission(),
146            "--tempo.digest does not support sponsored transactions"
147        );
148        if network.is_tempo() {
149            return self.run_generic::<TempoNetwork>(signer, access_key).await;
150        }
151
152        #[cfg(feature = "base")]
153        if network.is_base() {
154            super::validate_base_transaction_options(&self.tx)?;
155            return self.run_generic::<Base>(signer, None).await;
156        }
157
158        self.run_generic::<Ethereum>(signer, None).await
159    }
160
161    async fn run_generic<N: Network>(
162        self,
163        pre_resolved_signer: Option<WalletSigner>,
164        pre_resolved_access_key: Option<TempoAccountsWallet>,
165    ) -> Result<()>
166    where
167        N::TxEnvelope: From<Signed<N::UnsignedTx>>,
168        N::UnsignedTx: SignableTransaction<Signature>,
169        N::TransactionRequest: FoundryTransactionBuilder<N>,
170    {
171        let Self {
172            to,
173            mut sig,
174            mut args,
175            command,
176            mut tx,
177            force,
178            path,
179            eth,
180            raw_unsigned,
181            tempo_digest,
182            ethsign,
183            signature,
184        } = self;
185        let has_session = tx.tempo.session_id()?.is_some();
186
187        let print_sponsor_hash = tx.tempo.print_sponsor_hash;
188        let sponsor_fee_payer = tx.tempo.sponsor;
189        let expires_at = tx.tempo.resolve_expires();
190        let tempo_sponsor =
191            if print_sponsor_hash { None } else { tx.tempo.sponsor_config().await? };
192
193        let blob_data = path.map(std::fs::read).transpose()?;
194
195        let code = if let Some(MakeTxSubcommands::Create {
196            code,
197            sig: constructor_sig,
198            args: constructor_args,
199        }) = command
200        {
201            sig = constructor_sig;
202            args = constructor_args;
203            Some(code)
204        } else {
205            None
206        };
207
208        let config = eth.load_config()?;
209        let provider = ProviderBuilder::<N>::from_config(&config)?.build()?;
210        // The provider is not consulted for fee tokens in `--curl` mode.
211        let fee_provider = (!config.eth_rpc_curl).then_some(&provider);
212
213        // Populate `tx.tempo.nonce_key` from `--tempo.lane` before the options are cloned into
214        // the builder.
215        let resolved_lane = resolve_lane(&mut tx.tempo, &config.root)?;
216        let lane = resolved_lane.as_ref();
217
218        let mut tx_builder = CastTxBuilder::new(&provider, tx.clone(), &config)
219            .await?
220            .with_to(to)
221            .await?
222            .with_code_sig_and_args(code, sig, args)
223            .await?
224            .with_blob_data(blob_data)?;
225        let chain = tx_builder.chain();
226        let (mut signer, access_key) = if has_session || pre_resolved_access_key.is_some() {
227            tempo::resolve_session_or_wallet_signer(&tx.tempo, &eth.wallet, chain.id()).await?
228        } else {
229            (pre_resolved_signer, None)
230        };
231        // A configurable account sender is signed by its local owners. Unsigned and externally
232        // signed transactions take the sender as given, and `--tempo.digest` resolves its owner
233        // quorum.
234        let configurable_account = if access_key.is_some()
235            || raw_unsigned
236            || ethsign
237            || signature.is_some()
238        {
239            // Only local owners can sign the keychain signature of a configurable access key.
240            eyre::ensure!(
241                tx.tempo.configurable_access_key.is_none(),
242                "--tempo.configurable-access-key cannot be combined with --raw-unsigned, \
243                 --ethsign, --signature or a Tempo access key"
244            );
245            None
246        } else {
247            tempo::resolve_configurable_account::<N>(&tx.tempo, &config, &eth.wallet, &mut signer)
248                .await?
249        };
250        if let Some(account) = &configurable_account {
251            account.prepare_request::<N>(tx_builder.tx_mut());
252        }
253
254        // If --tempo.print-sponsor-hash was passed, build the tx, print the hash, and exit.
255        if print_sponsor_hash {
256            // Resolve the actual sender because the sponsor hash commits to it. Tempo access-key
257            // transactions must also be prepared before hashing so a pending authorization is
258            // included in the digest.
259            let (mut tx, from) = if let Some(access_key) = access_key {
260                let Some((tx, prepared)) =
261                    confirm_and_build_with_tempo_wallet(tx_builder, &access_key, force, None)
262                        .await?
263                else {
264                    return Ok(());
265                };
266                (tx, prepared.account())
267            } else if let Some(account) = &configurable_account {
268                let Some(tx) =
269                    confirm_and_build(tx_builder, account.sender(), force, None, false).await?
270                else {
271                    return Ok(());
272                };
273                (tx, account.sender())
274            } else {
275                let signer = match signer {
276                    Some(signer) => signer,
277                    None => eth.wallet.signer().await?,
278                };
279                let Some(tx) = confirm_and_build(tx_builder, &signer, force, None, false).await?
280                else {
281                    return Ok(());
282                };
283                (tx, signer.address())
284            };
285            let hash = tempo::sponsor_hash(fee_provider, &mut tx, from, sponsor_fee_payer).await?;
286            return print_scalar(format!("{hash:?}"));
287        }
288
289        tempo::print_expires(expires_at)?;
290
291        if raw_unsigned {
292            // Without a sender the nonce cannot be fetched.
293            // See: <https://github.com/foundry-rs/foundry/issues/11110>
294            if eth.wallet.from.is_none() && tx.nonce.is_none() {
295                eyre::bail!(
296                    "Missing required parameters for raw unsigned transaction. When --from is not provided, you must specify: --nonce"
297                );
298            }
299            if tempo_sponsor.is_some() && eth.wallet.from.is_none() {
300                eyre::bail!(
301                    "--tempo.sponsor requires --from for --raw-unsigned because the sponsor digest commits to the sender"
302                );
303            }
304
305            // Use zero address as placeholder for unsigned transactions
306            let from = eth.wallet.from.unwrap_or(Address::ZERO);
307            let digest_version = if tempo_digest {
308                let (version, spec) =
309                    configurable_account::digest_context(&eth, from, tx.gas_limit.is_some())
310                        .await?;
311                // A `0x05` signature only signs Tempo transactions.
312                if tx_builder.tx_mut().nonce_key().is_none() {
313                    tx_builder.tx_mut().set_nonce_key(U256::ZERO);
314                }
315                if let Some(spec) = spec {
316                    tx_builder.tx_mut().set_configurable_account_simulation(spec);
317                }
318                Some(version)
319            } else {
320                None
321            };
322            let Some(mut tx) = confirm_and_build(tx_builder, from, force, lane, false).await?
323            else {
324                return Ok(());
325            };
326            tempo::apply_fee_payment::<N, _>(tempo_sponsor.as_ref(), fee_provider, &mut tx, from)
327                .await?;
328            let unsigned = tx.build_unsigned()?;
329            let raw = hex::encode_prefixed(unsigned.encoded_for_signing());
330            let Some(version) = digest_version else { return print_scalar(raw) };
331            let digest = configurable_account_digest(unsigned.signature_hash(), from, version);
332            if shell::is_json() {
333                return print_json_success(json!({
334                    "unsigned_tx": raw,
335                    "digest": digest,
336                    "account": from,
337                    "version": version,
338                }));
339            }
340            sh_status!("Owner digest: {digest}")?;
341            sh_status!(
342                "Each owner signs it with `cast wallet sign --no-hash {digest}`, adding `--p256` \
343                 for a raw P-256 owner"
344            )?;
345            sh_println!("{raw}\t{digest}")?;
346            return Ok(());
347        }
348
349        if let Some(signature) = signature {
350            let signature = signature.normalized_s();
351            let from = eth.wallet.from.expect("required by clap");
352            let Some(mut tx) = confirm_and_build(tx_builder, from, force, lane, false).await?
353            else {
354                return Ok(());
355            };
356            tempo::apply_fee_payment::<N, _>(tempo_sponsor.as_ref(), fee_provider, &mut tx, from)
357                .await?;
358
359            let tx = tx.build_unsigned()?;
360            let recovered = signature.recover_address_from_prehash(&tx.signature_hash())?;
361            if recovered != from {
362                eyre::bail!(
363                    "The provided signature recovers to {recovered}, which does not match the specified sender {from}"
364                );
365            }
366
367            let tx = N::TxEnvelope::from(tx.into_signed(signature));
368            return print_scalar(hex::encode_prefixed(tx.encoded_2718()));
369        }
370
371        if ethsign {
372            // Use "eth_signTransaction" to sign the transaction only works if the node/RPC has
373            // unlocked accounts.
374            let Some(mut tx) =
375                confirm_and_build(tx_builder, config.sender, force, lane, true).await?
376            else {
377                return Ok(());
378            };
379            tempo::apply_fee_payment::<N, _>(
380                tempo_sponsor.as_ref(),
381                fee_provider,
382                &mut tx,
383                config.sender,
384            )
385            .await?;
386            return print_scalar(provider.sign_transaction(tx).await?);
387        }
388
389        // Default to using the local signer.
390        let signed_tx = if let Some(access_key) = access_key {
391            let Some((mut tx, prepared)) =
392                confirm_and_build_with_tempo_wallet(tx_builder, &access_key, force, lane).await?
393            else {
394                return Ok(());
395            };
396            tempo::apply_fee_payment::<N, _>(
397                tempo_sponsor.as_ref(),
398                fee_provider,
399                &mut tx,
400                prepared.account(),
401            )
402            .await?;
403            tx.sign_with_tempo_wallet(&prepared).await?
404        } else if let Some(account) = &configurable_account {
405            let from = account.sender();
406            let Some(mut tx) = confirm_and_build(tx_builder, from, force, lane, false).await?
407            else {
408                return Ok(());
409            };
410            tempo::apply_fee_payment::<N, _>(tempo_sponsor.as_ref(), fee_provider, &mut tx, from)
411                .await?;
412            tx.sign_with_configurable_account(account).await?
413        } else {
414            let (signer, from) = tx::resolve_send_signer(signer, &eth).await?;
415            let Some(mut tx) = confirm_and_build(tx_builder, &signer, force, lane, false).await?
416            else {
417                return Ok(());
418            };
419            tempo::apply_fee_payment::<N, _>(tempo_sponsor.as_ref(), fee_provider, &mut tx, from)
420                .await?;
421            tx.build(&EthereumWallet::new(signer)).await?.encoded_2718()
422        };
423
424        print_scalar(hex::encode_prefixed(signed_tx))
425    }
426}