Skip to main content

forge/cmd/
create.rs

1use alloy_chains::Chain;
2use alloy_consensus::{SignableTransaction, Signed};
3use alloy_dyn_abi::{DynSolValue, JsonAbiExt};
4use alloy_json_abi::JsonAbi;
5use alloy_network::{Ethereum, EthereumWallet, Network, ReceiptResponse, TransactionBuilder};
6use alloy_primitives::{Address, Bytes, U256, hex};
7use alloy_provider::{
8    PendingTransactionBuilder, PendingTransactionError, Provider,
9    ProviderBuilder as AlloyProviderBuilder,
10};
11use alloy_signer::{Signature, Signer};
12use clap::{Parser, ValueHint};
13use eyre::{Context, ContextCompat, Result};
14use forge_verify::{RetryArgs, VerifierArgs, VerifyArgs, parse_etherscan_license_type};
15use foundry_cli::{
16    opts::{BuildOpts, EthereumOpts, EtherscanOpts, TransactionOpts},
17    utils::{
18        LoadConfig, ResolvedLane, apply_gas_estimate_multiplier, find_contract_artifacts,
19        maybe_print_resolved_lane, parse_constructor_args, read_constructor_args_file,
20        resolve_lane,
21    },
22};
23use foundry_common::{
24    FoundryTransactionBuilder, compile,
25    provider::{
26        ProviderBuilder,
27        fee::{estimate_eip1559_fees, resolve_broadcast_eip1559_fees},
28    },
29    retry::Retry,
30    shell,
31    tempo::{
32        configurable_account::ConfigurableAccountSigner, mark_sponsored_gas_estimation,
33        maybe_print_fee_token, resolve_and_set_fee_token,
34    },
35};
36use foundry_compilers::{
37    ArtifactId, artifacts::BytecodeObject, info::ContractInfo, utils::canonicalize,
38};
39use foundry_config::{
40    Config, Eip1559FeeEstimatePreset,
41    figment::{
42        self, Metadata, Profile,
43        value::{Dict, Map},
44    },
45    merge_impl_figment_convert,
46};
47use foundry_wallets::{BrowserWalletOpts, WalletSigner, wallet_browser::signer::BrowserSigner};
48use serde_json::json;
49use std::{borrow::Borrow, marker::PhantomData, path::PathBuf, sync::Arc, time::Duration};
50use tempo_alloy::{TempoNetwork, accounts::TempoAccountsWallet};
51
52merge_impl_figment_convert!(CreateArgs, build, eth);
53
54/// CLI arguments for `forge create`.
55#[derive(Clone, Debug, Parser)]
56#[command(mut_arg("auth", |arg| arg.hide(true)))]
57pub struct CreateArgs {
58    /// The contract identifier in the form `<path>:<contractname>`.
59    contract: ContractInfo,
60
61    /// The constructor arguments.
62    #[arg(
63        long,
64        num_args(1..),
65        conflicts_with = "constructor_args_path",
66        value_name = "ARGS",
67        allow_hyphen_values = true,
68    )]
69    constructor_args: Vec<String>,
70
71    /// The path to a file containing the constructor arguments.
72    #[arg(
73        long,
74        value_hint = ValueHint::FilePath,
75        value_name = "PATH",
76    )]
77    constructor_args_path: Option<PathBuf>,
78
79    /// Broadcast the transaction.
80    #[arg(long)]
81    pub broadcast: bool,
82
83    /// Verify contract after creation.
84    #[arg(long)]
85    verify: bool,
86
87    /// Send via `eth_sendTransaction` using the `--from` argument or `$ETH_FROM` as sender
88    #[arg(long, requires = "from")]
89    unlocked: bool,
90
91    /// Prints the standard json compiler input if `--verify` is provided.
92    ///
93    /// The standard json compiler input can be used to manually submit contract verification in
94    /// the browser.
95    #[arg(long, requires = "verify")]
96    show_standard_json_input: bool,
97
98    /// The Etherscan license type code or SPDX identifier to include with the verification
99    /// request.
100    ///
101    /// Accepts either an Etherscan numeric license code or a common SPDX identifier such as `MIT`.
102    /// This is only used for Etherscan-style verifiers when `--verify` is enabled.
103    #[arg(
104        long,
105        requires = "verify",
106        value_name = "LICENSE",
107        help_heading = "Verifier options",
108        value_parser = parse_etherscan_license_type,
109    )]
110    license_type: Option<String>,
111
112    /// Timeout to use for broadcasting transactions.
113    #[arg(long, env = "ETH_TIMEOUT")]
114    pub timeout: Option<u64>,
115
116    /// Relative percentage to multiply the gas estimate by.
117    #[arg(long, value_name = "PERCENT", help_heading = "Transaction options")]
118    gas_estimate_multiplier: Option<u64>,
119
120    #[command(flatten)]
121    build: BuildOpts,
122
123    #[command(flatten)]
124    tx: TransactionOpts,
125
126    #[command(flatten)]
127    eth: EthereumOpts,
128
129    #[command(flatten)]
130    pub verifier: VerifierArgs,
131
132    #[command(flatten)]
133    retry: RetryArgs,
134
135    /// Browser wallet options
136    #[command(flatten)]
137    browser: BrowserWalletOpts,
138}
139
140impl CreateArgs {
141    /// Executes the command to create a contract
142    pub async fn run(mut self) -> Result<()> {
143        if self.tx.tempo.sponsor_url.is_some() {
144            eyre::bail!(
145                "--sponsor-url is not supported by forge create; use --tempo.sponsor with \
146                 --tempo.sponsor-signer or --tempo.sponsor-sig"
147            );
148        }
149        // Tempo rejects keychain transactions whose first call is a CREATE.
150        eyre::ensure!(
151            self.tx.tempo.configurable_access_key.is_none(),
152            "--tempo.configurable-access-key cannot deploy: Tempo access keys cannot sign CREATE"
153        );
154
155        // Resolve chain early so we can dispatch to the correct network type.
156        let chain = if let Some(chain) = self.chain_id() {
157            chain
158        } else {
159            let config = self.load_config()?;
160            let provider = ProviderBuilder::<Ethereum>::from_config(&config)?.build()?;
161            let chain_id = provider.get_chain_id().await?;
162            let chain = Chain::from(chain_id);
163            self.eth.etherscan.chain = Some(chain);
164            chain
165        };
166        let mut wallet = self.eth.wallet.clone();
167        if !chain.is_tempo() && !self.tx.tempo.is_tempo() {
168            // Do not let a matching entry in the Tempo Accounts store change an ordinary Ethereum
169            // deployment into a Tempo transaction.
170            wallet.from = None;
171        }
172        let (mut signer, tempo_access_key) =
173            foundry_common::tempo::maybe_signer(&wallet, Some(chain.id())).await?;
174
175        // A configurable account sender deploys with its owners' approvals.
176        let is_tempo = tempo_access_key.is_some() || self.tx.tempo.is_tempo() || chain.is_tempo();
177        let configurable_account = if !is_tempo
178            || tempo_access_key.is_some()
179            || self.unlocked
180            || self.browser.browser
181            || (self.load_config()?.eth_rpc_curl
182                && !self.tx.tempo.has_configurable_account_options())
183        {
184            eyre::ensure!(
185                !self.tx.tempo.has_configurable_account_options(),
186                "Tempo configurable accounts need a Tempo network and an RPC, and cannot be \
187                 combined with --unlocked, --browser or an access key"
188            );
189            None
190        } else {
191            self.tx
192                .tempo
193                .configurable_account_signer(
194                    &self.load_config()?,
195                    &self.eth.wallet,
196                    &mut signer,
197                    "forge create needs the owner keys locally: pass the other owners with \
198                     --tempo.owner, or keep them in the Tempo Accounts store.",
199                )
200                .await?
201        };
202
203        // Never deploy from an account other than the one explicitly selected by the user. Unlocked
204        // and browser deployments do not use the resolved signer.
205        let deployer = signer
206            .as_ref()
207            .map(|signer| signer.address())
208            .or_else(|| tempo_access_key.as_ref().map(|ak| ak.account()));
209        if configurable_account.is_none()
210            && !self.unlocked
211            && !self.browser.browser
212            && let Some(from) = self.eth.wallet.from
213            && let Some(deployer) = deployer
214            && from != deployer
215        {
216            eyre::bail!(
217                "the sender specified via `--from`/`ETH_FROM` ({from}) does not match the \
218                 signer address ({deployer})"
219            );
220        }
221
222        if is_tempo {
223            self.run_generic::<TempoNetwork>(signer, tempo_access_key, configurable_account).await
224        } else {
225            self.run_generic::<Ethereum>(signer, None, None).await
226        }
227    }
228
229    async fn run_generic<N: Network>(
230        mut self,
231        pre_resolved_signer: Option<WalletSigner>,
232        access_key: Option<TempoAccountsWallet>,
233        configurable_account: Option<ConfigurableAccountSigner>,
234    ) -> Result<()>
235    where
236        N::TxEnvelope: From<Signed<N::UnsignedTx>>,
237        N::UnsignedTx: SignableTransaction<Signature>,
238        N::TransactionRequest: FoundryTransactionBuilder<N> + serde::Serialize,
239        N::ReceiptResponse: serde::Serialize,
240    {
241        let mut config = self.load_config()?;
242        let resolve_unknown_fee_token_symbol = !config.eth_rpc_curl;
243
244        // Install missing dependencies.
245        self.install_missing_dependencies(&mut config)?;
246
247        // Find Project & Compile
248        let project = config.project()?;
249
250        let target_path = if let Some(ref mut path) = self.contract.path {
251            canonicalize(project.root().join(path))?
252        } else {
253            project.find_contract_path(&self.contract.name)?
254        };
255
256        let compiler = compile::ProjectCompiler::new()
257            .allow_linked_libraries(config.allow_linked_libraries)
258            .external_compilers(&config)
259            .quiet(shell::is_json())
260            .target_files([target_path.clone()]);
261        let output = compiler.compile(&project)?;
262
263        let (abi, bin, id) = find_contract_artifacts(output, &target_path, &self.contract.name)?;
264
265        let bin = match bin.object {
266            BytecodeObject::Bytecode(_) => bin.object,
267            _ => {
268                let link_refs = bin
269                    .link_references
270                    .iter()
271                    .flat_map(|(path, names)| {
272                        names.keys().map(move |name| format!("\t{name}: {path}"))
273                    })
274                    .collect::<Vec<String>>()
275                    .join("\n");
276                eyre::bail!(
277                    "Dynamic linking not supported in `create` command - deploy the following library contracts first, then provide the address to link at compile time\n{}",
278                    link_refs
279                );
280            }
281        };
282
283        // Add arguments to constructor
284        let params = if let Some(constructor) = &abi.constructor {
285            let constructor_args =
286                self.constructor_args_path.clone().map(read_constructor_args_file).transpose()?;
287            parse_constructor_args(
288                constructor,
289                constructor_args.as_deref().unwrap_or(&self.constructor_args),
290            )?
291        } else {
292            if !self.constructor_args.is_empty() || self.constructor_args_path.is_some() {
293                sh_warn!(
294                    "`{}` has no constructor; ignoring provided constructor arguments",
295                    self.contract.name
296                )?;
297            }
298            vec![]
299        };
300
301        let provider = ProviderBuilder::<N>::from_config(&config)?.build()?;
302
303        // Inject access key ID into TempoOpts so it's set before gas estimation.
304        if let Some(ref ak) = access_key {
305            self.tx.tempo.key_id = Some(ak.key_id()?);
306        }
307
308        // Resolve `--tempo.lane <name>` against the lanes file (default
309        // `<root>/tempo.lanes.toml`) and populate `self.tx.tempo.nonce_key` from the lane.
310        // Must happen before `self.deploy(...)` so `TempoOpts::apply` picks up the nonce_key.
311        let resolved_lane = resolve_lane(&mut self.tx.tempo, &config.root)?;
312        let expires_at = self.tx.tempo.resolve_expires();
313
314        // Whether to broadcast the transaction or not
315        let dry_run = !self.broadcast;
316
317        // Launch browser signer if `--browser` flag is set
318        let browser = self.browser.run::<N>().await?;
319
320        if let Some(browser) = browser {
321            // Deploy with browser wallet
322            let deployer_address = browser.address();
323            self.deploy(
324                abi,
325                bin,
326                params,
327                provider,
328                deployer_address,
329                config.transaction_timeout,
330                id,
331                dry_run,
332                TempoSigner::None,
333                Some(browser),
334                resolved_lane,
335                expires_at,
336                resolve_unknown_fee_token_symbol,
337                config.eip1559_fee_estimate,
338            )
339            .await
340        } else if self.unlocked {
341            // Deploy with unlocked account
342            let sender = self.eth.wallet.from.expect("required");
343            self.deploy(
344                abi,
345                bin,
346                params,
347                provider,
348                sender,
349                config.transaction_timeout,
350                id,
351                dry_run,
352                TempoSigner::None,
353                None,
354                resolved_lane,
355                expires_at,
356                resolve_unknown_fee_token_symbol,
357                config.eip1559_fee_estimate,
358            )
359            .await
360        } else if let Some(account) = configurable_account {
361            let deployer_address = account.account();
362            self.deploy(
363                abi,
364                bin,
365                params,
366                provider,
367                deployer_address,
368                config.transaction_timeout,
369                id,
370                dry_run,
371                TempoSigner::ConfigurableAccount(account),
372                None,
373                resolved_lane,
374                expires_at,
375                resolve_unknown_fee_token_symbol,
376                config.eip1559_fee_estimate,
377            )
378            .await
379        } else if let Some(ak) = access_key {
380            let deployer_address = ak.account();
381            self.deploy(
382                abi,
383                bin,
384                params,
385                provider,
386                deployer_address,
387                config.transaction_timeout,
388                id,
389                dry_run,
390                TempoSigner::AccessKey(ak),
391                None,
392                resolved_lane,
393                expires_at,
394                resolve_unknown_fee_token_symbol,
395                config.eip1559_fee_estimate,
396            )
397            .await
398        } else {
399            // Deploy with signer
400            let signer = match pre_resolved_signer {
401                Some(s) => s,
402                None => self.eth.wallet.signer().await?,
403            };
404            let deployer = signer.address();
405            let provider = AlloyProviderBuilder::<_, _, N>::default()
406                .wallet(EthereumWallet::new(signer))
407                .connect_provider(provider);
408            self.deploy(
409                abi,
410                bin,
411                params,
412                provider,
413                deployer,
414                config.transaction_timeout,
415                id,
416                dry_run,
417                TempoSigner::None,
418                None,
419                resolved_lane,
420                expires_at,
421                resolve_unknown_fee_token_symbol,
422                config.eip1559_fee_estimate,
423            )
424            .await
425        }
426    }
427
428    /// Returns the resolved chain, if any.
429    const fn chain_id(&self) -> Option<Chain> {
430        self.eth.etherscan.chain
431    }
432
433    /// Ensures the verify command can be executed.
434    ///
435    /// This is supposed to check any things that might go wrong when preparing a verify request
436    /// before the contract is deployed. This should prevent situations where a contract is deployed
437    /// successfully, but we fail to prepare a verify request which would require manual
438    /// verification.
439    async fn verify_preflight_check(
440        &self,
441        constructor_args: Option<String>,
442        id: &ArtifactId,
443    ) -> Result<()> {
444        // NOTE: this does not represent the same `VerifyArgs` that would be sent after deployment,
445        // since we don't know the address yet.
446        let mut verify = VerifyArgs {
447            address: Default::default(),
448            contract: Some(self.contract.clone()),
449            compiler_version: Some(id.version.to_string()),
450            constructor_args,
451            constructor_args_path: None,
452            no_auto_detect: false,
453            use_solc: None,
454            num_of_optimizations: None,
455            etherscan: EtherscanOpts {
456                key: self.eth.etherscan.key.clone(),
457                chain: self.chain_id(),
458            },
459            rpc: Default::default(),
460            flatten: false,
461            force: false,
462            skip_is_verified_check: true,
463            watch: true,
464            print_submission_result_to_stdout: false,
465            retry: self.retry,
466            libraries: self.build.libraries.clone(),
467            root: None,
468            verifier: self.verifier.clone(),
469            via_ir: self.build.compiler.via_ir,
470            license_type: self.license_type.clone(),
471            evm_version: self.build.compiler.evm_version,
472            show_standard_json_input: self.show_standard_json_input,
473            guess_constructor_args: false,
474            compilation_profile: Some(id.profile.clone()),
475            language: None,
476            creation_transaction_hash: None,
477        };
478
479        // Check config for Etherscan API Keys to avoid preflight check failing if no
480        // ETHERSCAN_API_KEY value set.
481        let config = verify.load_config()?;
482        verify.etherscan.key = config
483            .get_etherscan_config_with_chain(self.chain_id())?
484            .map(|c| c.key)
485            .or_else(|| config.etherscan_api_key.clone());
486
487        let context = verify.resolve_context().await?;
488
489        verify.verification_provider()?.preflight_verify_check(verify.clone(), context).await?;
490
491        let api_key = verify.verifier.resolve_api_key(verify.etherscan.key.as_deref());
492        let chain = verify.etherscan.chain.context("chain ID not resolved")?;
493        verify
494            .verifier
495            .check_credentials(api_key, chain, &config)
496            .await
497            .wrap_err("Verification preflight check failed")?;
498
499        Ok(())
500    }
501
502    /// Deploys the contract
503    #[expect(clippy::too_many_arguments)]
504    async fn deploy<N: Network, P: Provider<N>>(
505        self,
506        abi: JsonAbi,
507        bin: BytecodeObject,
508        args: Vec<DynSolValue>,
509        provider: P,
510        deployer_address: Address,
511        timeout: u64,
512        id: ArtifactId,
513        dry_run: bool,
514        mut tempo_signer: TempoSigner,
515        browser_signer: Option<BrowserSigner<N>>,
516        resolved_lane: Option<ResolvedLane>,
517        expires_at: Option<u64>,
518        resolve_unknown_fee_token_symbol: bool,
519        eip1559_fee_estimate: Eip1559FeeEstimatePreset,
520    ) -> Result<()>
521    where
522        N::TransactionRequest: FoundryTransactionBuilder<N> + serde::Serialize,
523        N::ReceiptResponse: serde::Serialize,
524    {
525        let chain = self.chain_id().context("chain ID not resolved")?;
526
527        let bin = bin.into_bytes().unwrap_or_default();
528        if bin.is_empty() {
529            eyre::bail!("no bytecode found in bin object for {}", self.contract.name);
530        }
531
532        let provider = Arc::new(provider);
533        let factory =
534            DeploymentTxFactory::<N, _>::new(abi.clone(), bin.clone(), provider.clone(), timeout);
535
536        let is_args_empty = args.is_empty();
537        let mut deployer =
538            factory.deploy_tokens(args.clone()).context("failed to deploy contract").map_err(|e| {
539                if is_args_empty {
540                    e.wrap_err("no arguments provided for contract constructor; consider --constructor-args or --constructor-args-path")
541                } else {
542                    e
543                }
544            })?;
545        let is_legacy = self.tx.legacy || chain.is_legacy();
546
547        deployer.tx.set_from(deployer_address);
548        deployer.tx.set_chain_id(chain.id());
549        // `to` field must be set explicitly, cannot be None.
550        if deployer.tx.to().is_none() {
551            deployer.tx.set_create();
552        }
553
554        // Apply user-provided gas, fee, nonce, and Tempo options.
555        self.tx.apply::<N>(&mut deployer.tx, is_legacy);
556
557        // Convert only AA CREATE transactions into a call entry. Plain Tempo
558        // CREATE transactions remain Ethereum transactions, while AA requests
559        // (for example, an expiring nonce) require a non-empty `calls` list.
560        match &tempo_signer {
561            TempoSigner::AccessKey(_) if deployer.tx.nonce_key().is_none() => {
562                deployer.tx.set_nonce_key(U256::ZERO);
563            }
564            TempoSigner::ConfigurableAccount(account) => {
565                account.prepare_request::<N>(&mut deployer.tx);
566            }
567            _ => {}
568        }
569        if deployer.tx.is_tempo_aa() {
570            deployer.tx.convert_create_to_call();
571        }
572
573        // Fetch defaults from provider for values not specified by user.
574        if self.tx.nonce.is_none() && !self.tx.tempo.expiring_nonce {
575            deployer.tx.set_nonce(provider.get_transaction_count(deployer_address).await?);
576        }
577
578        maybe_print_resolved_lane(resolved_lane.as_ref(), deployer.tx.nonce().unwrap_or_default())?;
579
580        if let TempoSigner::AccessKey(wallet) = &tempo_signer {
581            tempo_signer = TempoSigner::AccessKey(
582                deployer.tx.prepare_with_tempo_wallet(provider.as_ref(), wallet).await?,
583            );
584        }
585
586        if is_legacy {
587            if self.tx.gas_price.is_none() {
588                deployer.tx.set_gas_price(provider.get_gas_price().await?);
589            }
590        } else {
591            if self.tx.gas_price.is_none() || self.tx.priority_gas_price.is_none() {
592                let estimate = estimate_eip1559_fees(&provider, eip1559_fee_estimate).await.wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?;
593
594                // Only honor the browser-suggested tip when the user has not pinned
595                // a priority fee; `resolve_broadcast_eip1559_fees` ignores a lower tip.
596                let browser_suggested_tip =
597                    if browser_signer.is_some() && self.tx.priority_gas_price.is_none() {
598                        provider.get_max_priority_fee_per_gas().await.ok()
599                    } else {
600                        None
601                    };
602
603                // User `--gas-price`/`--priority-gas-price` overrides are applied
604                // below only for unset fields; pass `None` to avoid double-applying.
605                let estimate =
606                    resolve_broadcast_eip1559_fees(estimate, None, None, browser_suggested_tip)?;
607
608                if self.tx.priority_gas_price.is_none() {
609                    deployer.tx.set_max_priority_fee_per_gas(estimate.max_priority_fee_per_gas);
610                }
611                if self.tx.gas_price.is_none() {
612                    deployer.tx.set_max_fee_per_gas(estimate.max_fee_per_gas);
613                }
614            }
615            if let (Some(max_fee), Some(priority)) =
616                (deployer.tx.max_fee_per_gas(), deployer.tx.max_priority_fee_per_gas())
617            {
618                eyre::ensure!(
619                    priority <= max_fee,
620                    "max priority fee per gas ({priority}) cannot exceed max fee per gas ({max_fee})"
621                );
622            }
623        }
624
625        // set access list if specified
626        if let Some(access_list) = match self.tx.access_list {
627            None => None,
628            Some(None) => Some(provider.create_access_list(&deployer.tx).await?.access_list),
629            Some(Some(ref access_list)) => Some(access_list.clone()),
630        } {
631            deployer.tx.set_access_list(access_list);
632        }
633
634        if self.tx.gas_limit.is_none() {
635            let mut request = if browser_signer.is_some() {
636                deployer.tx.browser_wallet_gas_estimation_request()
637            } else {
638                deployer.tx.clone()
639            };
640            if self.tx.tempo.is_sponsored() {
641                mark_sponsored_gas_estimation(&provider, &mut request).await;
642            }
643            let estimated = provider.estimate_gas(request).await?;
644            deployer.tx.set_gas_limit(apply_gas_estimate_multiplier(
645                estimated,
646                self.gas_estimate_multiplier,
647            )?);
648        }
649
650        // Before we actually deploy the contract we try check if the verify settings are valid
651        let mut constructor_args = None;
652        if self.verify {
653            if !args.is_empty() {
654                let encoded_args = abi
655                    .constructor()
656                    .ok_or_else(|| eyre::eyre!("could not find constructor"))?
657                    .abi_encode_input(&args)?;
658                constructor_args = Some(hex::encode(encoded_args));
659            }
660
661            self.verify_preflight_check(constructor_args.clone(), &id).await?;
662        }
663
664        if dry_run {
665            if shell::is_json() {
666                let output = json!({
667                    "contract": self.contract.name,
668                    "transaction": &deployer.tx,
669                    "abi":&abi
670                });
671                sh_println!("{}", serde_json::to_string_pretty(&output)?)?;
672            } else {
673                sh_warn!("Dry run enabled, not broadcasting transaction\n")?;
674
675                sh_println!("Contract: {}", self.contract.name)?;
676                sh_println!(
677                    "Transaction: {}",
678                    serde_json::to_string_pretty(&deployer.tx.clone())?
679                )?;
680                sh_println!("ABI: {}\n", serde_json::to_string_pretty(&abi)?)?;
681
682                sh_warn!(
683                    "To broadcast this transaction, add --broadcast to the previous command. See forge create --help for more."
684                )?;
685            }
686
687            return Ok(());
688        }
689
690        if let Some(ts) = expires_at {
691            sh_status!("Transaction expires at unix timestamp {ts}")?;
692        }
693
694        let tempo_sponsor = self.tx.tempo.sponsor_config().await?;
695        if let Some(sponsor) = &tempo_sponsor {
696            sponsor
697                .resolve_and_set_fee_token(
698                    resolve_unknown_fee_token_symbol.then_some(&provider),
699                    &mut deployer.tx,
700                )
701                .await?;
702            sponsor.attach_and_print::<N>(&mut deployer.tx, deployer_address).await?;
703        } else {
704            let fee_token = resolve_and_set_fee_token(
705                resolve_unknown_fee_token_symbol.then_some(&provider),
706                &mut deployer.tx,
707                Some(deployer_address),
708            )
709            .await?;
710            maybe_print_fee_token(resolve_unknown_fee_token_symbol.then_some(&provider), fee_token)
711                .await?;
712        }
713
714        // Deploy the actual contract
715        let (deployed_contract, receipt) = if let Some(browser) = browser_signer {
716            // Browser wallet signs and sends the transaction
717            let tx_hash = browser.send_transaction_via_browser(deployer.tx).await?;
718            wait_for_deployment(PendingTransactionBuilder::new(provider.root().clone(), tx_hash))
719                .await?
720        } else if let Some(raw_tx) = match &tempo_signer {
721            TempoSigner::AccessKey(wallet) => {
722                Some(deployer.tx.clone().sign_with_tempo_wallet(wallet).await?)
723            }
724            TempoSigner::ConfigurableAccount(account) => {
725                Some(deployer.tx.clone().sign_with_configurable_account(account).await?)
726            }
727            TempoSigner::None => None,
728        } {
729            let pending = provider
730                .send_raw_transaction(&raw_tx)
731                .await?
732                .with_required_confirmations(1)
733                .with_timeout(Some(Duration::from_secs(timeout)));
734            wait_for_deployment(pending).await?
735        } else {
736            deployer.send_with_receipt().await?
737        };
738
739        let address = deployed_contract;
740        let tx_hash = receipt.transaction_hash();
741        if shell::is_json() {
742            let output = json!({
743                "deployer": deployer_address.to_string(),
744                "deployedTo": address.to_string(),
745                "transactionHash": tx_hash
746            });
747            sh_println!("{}", serde_json::to_string_pretty(&output)?)?;
748        } else {
749            sh_println!("Deployer: {deployer_address}")?;
750            sh_println!("Deployed to: {address}")?;
751            sh_println!("Transaction hash: {tx_hash:?}")?;
752        };
753
754        if !self.verify {
755            return Ok(());
756        }
757
758        sh_status!("Starting contract verification...")?;
759
760        let num_of_optimizations = if let Some(optimizer) = self.build.compiler.optimize {
761            optimizer.then(|| self.build.compiler.optimizer_runs.unwrap_or(200))
762        } else {
763            self.build.compiler.optimizer_runs
764        };
765
766        let verify = VerifyArgs {
767            address,
768            contract: Some(self.contract),
769            compiler_version: Some(id.version.to_string()),
770            constructor_args,
771            constructor_args_path: None,
772            no_auto_detect: false,
773            use_solc: None,
774            num_of_optimizations,
775            etherscan: EtherscanOpts { key: self.eth.etherscan.key(), chain: Some(chain) },
776            rpc: Default::default(),
777            flatten: false,
778            force: false,
779            skip_is_verified_check: true,
780            watch: true,
781            print_submission_result_to_stdout: false,
782            retry: self.retry,
783            libraries: self.build.libraries.clone(),
784            root: None,
785            verifier: self.verifier,
786            via_ir: self.build.compiler.via_ir,
787            license_type: self.license_type,
788            evm_version: self.build.compiler.evm_version,
789            show_standard_json_input: self.show_standard_json_input,
790            guess_constructor_args: false,
791            compilation_profile: Some(id.profile.clone()),
792            language: None,
793            creation_transaction_hash: Some(tx_hash),
794        };
795        // Load the full config (including foundry.toml) so the key used for resolution matches
796        // what `verify.run()` will actually use, preventing a "Waiting for sourcify..." message
797        // when the run will actually use Etherscan (or vice versa for unknown chains).
798        let verify_config = verify.load_config()?;
799        let effective_key = verify_config
800            .get_etherscan_config_with_chain(Some(chain))?
801            .map(|c| c.key)
802            .or_else(|| verify_config.etherscan_api_key.clone());
803        let resolved_verifier = verify.verifier.resolve(effective_key.as_deref(), Some(chain));
804        sh_status!("Waiting for {resolved_verifier} to detect contract deployment...")?;
805        verify.run().await
806    }
807}
808
809impl figment::Provider for CreateArgs {
810    fn metadata(&self) -> Metadata {
811        Metadata::named("Create Args Provider")
812    }
813
814    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
815        let mut dict = Dict::default();
816        if let Some(timeout) = self.timeout {
817            dict.insert("transaction_timeout".to_string(), timeout.into());
818        }
819        Ok(Map::from([(Config::selected_profile(), dict)]))
820    }
821}
822
823/// Helper which manages the deployment transaction of a smart contract. It
824/// wraps a deployment transaction, and retrieves the contract address output
825/// by it.
826#[derive(Debug)]
827#[must_use = "ContractDeploymentTx does nothing unless you `send` it"]
828pub struct ContractDeploymentTx<N: Network, P, C> {
829    /// the actual deployer, exposed for overriding the defaults
830    pub deployer: Deployer<N, P>,
831    /// marker for the `Contract` type to create afterwards
832    ///
833    /// this type will be used to construct it via `From::from(Contract)`
834    _contract: PhantomData<C>,
835}
836
837impl<N: Network, P: Clone, C> Clone for ContractDeploymentTx<N, P, C> {
838    fn clone(&self) -> Self {
839        Self { deployer: self.deployer.clone(), _contract: self._contract }
840    }
841}
842
843impl<N: Network, P, C> From<Deployer<N, P>> for ContractDeploymentTx<N, P, C> {
844    fn from(deployer: Deployer<N, P>) -> Self {
845        Self { deployer, _contract: PhantomData }
846    }
847}
848
849/// Helper which manages the deployment transaction of a smart contract
850#[derive(Clone, Debug)]
851#[must_use = "Deployer does nothing unless you `send` it"]
852pub struct Deployer<N: Network, P> {
853    /// The deployer's transaction, exposed for overriding the defaults
854    pub tx: N::TransactionRequest,
855    client: P,
856    confs: usize,
857    timeout: u64,
858}
859
860impl<N: Network, P: Provider<N>> Deployer<N, P> {
861    /// Broadcasts the contract deployment transaction and after waiting for it to
862    /// be sufficiently confirmed (default: 1), it returns a tuple with the [`Address`] at the
863    /// deployed contract's address and the corresponding receipt.
864    pub async fn send_with_receipt(self) -> Result<(Address, N::ReceiptResponse)> {
865        let pending = self
866            .client
867            .borrow()
868            .send_transaction(self.tx)
869            .await?
870            .with_required_confirmations(self.confs as u64)
871            .with_timeout(Some(Duration::from_secs(self.timeout)));
872        wait_for_deployment(pending).await
873    }
874}
875
876/// How a Tempo deployment is signed, besides a wallet-filled provider or a browser wallet.
877enum TempoSigner {
878    None,
879    /// A Tempo access key.
880    AccessKey(TempoAccountsWallet),
881    /// A configurable account's local owners.
882    ConfigurableAccount(ConfigurableAccountSigner),
883}
884
885/// Waits for a deployment transaction's receipt and returns the deployed address with it.
886///
887/// A load-balanced RPC can report the transaction as mined before the node that serves
888/// `eth_getTransactionReceipt` has its receipt, which alloy reports as a null response. The
889/// deployment went through, so keep polling for the receipt instead of failing it.
890async fn wait_for_deployment<N: Network>(
891    pending: PendingTransactionBuilder<N>,
892) -> Result<(Address, N::ReceiptResponse)> {
893    let tx_hash = *pending.tx_hash();
894    let provider = pending.provider().clone();
895    let receipt = match pending.get_receipt().await {
896        Err(PendingTransactionError::TransportError(err)) if err.is_null_resp() => {
897            Retry::new(15, Duration::from_secs(1))
898                .run_async(|| async {
899                    provider
900                        .get_transaction_receipt(tx_hash)
901                        .await?
902                        .wrap_err("the RPC has no receipt for the mined transaction yet")
903                })
904                .await
905        }
906        res => res.map_err(Into::into),
907    }
908    .wrap_err_with(|| {
909        format!("transaction {tx_hash} was sent, but waiting for its receipt failed")
910    })?;
911
912    eyre::ensure!(receipt.status(), "deployment transaction failed (receipt status 0): {tx_hash}");
913    let address = receipt.contract_address().wrap_err("contract was not deployed")?;
914    Ok((address, receipt))
915}
916
917/// To deploy a contract to the Ethereum network, a [`DeploymentTxFactory`] can be
918/// created which manages the Contract bytecode and Application Binary Interface
919/// (ABI), usually generated from the Solidity compiler.
920#[derive(Clone, Debug)]
921pub struct DeploymentTxFactory<N: Network, P> {
922    client: P,
923    abi: JsonAbi,
924    bytecode: Bytes,
925    timeout: u64,
926    _network: PhantomData<N>,
927}
928
929impl<N: Network, P: Provider<N> + Clone> DeploymentTxFactory<N, P> {
930    /// Creates a factory for deployment of the Contract with bytecode, and the
931    /// constructor defined in the abi. The client will be used to send any deployment
932    /// transaction.
933    pub const fn new(abi: JsonAbi, bytecode: Bytes, client: P, timeout: u64) -> Self {
934        Self { client, abi, bytecode, timeout, _network: PhantomData }
935    }
936
937    /// Create a deployment tx using the provided tokens as constructor
938    /// arguments
939    pub fn deploy_tokens(
940        self,
941        params: Vec<DynSolValue>,
942    ) -> Result<Deployer<N, P>, ContractDeploymentError>
943    where
944        N::TransactionRequest: FoundryTransactionBuilder<N>,
945    {
946        // Encode the constructor args & concatenate with the bytecode if necessary
947        let data: Bytes = match (self.abi.constructor(), params.is_empty()) {
948            (None, false) => return Err(ContractDeploymentError::ConstructorError),
949            (None, true) => self.bytecode.clone(),
950            (Some(constructor), _) => {
951                let input: Bytes = constructor
952                    .abi_encode_input(&params)
953                    .map_err(ContractDeploymentError::DetokenizationError)?
954                    .into();
955                // Concatenate the bytecode and abi-encoded constructor call.
956                self.bytecode.iter().copied().chain(input).collect()
957            }
958        };
959
960        // create the tx object. Since we're deploying a contract, `to` is `None`
961        let mut tx = N::TransactionRequest::default();
962        tx.set_input(data);
963        Ok(Deployer { client: self.client.clone(), tx, confs: 1, timeout: self.timeout })
964    }
965}
966
967#[derive(thiserror::Error, Debug)]
968/// An Error which is thrown when interacting with a smart contract
969pub enum ContractDeploymentError {
970    #[error("constructor is not defined in the ABI")]
971    ConstructorError,
972    #[error(transparent)]
973    DetokenizationError(#[from] alloy_dyn_abi::Error),
974}
975
976#[cfg(test)]
977mod tests {
978    use super::*;
979    use alloy_json_abi::Constructor;
980    use alloy_primitives::I256;
981    use foundry_cli::utils::parse_json;
982
983    #[test]
984    fn can_parse_create() {
985        let args: CreateArgs = CreateArgs::parse_from([
986            "foundry-cli",
987            "src/Domains.sol:Domains",
988            "--verify",
989            "--retries",
990            "10",
991            "--delay",
992            "30",
993            "--license-type",
994            "13",
995            "--gas-estimate-multiplier",
996            "125",
997        ]);
998        assert_eq!(args.retry.retries, 10);
999        assert_eq!(args.retry.delay, 30);
1000        assert_eq!(args.license_type.as_deref(), Some("13"));
1001        assert_eq!(args.gas_estimate_multiplier, Some(125));
1002    }
1003
1004    #[test]
1005    fn create_help_hides_auth() {
1006        let help = <CreateArgs as clap::CommandFactory>::command().render_long_help().to_string();
1007        assert!(!help.contains("--auth"));
1008    }
1009
1010    #[test]
1011    fn can_parse_create_license_type_spdx() {
1012        let args: CreateArgs = CreateArgs::parse_from([
1013            "foundry-cli",
1014            "src/Domains.sol:Domains",
1015            "--verify",
1016            "--license-type",
1017            "MIT",
1018        ]);
1019        assert_eq!(args.license_type.as_deref(), Some("3"));
1020    }
1021
1022    #[test]
1023    fn errors_on_invalid_create_license_type() {
1024        let err = CreateArgs::try_parse_from([
1025            "foundry-cli",
1026            "src/Domains.sol:Domains",
1027            "--verify",
1028            "--license-type",
1029            "definitely-not-a-license",
1030        ])
1031        .unwrap_err();
1032        assert!(err.to_string().contains("unsupported Etherscan license type"));
1033    }
1034
1035    #[test]
1036    fn can_parse_chain_id() {
1037        let args: CreateArgs = CreateArgs::parse_from([
1038            "foundry-cli",
1039            "src/Domains.sol:Domains",
1040            "--verify",
1041            "--retries",
1042            "10",
1043            "--delay",
1044            "30",
1045            "--chain-id",
1046            "9999",
1047        ]);
1048        assert_eq!(args.chain_id().map(|c| c.id()), Some(9999));
1049    }
1050
1051    #[test]
1052    fn test_parse_constructor_args() {
1053        let args: CreateArgs = CreateArgs::parse_from([
1054            "foundry-cli",
1055            "src/Domains.sol:Domains",
1056            "--constructor-args",
1057            "Hello",
1058        ]);
1059        let constructor: Constructor = parse_json(r#"{"type":"constructor","inputs":[{"name":"_name","type":"string","internalType":"string"}],"stateMutability":"nonpayable"}"#).unwrap();
1060        let params = parse_constructor_args(&constructor, &args.constructor_args).unwrap();
1061        assert_eq!(params, vec![DynSolValue::String("Hello".to_string())]);
1062    }
1063
1064    #[test]
1065    fn test_parse_tuple_constructor_args() {
1066        let args: CreateArgs = CreateArgs::parse_from([
1067            "foundry-cli",
1068            "src/Domains.sol:Domains",
1069            "--constructor-args",
1070            "[(1,2), (2,3), (3,4)]",
1071        ]);
1072        let constructor: Constructor = parse_json(r#"{"type":"constructor","inputs":[{"name":"_points","type":"tuple[]","internalType":"struct Point[]","components":[{"name":"x","type":"uint256","internalType":"uint256"},{"name":"y","type":"uint256","internalType":"uint256"}]}],"stateMutability":"nonpayable"}"#).unwrap();
1073        let _params = parse_constructor_args(&constructor, &args.constructor_args).unwrap();
1074    }
1075
1076    #[test]
1077    fn test_parse_int_constructor_args() {
1078        let args: CreateArgs = CreateArgs::parse_from([
1079            "foundry-cli",
1080            "src/Domains.sol:Domains",
1081            "--constructor-args",
1082            "-5",
1083        ]);
1084        let constructor: Constructor = parse_json(r#"{"type":"constructor","inputs":[{"name":"_name","type":"int256","internalType":"int256"}],"stateMutability":"nonpayable"}"#).unwrap();
1085        let params = parse_constructor_args(&constructor, &args.constructor_args).unwrap();
1086        assert_eq!(params, vec![DynSolValue::Int(I256::unchecked_from(-5), 256)]);
1087    }
1088}