forge/cmd/
create.rs

1use crate::cmd::install;
2use alloy_chains::Chain;
3use alloy_dyn_abi::{DynSolValue, JsonAbiExt, Specifier};
4use alloy_json_abi::{Constructor, JsonAbi};
5use alloy_network::{AnyNetwork, AnyTransactionReceipt, EthereumWallet, TransactionBuilder};
6use alloy_primitives::{hex, Address, Bytes};
7use alloy_provider::{PendingTransactionError, Provider, ProviderBuilder};
8use alloy_rpc_types::TransactionRequest;
9use alloy_serde::WithOtherFields;
10use alloy_signer::Signer;
11use alloy_transport::TransportError;
12use clap::{Parser, ValueHint};
13use eyre::{Context, Result};
14use forge_verify::{RetryArgs, VerifierArgs, VerifyArgs};
15use foundry_cli::{
16    opts::{BuildOpts, EthereumOpts, EtherscanOpts, TransactionOpts},
17    utils::{self, read_constructor_args_file, remove_contract, LoadConfig},
18};
19use foundry_common::{
20    compile::{self},
21    fmt::parse_tokens,
22    shell,
23};
24use foundry_compilers::{
25    artifacts::BytecodeObject, info::ContractInfo, utils::canonicalize, ArtifactId,
26};
27use foundry_config::{
28    figment::{
29        self,
30        value::{Dict, Map},
31        Metadata, Profile,
32    },
33    merge_impl_figment_convert, Config,
34};
35use serde_json::json;
36use std::{borrow::Borrow, marker::PhantomData, path::PathBuf, sync::Arc, time::Duration};
37
38merge_impl_figment_convert!(CreateArgs, build, eth);
39
40/// CLI arguments for `forge create`.
41#[derive(Clone, Debug, Parser)]
42pub struct CreateArgs {
43    /// The contract identifier in the form `<path>:<contractname>`.
44    contract: ContractInfo,
45
46    /// The constructor arguments.
47    #[arg(
48        long,
49        num_args(1..),
50        conflicts_with = "constructor_args_path",
51        value_name = "ARGS",
52        allow_hyphen_values = true,
53    )]
54    constructor_args: Vec<String>,
55
56    /// The path to a file containing the constructor arguments.
57    #[arg(
58        long,
59        value_hint = ValueHint::FilePath,
60        value_name = "PATH",
61    )]
62    constructor_args_path: Option<PathBuf>,
63
64    /// Broadcast the transaction.
65    #[arg(long)]
66    pub broadcast: bool,
67
68    /// Verify contract after creation.
69    #[arg(long)]
70    verify: bool,
71
72    /// Send via `eth_sendTransaction` using the `--from` argument or `$ETH_FROM` as sender
73    #[arg(long, requires = "from")]
74    unlocked: bool,
75
76    /// Prints the standard json compiler input if `--verify` is provided.
77    ///
78    /// The standard json compiler input can be used to manually submit contract verification in
79    /// the browser.
80    #[arg(long, requires = "verify")]
81    show_standard_json_input: bool,
82
83    /// Timeout to use for broadcasting transactions.
84    #[arg(long, env = "ETH_TIMEOUT")]
85    pub timeout: Option<u64>,
86
87    #[command(flatten)]
88    build: BuildOpts,
89
90    #[command(flatten)]
91    tx: TransactionOpts,
92
93    #[command(flatten)]
94    eth: EthereumOpts,
95
96    #[command(flatten)]
97    pub verifier: VerifierArgs,
98
99    #[command(flatten)]
100    retry: RetryArgs,
101}
102
103impl CreateArgs {
104    /// Executes the command to create a contract
105    pub async fn run(mut self) -> Result<()> {
106        let mut config = self.load_config()?;
107
108        // Install missing dependencies.
109        if install::install_missing_dependencies(&mut config) && config.auto_detect_remappings {
110            // need to re-configure here to also catch additional remappings
111            config = self.load_config()?;
112        }
113
114        // Find Project & Compile
115        let project = config.project()?;
116
117        let target_path = if let Some(ref mut path) = self.contract.path {
118            canonicalize(project.root().join(path))?
119        } else {
120            project.find_contract_path(&self.contract.name)?
121        };
122
123        let output = compile::compile_target(&target_path, &project, shell::is_json())?;
124
125        let (abi, bin, id) = remove_contract(output, &target_path, &self.contract.name)?;
126
127        let bin = match bin.object {
128            BytecodeObject::Bytecode(_) => bin.object,
129            _ => {
130                let link_refs = bin
131                    .link_references
132                    .iter()
133                    .flat_map(|(path, names)| {
134                        names.keys().map(move |name| format!("\t{name}: {path}"))
135                    })
136                    .collect::<Vec<String>>()
137                    .join("\n");
138                eyre::bail!("Dynamic linking not supported in `create` command - deploy the following library contracts first, then provide the address to link at compile time\n{}", link_refs)
139            }
140        };
141
142        // Add arguments to constructor
143        let params = if let Some(constructor) = &abi.constructor {
144            let constructor_args =
145                self.constructor_args_path.clone().map(read_constructor_args_file).transpose()?;
146            self.parse_constructor_args(
147                constructor,
148                constructor_args.as_deref().unwrap_or(&self.constructor_args),
149            )?
150        } else {
151            vec![]
152        };
153
154        let provider = utils::get_provider(&config)?;
155
156        // respect chain, if set explicitly via cmd args
157        let chain_id = if let Some(chain_id) = self.chain_id() {
158            chain_id
159        } else {
160            provider.get_chain_id().await?
161        };
162
163        // Whether to broadcast the transaction or not
164        let dry_run = !self.broadcast;
165
166        if self.unlocked {
167            // Deploy with unlocked account
168            let sender = self.eth.wallet.from.expect("required");
169            self.deploy(
170                abi,
171                bin,
172                params,
173                provider,
174                chain_id,
175                sender,
176                config.transaction_timeout,
177                id,
178                dry_run,
179            )
180            .await
181        } else {
182            // Deploy with signer
183            let signer = self.eth.wallet.signer().await?;
184            let deployer = signer.address();
185            let provider = ProviderBuilder::<_, _, AnyNetwork>::default()
186                .wallet(EthereumWallet::new(signer))
187                .on_provider(provider);
188            self.deploy(
189                abi,
190                bin,
191                params,
192                provider,
193                chain_id,
194                deployer,
195                config.transaction_timeout,
196                id,
197                dry_run,
198            )
199            .await
200        }
201    }
202
203    /// Returns the provided chain id, if any.
204    fn chain_id(&self) -> Option<u64> {
205        self.eth.etherscan.chain.map(|chain| chain.id())
206    }
207
208    /// Ensures the verify command can be executed.
209    ///
210    /// This is supposed to check any things that might go wrong when preparing a verify request
211    /// before the contract is deployed. This should prevent situations where a contract is deployed
212    /// successfully, but we fail to prepare a verify request which would require manual
213    /// verification.
214    async fn verify_preflight_check(
215        &self,
216        constructor_args: Option<String>,
217        chain: u64,
218        id: &ArtifactId,
219    ) -> Result<()> {
220        // NOTE: this does not represent the same `VerifyArgs` that would be sent after deployment,
221        // since we don't know the address yet.
222        let mut verify = VerifyArgs {
223            address: Default::default(),
224            contract: Some(self.contract.clone()),
225            compiler_version: Some(id.version.to_string()),
226            constructor_args,
227            constructor_args_path: None,
228            num_of_optimizations: None,
229            etherscan: EtherscanOpts {
230                key: self.eth.etherscan.key.clone(),
231                chain: Some(chain.into()),
232            },
233            rpc: Default::default(),
234            flatten: false,
235            force: false,
236            skip_is_verified_check: true,
237            watch: true,
238            retry: self.retry,
239            libraries: self.build.libraries.clone(),
240            root: None,
241            verifier: self.verifier.clone(),
242            via_ir: self.build.via_ir,
243            evm_version: self.build.compiler.evm_version,
244            show_standard_json_input: self.show_standard_json_input,
245            guess_constructor_args: false,
246            compilation_profile: Some(id.profile.to_string()),
247        };
248
249        // Check config for Etherscan API Keys to avoid preflight check failing if no
250        // ETHERSCAN_API_KEY value set.
251        let config = verify.load_config()?;
252        verify.etherscan.key =
253            config.get_etherscan_config_with_chain(Some(chain.into()))?.map(|c| c.key);
254
255        let context = verify.resolve_context().await?;
256
257        verify.verification_provider()?.preflight_verify_check(verify, context).await?;
258        Ok(())
259    }
260
261    /// Deploys the contract
262    #[expect(clippy::too_many_arguments)]
263    async fn deploy<P: Provider<AnyNetwork>>(
264        self,
265        abi: JsonAbi,
266        bin: BytecodeObject,
267        args: Vec<DynSolValue>,
268        provider: P,
269        chain: u64,
270        deployer_address: Address,
271        timeout: u64,
272        id: ArtifactId,
273        dry_run: bool,
274    ) -> Result<()> {
275        let bin = bin.into_bytes().unwrap_or_default();
276        if bin.is_empty() {
277            eyre::bail!("no bytecode found in bin object for {}", self.contract.name)
278        }
279
280        let provider = Arc::new(provider);
281        let factory = ContractFactory::new(abi.clone(), bin.clone(), provider.clone(), timeout);
282
283        let is_args_empty = args.is_empty();
284        let mut deployer =
285            factory.deploy_tokens(args.clone()).context("failed to deploy contract").map_err(|e| {
286                if is_args_empty {
287                    e.wrap_err("no arguments provided for contract constructor; consider --constructor-args or --constructor-args-path")
288                } else {
289                    e
290                }
291            })?;
292        let is_legacy = self.tx.legacy || Chain::from(chain).is_legacy();
293
294        deployer.tx.set_from(deployer_address);
295        deployer.tx.set_chain_id(chain);
296        // `to` field must be set explicitly, cannot be None.
297        if deployer.tx.to.is_none() {
298            deployer.tx.set_create();
299        }
300        deployer.tx.set_nonce(if let Some(nonce) = self.tx.nonce {
301            Ok(nonce.to())
302        } else {
303            provider.get_transaction_count(deployer_address).await
304        }?);
305
306        // set tx value if specified
307        if let Some(value) = self.tx.value {
308            deployer.tx.set_value(value);
309        }
310
311        deployer.tx.set_gas_limit(if let Some(gas_limit) = self.tx.gas_limit {
312            Ok(gas_limit.to())
313        } else {
314            provider.estimate_gas(deployer.tx.clone()).await
315        }?);
316
317        if is_legacy {
318            let gas_price = if let Some(gas_price) = self.tx.gas_price {
319                gas_price.to()
320            } else {
321                provider.get_gas_price().await?
322            };
323            deployer.tx.set_gas_price(gas_price);
324        } else {
325            let estimate = provider.estimate_eip1559_fees().await.wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?;
326            let priority_fee = if let Some(priority_fee) = self.tx.priority_gas_price {
327                priority_fee.to()
328            } else {
329                estimate.max_priority_fee_per_gas
330            };
331            let max_fee = if let Some(max_fee) = self.tx.gas_price {
332                max_fee.to()
333            } else {
334                estimate.max_fee_per_gas
335            };
336
337            deployer.tx.set_max_fee_per_gas(max_fee);
338            deployer.tx.set_max_priority_fee_per_gas(priority_fee);
339        }
340
341        // Before we actually deploy the contract we try check if the verify settings are valid
342        let mut constructor_args = None;
343        if self.verify {
344            if !args.is_empty() {
345                let encoded_args = abi
346                    .constructor()
347                    .ok_or_else(|| eyre::eyre!("could not find constructor"))?
348                    .abi_encode_input(&args)?;
349                constructor_args = Some(hex::encode(encoded_args));
350            }
351
352            self.verify_preflight_check(constructor_args.clone(), chain, &id).await?;
353        }
354
355        if dry_run {
356            if !shell::is_json() {
357                sh_warn!("Dry run enabled, not broadcasting transaction\n")?;
358
359                sh_println!("Contract: {}", self.contract.name)?;
360                sh_println!(
361                    "Transaction: {}",
362                    serde_json::to_string_pretty(&deployer.tx.clone())?
363                )?;
364                sh_println!("ABI: {}\n", serde_json::to_string_pretty(&abi)?)?;
365
366                sh_warn!("To broadcast this transaction, add --broadcast to the previous command. See forge create --help for more.")?;
367            } else {
368                let output = json!({
369                    "contract": self.contract.name,
370                    "transaction": &deployer.tx,
371                    "abi":&abi
372                });
373                sh_println!("{}", serde_json::to_string_pretty(&output)?)?;
374            }
375
376            return Ok(());
377        }
378
379        // Deploy the actual contract
380        let (deployed_contract, receipt) = deployer.send_with_receipt().await?;
381
382        let address = deployed_contract;
383        if shell::is_json() {
384            let output = json!({
385                "deployer": deployer_address.to_string(),
386                "deployedTo": address.to_string(),
387                "transactionHash": receipt.transaction_hash
388            });
389            sh_println!("{}", serde_json::to_string_pretty(&output)?)?;
390        } else {
391            sh_println!("Deployer: {deployer_address}")?;
392            sh_println!("Deployed to: {address}")?;
393            sh_println!("Transaction hash: {:?}", receipt.transaction_hash)?;
394        };
395
396        if !self.verify {
397            return Ok(());
398        }
399
400        sh_println!("Starting contract verification...")?;
401
402        let num_of_optimizations = if let Some(optimizer) = self.build.compiler.optimize {
403            if optimizer {
404                Some(self.build.compiler.optimizer_runs.unwrap_or(200))
405            } else {
406                None
407            }
408        } else {
409            self.build.compiler.optimizer_runs
410        };
411
412        let verify = VerifyArgs {
413            address,
414            contract: Some(self.contract),
415            compiler_version: Some(id.version.to_string()),
416            constructor_args,
417            constructor_args_path: None,
418            num_of_optimizations,
419            etherscan: EtherscanOpts { key: self.eth.etherscan.key(), chain: Some(chain.into()) },
420            rpc: Default::default(),
421            flatten: false,
422            force: false,
423            skip_is_verified_check: true,
424            watch: true,
425            retry: self.retry,
426            libraries: self.build.libraries.clone(),
427            root: None,
428            verifier: self.verifier,
429            via_ir: self.build.via_ir,
430            evm_version: self.build.compiler.evm_version,
431            show_standard_json_input: self.show_standard_json_input,
432            guess_constructor_args: false,
433            compilation_profile: Some(id.profile.to_string()),
434        };
435        sh_println!("Waiting for {} to detect contract deployment...", verify.verifier.verifier)?;
436        verify.run().await
437    }
438
439    /// Parses the given constructor arguments into a vector of `DynSolValue`s, by matching them
440    /// against the constructor's input params.
441    ///
442    /// Returns a list of parsed values that match the constructor's input params.
443    fn parse_constructor_args(
444        &self,
445        constructor: &Constructor,
446        constructor_args: &[String],
447    ) -> Result<Vec<DynSolValue>> {
448        let mut params = Vec::with_capacity(constructor.inputs.len());
449        for (input, arg) in constructor.inputs.iter().zip(constructor_args) {
450            // resolve the input type directly
451            let ty = input
452                .resolve()
453                .wrap_err_with(|| format!("Could not resolve constructor arg: input={input}"))?;
454            params.push((ty, arg));
455        }
456        let params = params.iter().map(|(ty, arg)| (ty, arg.as_str()));
457        parse_tokens(params).map_err(Into::into)
458    }
459}
460
461impl figment::Provider for CreateArgs {
462    fn metadata(&self) -> Metadata {
463        Metadata::named("Create Args Provider")
464    }
465
466    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
467        let mut dict = Dict::default();
468        if let Some(timeout) = self.timeout {
469            dict.insert("transaction_timeout".to_string(), timeout.into());
470        }
471        Ok(Map::from([(Config::selected_profile(), dict)]))
472    }
473}
474
475/// `ContractFactory` is a [`DeploymentTxFactory`] object with an
476/// [`Arc`] middleware. This type alias exists to preserve backwards
477/// compatibility with less-abstract Contracts.
478///
479/// For full usage docs, see [`DeploymentTxFactory`].
480pub type ContractFactory<P> = DeploymentTxFactory<P>;
481
482/// Helper which manages the deployment transaction of a smart contract. It
483/// wraps a deployment transaction, and retrieves the contract address output
484/// by it.
485#[derive(Debug)]
486#[must_use = "ContractDeploymentTx does nothing unless you `send` it"]
487pub struct ContractDeploymentTx<P, C> {
488    /// the actual deployer, exposed for overriding the defaults
489    pub deployer: Deployer<P>,
490    /// marker for the `Contract` type to create afterwards
491    ///
492    /// this type will be used to construct it via `From::from(Contract)`
493    _contract: PhantomData<C>,
494}
495
496impl<P: Clone, C> Clone for ContractDeploymentTx<P, C> {
497    fn clone(&self) -> Self {
498        Self { deployer: self.deployer.clone(), _contract: self._contract }
499    }
500}
501
502impl<P, C> From<Deployer<P>> for ContractDeploymentTx<P, C> {
503    fn from(deployer: Deployer<P>) -> Self {
504        Self { deployer, _contract: PhantomData }
505    }
506}
507
508/// Helper which manages the deployment transaction of a smart contract
509#[derive(Clone, Debug)]
510#[must_use = "Deployer does nothing unless you `send` it"]
511pub struct Deployer<P> {
512    /// The deployer's transaction, exposed for overriding the defaults
513    pub tx: WithOtherFields<TransactionRequest>,
514    client: P,
515    confs: usize,
516    timeout: u64,
517}
518
519impl<P: Provider<AnyNetwork>> Deployer<P> {
520    /// Broadcasts the contract deployment transaction and after waiting for it to
521    /// be sufficiently confirmed (default: 1), it returns a tuple with the [`Address`] at the
522    /// deployed contract's address and the corresponding [`AnyTransactionReceipt`].
523    pub async fn send_with_receipt(
524        self,
525    ) -> Result<(Address, AnyTransactionReceipt), ContractDeploymentError> {
526        let receipt = self
527            .client
528            .borrow()
529            .send_transaction(self.tx)
530            .await?
531            .with_required_confirmations(self.confs as u64)
532            .with_timeout(Some(Duration::from_secs(self.timeout)))
533            .get_receipt()
534            .await?;
535
536        let address =
537            receipt.contract_address.ok_or(ContractDeploymentError::ContractNotDeployed)?;
538
539        Ok((address, receipt))
540    }
541}
542
543/// To deploy a contract to the Ethereum network, a [`ContractFactory`] can be
544/// created which manages the Contract bytecode and Application Binary Interface
545/// (ABI), usually generated from the Solidity compiler.
546#[derive(Clone, Debug)]
547pub struct DeploymentTxFactory<P> {
548    client: P,
549    abi: JsonAbi,
550    bytecode: Bytes,
551    timeout: u64,
552}
553
554impl<P: Provider<AnyNetwork> + Clone> DeploymentTxFactory<P> {
555    /// Creates a factory for deployment of the Contract with bytecode, and the
556    /// constructor defined in the abi. The client will be used to send any deployment
557    /// transaction.
558    pub fn new(abi: JsonAbi, bytecode: Bytes, client: P, timeout: u64) -> Self {
559        Self { client, abi, bytecode, timeout }
560    }
561
562    /// Create a deployment tx using the provided tokens as constructor
563    /// arguments
564    pub fn deploy_tokens(
565        self,
566        params: Vec<DynSolValue>,
567    ) -> Result<Deployer<P>, ContractDeploymentError> {
568        // Encode the constructor args & concatenate with the bytecode if necessary
569        let data: Bytes = match (self.abi.constructor(), params.is_empty()) {
570            (None, false) => return Err(ContractDeploymentError::ConstructorError),
571            (None, true) => self.bytecode.clone(),
572            (Some(constructor), _) => {
573                let input: Bytes = constructor
574                    .abi_encode_input(&params)
575                    .map_err(ContractDeploymentError::DetokenizationError)?
576                    .into();
577                // Concatenate the bytecode and abi-encoded constructor call.
578                self.bytecode.iter().copied().chain(input).collect()
579            }
580        };
581
582        // create the tx object. Since we're deploying a contract, `to` is `None`
583        let tx = WithOtherFields::new(TransactionRequest::default().input(data.into()));
584
585        Ok(Deployer { client: self.client.clone(), tx, confs: 1, timeout: self.timeout })
586    }
587}
588
589#[derive(thiserror::Error, Debug)]
590/// An Error which is thrown when interacting with a smart contract
591pub enum ContractDeploymentError {
592    #[error("constructor is not defined in the ABI")]
593    ConstructorError,
594    #[error(transparent)]
595    DetokenizationError(#[from] alloy_dyn_abi::Error),
596    #[error("contract was not deployed")]
597    ContractNotDeployed,
598    #[error(transparent)]
599    RpcError(#[from] TransportError),
600}
601
602impl From<PendingTransactionError> for ContractDeploymentError {
603    fn from(_err: PendingTransactionError) -> Self {
604        Self::ContractNotDeployed
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611    use alloy_primitives::I256;
612
613    #[test]
614    fn can_parse_create() {
615        let args: CreateArgs = CreateArgs::parse_from([
616            "foundry-cli",
617            "src/Domains.sol:Domains",
618            "--verify",
619            "--retries",
620            "10",
621            "--delay",
622            "30",
623        ]);
624        assert_eq!(args.retry.retries, 10);
625        assert_eq!(args.retry.delay, 30);
626    }
627    #[test]
628    fn can_parse_chain_id() {
629        let args: CreateArgs = CreateArgs::parse_from([
630            "foundry-cli",
631            "src/Domains.sol:Domains",
632            "--verify",
633            "--retries",
634            "10",
635            "--delay",
636            "30",
637            "--chain-id",
638            "9999",
639        ]);
640        assert_eq!(args.chain_id(), Some(9999));
641    }
642
643    #[test]
644    fn test_parse_constructor_args() {
645        let args: CreateArgs = CreateArgs::parse_from([
646            "foundry-cli",
647            "src/Domains.sol:Domains",
648            "--constructor-args",
649            "Hello",
650        ]);
651        let constructor: Constructor = serde_json::from_str(r#"{"type":"constructor","inputs":[{"name":"_name","type":"string","internalType":"string"}],"stateMutability":"nonpayable"}"#).unwrap();
652        let params = args.parse_constructor_args(&constructor, &args.constructor_args).unwrap();
653        assert_eq!(params, vec![DynSolValue::String("Hello".to_string())]);
654    }
655
656    #[test]
657    fn test_parse_tuple_constructor_args() {
658        let args: CreateArgs = CreateArgs::parse_from([
659            "foundry-cli",
660            "src/Domains.sol:Domains",
661            "--constructor-args",
662            "[(1,2), (2,3), (3,4)]",
663        ]);
664        let constructor: Constructor = serde_json::from_str(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();
665        let _params = args.parse_constructor_args(&constructor, &args.constructor_args).unwrap();
666    }
667
668    #[test]
669    fn test_parse_int_constructor_args() {
670        let args: CreateArgs = CreateArgs::parse_from([
671            "foundry-cli",
672            "src/Domains.sol:Domains",
673            "--constructor-args",
674            "-5",
675        ]);
676        let constructor: Constructor = serde_json::from_str(r#"{"type":"constructor","inputs":[{"name":"_name","type":"int256","internalType":"int256"}],"stateMutability":"nonpayable"}"#).unwrap();
677        let params = args.parse_constructor_args(&constructor, &args.constructor_args).unwrap();
678        assert_eq!(params, vec![DynSolValue::Int(I256::unchecked_from(-5), 256)]);
679    }
680}