Skip to main content

cast/cmd/
create2.rs

1use alloy_dyn_abi::JsonAbiExt;
2use alloy_primitives::{Address, B256, U256, hex, hex::FromHex, keccak256};
3use clap::{Args, Parser, Subcommand};
4use eyre::{Result, WrapErr};
5use foundry_cli::{
6    json::print_scalar,
7    opts::BuildOpts,
8    utils::{LoadConfig, find_contract_artifacts, parse_constructor_args},
9};
10use foundry_common::{compile, shell};
11use foundry_compilers::{info::ContractInfo, utils::canonicalize};
12use rand::{RngCore, SeedableRng, rngs::StdRng};
13use regex::RegexSetBuilder;
14use std::time::Instant;
15
16// https://etherscan.io/address/0x4e59b44847b379578588920ca78fbf26c0b4956c#code
17const DEPLOYER: &str = "0x4e59b44847b379578588920ca78fbf26c0b4956c";
18const ADDRESS_HEX_LEN: usize = Address::len_bytes() * 2;
19
20#[derive(Clone, Debug, Subcommand)]
21enum Create2Subcommand {
22    /// Compute a contract's CREATE2 init code hash.
23    #[command(visible_alias = "initcodehash")]
24    InitCodeHash(InitCodeHashArgs),
25}
26
27foundry_config::impl_figment_convert!(InitCodeHashArgs, build);
28
29#[derive(Clone, Debug, Args)]
30struct InitCodeHashArgs {
31    /// The contract identifier in the form `<path>:<contractname>`.
32    contract: ContractInfo,
33
34    /// The constructor arguments.
35    #[arg(value_name = "ARGS", allow_negative_numbers = true)]
36    constructor_args: Vec<String>,
37
38    #[command(flatten)]
39    build: BuildOpts,
40}
41
42impl InitCodeHashArgs {
43    fn run(&self) -> Result<()> {
44        let config = self.load_config()?;
45        let project = config.project()?;
46        let target_path = if let Some(path) = &self.contract.path {
47            canonicalize(project.root().join(path))?
48        } else {
49            project.find_contract_path(&self.contract.name)?
50        };
51
52        let output = compile::compile_target(&target_path, &project, true)?;
53        let (abi, bin, _) = find_contract_artifacts(output, &target_path, &self.contract.name)?;
54        let Some(bytecode) = bin.object.into_bytes() else {
55            eyre::bail!("contract contains unlinked libraries");
56        };
57        if bytecode.is_empty() {
58            eyre::bail!("no bytecode found in bin object for {}", self.contract.name);
59        }
60
61        let mut init_code = bytecode.to_vec();
62        if let Some(constructor) = &abi.constructor {
63            let params = parse_constructor_args(constructor, &self.constructor_args)?;
64            init_code.extend(constructor.abi_encode_input(&params)?);
65        } else if !self.constructor_args.is_empty() {
66            eyre::bail!("contract does not have a constructor");
67        }
68
69        print_scalar(keccak256(init_code))?;
70        Ok(())
71    }
72}
73
74/// CLI arguments for `cast create2`.
75#[derive(Clone, Debug, Parser)]
76#[command(subcommand_negates_reqs = true, args_conflicts_with_subcommands = true)]
77pub struct Create2Args {
78    #[command(subcommand)]
79    command: Option<Create2Subcommand>,
80
81    /// Prefix for the contract address.
82    #[arg(
83        long,
84        short,
85        required_unless_present_any = &["ends_with", "matching", "salt"],
86        value_name = "HEX"
87    )]
88    starts_with: Option<String>,
89
90    /// Suffix for the contract address.
91    #[arg(long, short, value_name = "HEX")]
92    ends_with: Option<String>,
93
94    /// Sequence that the address has to match.
95    #[arg(long, short, value_name = "HEX")]
96    matching: Option<String>,
97
98    /// Case sensitive matching.
99    #[arg(short, long)]
100    case_sensitive: bool,
101
102    /// Address of the contract deployer.
103    #[arg(
104        short,
105        long,
106        default_value = DEPLOYER,
107        value_name = "ADDRESS"
108    )]
109    deployer: Address,
110
111    /// Salt to be used for the contract deployment. This option separate from the default salt
112    /// mining with filters.
113    #[arg(
114        long,
115        conflicts_with_all = [
116            "starts_with",
117            "ends_with",
118            "matching",
119            "case_sensitive",
120            "caller",
121            "seed",
122            "no_random"
123        ],
124        value_name = "HEX"
125    )]
126    salt: Option<String>,
127
128    /// Init code of the contract to be deployed.
129    #[arg(short, long, value_name = "HEX")]
130    init_code: Option<String>,
131
132    /// Init code hash of the contract to be deployed.
133    #[arg(alias = "ch", long, value_name = "HASH", required_unless_present = "init_code")]
134    init_code_hash: Option<String>,
135
136    /// Number of threads to use. Specifying 0 defaults to the number of logical cores.
137    #[arg(global = true, long, short = 'j', visible_alias = "jobs")]
138    threads: Option<usize>,
139
140    /// Address of the caller. Used for the first 20 bytes of the salt.
141    #[arg(long, value_name = "ADDRESS")]
142    caller: Option<Address>,
143
144    /// The random number generator's seed, used to initialize the salt.
145    #[arg(long, value_name = "HEX")]
146    seed: Option<B256>,
147
148    /// Don't initialize the salt with a random value, and instead use the default value of 0.
149    #[arg(long, conflicts_with = "seed")]
150    no_random: bool,
151}
152
153impl Create2Args {
154    pub fn execute(self) -> Result<()> {
155        if let Some(Create2Subcommand::InitCodeHash(args)) = &self.command {
156            return args.run();
157        }
158        self.run().map(drop)
159    }
160
161    /// Mines (or derives) the salt and returns the resulting address and salt.
162    fn run(self) -> Result<(Address, B256)> {
163        let Self {
164            command: _,
165            starts_with,
166            ends_with,
167            matching,
168            case_sensitive,
169            deployer,
170            salt,
171            init_code,
172            init_code_hash,
173            threads,
174            caller,
175            seed,
176            no_random,
177        } = self;
178
179        let init_code_hash = match (init_code_hash, init_code) {
180            (Some(init_code_hash), _) => B256::from_hex(init_code_hash)?,
181            // Clap requires one of the two.
182            (None, init_code) => keccak256(hex::decode(init_code.unwrap_or_default())?),
183        };
184
185        if let Some(salt) = salt {
186            let salt = B256::from_hex(salt)?;
187            let address = deployer.create2(salt, init_code_hash);
188            sh_println!("{address}\t{salt}")?;
189            return Ok((address, salt));
190        }
191
192        let mut regexs = vec![];
193
194        if let Some(matches) = matching {
195            if starts_with.is_some() || ends_with.is_some() {
196                eyre::bail!("Either use --matching or --starts/ends-with");
197            }
198
199            let matches = matches.trim_start_matches("0x");
200
201            if matches.len() != ADDRESS_HEX_LEN {
202                eyre::bail!("Please provide a 40 characters long sequence for matching");
203            }
204
205            hex::decode(matches.replace('X', "0")).wrap_err("invalid matching hex provided")?;
206            // replacing X placeholders by . to match any character at these positions
207
208            regexs.push(matches.replace('X', "."));
209        }
210
211        if let Some(prefix) = starts_with {
212            regexs.push(format!(
213                r"^{}",
214                get_regex_hex_string(prefix).wrap_err("invalid prefix hex provided")?
215            ));
216        }
217        if let Some(suffix) = ends_with {
218            regexs.push(format!(
219                r"{}$",
220                get_regex_hex_string(suffix).wrap_err("invalid suffix hex provided")?
221            ))
222        }
223
224        debug_assert!(
225            regexs.iter().map(|p| p.len() - 1).sum::<usize>() <= ADDRESS_HEX_LEN,
226            "vanity patterns length exceeded. cannot be more than 40 characters",
227        );
228
229        let regex = RegexSetBuilder::new(regexs).case_insensitive(!case_sensitive).build()?;
230
231        // Validation and diagnostic patterns stay shared with checksum-sensitive mining.
232        // Compile each pattern into only the address bytes that constrain a nibble.
233        let byte_patterns = regex
234            .patterns()
235            .iter()
236            .map(|pattern| BytePattern::new(pattern))
237            .collect::<Option<Vec<_>>>();
238
239        let mut n_threads = match threads {
240            Some(n) if n != 0 => n,
241            _ => std::thread::available_parallelism().map_or(1, |n| n.get()),
242        };
243        if cfg!(test) {
244            n_threads = n_threads.min(2);
245        }
246
247        let mut salt = B256::ZERO;
248        let remaining = if let Some(caller_address) = caller {
249            salt[..Address::len_bytes()].copy_from_slice(caller_address.as_slice());
250            &mut salt[Address::len_bytes()..]
251        } else {
252            &mut salt[..]
253        };
254
255        if !no_random {
256            let mut rng = match seed {
257                Some(seed) => StdRng::from_seed(seed.0),
258                None => StdRng::from_os_rng(),
259            };
260            rng.fill_bytes(remaining);
261        }
262
263        sh_status!("Configuration:")?;
264        sh_status!("Init code hash: {init_code_hash}")?;
265        sh_status!("Regex patterns: {:?}\n", regex.patterns())?;
266        sh_status!(
267            "Starting to generate deterministic contract address with {n_threads} threads..."
268        )?;
269        let timer = Instant::now();
270        let mut checksum_buf = case_sensitive.then(|| Address::ZERO.to_checksum_buffer(None));
271        let (address, salt) = super::miner::mine_salt(salt, n_threads, move |salt| {
272            #[expect(clippy::needless_borrows_for_generic_args)]
273            let addr = deployer.create2(&salt, &init_code_hash);
274            let matches = if let Some(buffer) = &mut checksum_buf {
275                let s = buffer.format(&addr, None);
276                regex.matches(&s["0x".len()..]).matched_all()
277            } else {
278                byte_patterns
279                    .as_ref()
280                    .is_some_and(|patterns| patterns.iter().all(|pattern| pattern.matches(&addr)))
281            };
282            matches.then_some((addr, salt))
283        })
284        .ok_or_else(|| eyre::eyre!("create2 salt mining failed: all threads panicked"))?;
285        sh_status!("Successfully found contract address in {:?}", timer.elapsed())?;
286        sh_status!("Address: {address}")?;
287        sh_status!("Salt: {salt} ({})", Into::<U256>::into(salt))?;
288        // The machine-readable stdout record duplicates the prose above when stdout is an
289        // interactive terminal.
290        if !shell::is_out_tty() {
291            sh_println!("{address}\t{salt}")?;
292        }
293
294        Ok((address, salt))
295    }
296}
297
298fn get_regex_hex_string(s: String) -> Result<String> {
299    let s = s.strip_prefix("0x").unwrap_or(&s);
300    let pad_width = s.len() + s.len() % 2;
301    hex::decode(format!("{s:0<pad_width$}"))?;
302    Ok(s.to_string())
303}
304
305/// Byte constraints for a validated prefix, suffix, or full-address wildcard pattern.
306#[derive(Clone)]
307struct BytePattern(Vec<(usize, u8, u8)>);
308
309impl BytePattern {
310    fn new(pattern: &str) -> Option<Self> {
311        let suffix = pattern.ends_with('$');
312        let pattern = pattern.trim_start_matches('^').trim_end_matches('$');
313        // An overlong pattern cannot match a 40-nibble address.
314        if pattern.len() > ADDRESS_HEX_LEN {
315            return None;
316        }
317        let offset = if suffix { ADDRESS_HEX_LEN - pattern.len() } else { 0 };
318        let mut bytes = [(0u8, 0u8); Address::len_bytes()];
319        for (i, nibble) in pattern.chars().enumerate() {
320            if nibble != '.' {
321                // The hex decoder also accepts an uppercase 0X prefix, but the
322                // regex retains its X, which cannot match an address hex digit.
323                let value = nibble.to_digit(16)? as u8;
324                let i = offset + i;
325                let shift = if i.is_multiple_of(2) { 4 } else { 0 };
326                let (mask, expected) = &mut bytes[i / 2];
327                *mask |= 0xf << shift;
328                *expected |= value << shift;
329            }
330        }
331        Some(Self(
332            bytes
333                .into_iter()
334                .enumerate()
335                .filter_map(|(i, (mask, value))| (mask != 0).then_some((i, mask, value)))
336                .collect::<Vec<_>>(),
337        ))
338    }
339
340    fn matches(&self, address: &Address) -> bool {
341        self.0.iter().all(|&(i, mask, value)| address[i] & mask == value)
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use alloy_primitives::{address, b256};
349    use std::str::FromStr;
350
351    const ZERO_HASH: &str =
352        "--init-code-hash=0x0000000000000000000000000000000000000000000000000000000000000000";
353
354    fn run(args: &[&str]) -> Result<(Address, B256)> {
355        Create2Args::parse_from(["foundry-cli"].iter().chain(args)).run()
356    }
357
358    #[test]
359    fn basic_create2() {
360        for (flag, pattern) in [
361            ("--starts-with", "aa"),
362            ("--ends-with", "bb"),
363            ("--starts-with", "aaa"),
364            ("--ends-with", "bbb"),
365            ("--starts-with", "0xaa"),
366            ("--starts-with", "0xaaa"),
367        ] {
368            let (address, _) = run(&[ZERO_HASH, flag, pattern]).unwrap();
369            let address = format!("{address:x}");
370            let pattern = pattern.trim_start_matches("0x");
371            assert!(
372                if flag == "--starts-with" {
373                    address.starts_with(pattern)
374                } else {
375                    address.ends_with(pattern)
376                },
377                "{flag} {pattern}: {address}"
378            );
379        }
380
381        // Non-hex and misplaced prefixes are rejected.
382        assert!(run(&[ZERO_HASH, "--starts-with", "0xerr"]).is_err());
383        assert!(run(&[ZERO_HASH, "--starts-with", "x00"]).is_err());
384    }
385
386    #[test]
387    fn matches_pattern() {
388        let (address, _) =
389            run(&[ZERO_HASH, "--matching=0xbbXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"]).unwrap();
390        assert!(format!("{address:x}").starts_with("bb"));
391    }
392
393    #[test]
394    fn create2_salt() {
395        let (address, _) = run(&[
396            "--deployer=0x8ba1f109551bD432803012645Ac136ddd64DBA72",
397            "--salt=0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331",
398            "--init-code=0x6394198df16000526103ff60206004601c335afa6040516060f3",
399        ])
400        .unwrap();
401        assert_eq!(address, address!("0x533AE9D683B10C02EBDB05471642F85230071FC3"));
402    }
403
404    #[test]
405    fn create2_init_code() {
406        let init_code = "00";
407        let (address, salt) = run(&["--starts-with=cc", "--init-code", init_code]).unwrap();
408        assert!(format!("{address:x}").starts_with("cc"));
409        let deployer = Address::from_str(DEPLOYER).unwrap();
410        assert_eq!(address, deployer.create2_from_code(salt, hex::decode(init_code).unwrap()));
411    }
412
413    #[test]
414    fn create2_init_code_hash() {
415        let init_code_hash = "bc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a";
416        let (address, salt) =
417            run(&["--starts-with=dd", "--init-code-hash", init_code_hash]).unwrap();
418        assert!(format!("{address:x}").starts_with("dd"));
419        let deployer = Address::from_str(DEPLOYER).unwrap();
420        assert_eq!(address, deployer.create2(salt, B256::from_str(init_code_hash).unwrap()));
421    }
422
423    #[test]
424    fn create2_caller() {
425        let (address, salt) = run(&[
426            "--starts-with=dd",
427            "--init-code-hash=bc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a",
428            "--caller=0x66f9664f97F2b50F62D13eA064982f936dE76657",
429        ])
430        .unwrap();
431        assert!(format!("{address:x}").starts_with("dd"));
432        assert!(format!("{salt:x}").starts_with("66f9664f97f2b50f62d13ea064982f936de76657"));
433    }
434
435    #[test]
436    fn deterministic_seed() {
437        let (address, salt) = run(&[
438            "--starts-with=0x00",
439            "--init-code-hash=0x479d7e8f31234e208d704ba1a123c76385cea8a6981fd675b784fbd9cffb918d",
440            "--seed=0x479d7e8f31234e208d704ba1a123c76385cea8a6981fd675b784fbd9cffb918d",
441            "-j1",
442        ])
443        .unwrap();
444        assert_eq!(address, address!("0x00614b3D65ac4a09A376a264fE1aE5E5E12A6C43"));
445        assert_eq!(
446            salt,
447            b256!("0x322113f523203e2c0eb00bbc8e69208b0eb0c8dad0eaac7b01d64ff016edb40d")
448        );
449    }
450
451    #[test]
452    fn deterministic_output() {
453        let (address, salt) = run(&[
454            "--starts-with=0x00",
455            "--init-code-hash=0x479d7e8f31234e208d704ba1a123c76385cea8a6981fd675b784fbd9cffb918d",
456            "--no-random",
457            "-j1",
458        ])
459        .unwrap();
460        assert_eq!(address, address!("0x00bF495b8b42fdFeb91c8bCEB42CA4eE7186AEd2"));
461        assert_eq!(
462            salt,
463            b256!("0x000000000000000000000000000000000000000000000000df00000000000000")
464        );
465    }
466
467    fn matcher_addresses() -> Vec<Address> {
468        let address = address!("0123456789abcdef0123456789abcdef01234567");
469        let mut addresses = vec![address, Address::ZERO, Address::repeat_byte(0xff)];
470        // Change every nibble to every possible value, including both matching and failing inputs.
471        for i in 0..ADDRESS_HEX_LEN {
472            for value in 0..16 {
473                let mut changed = address;
474                let shift = if i.is_multiple_of(2) { 4 } else { 0 };
475                changed[i / 2] = (changed[i / 2] & !(0xf << shift)) | (value << shift);
476                addresses.push(changed);
477            }
478        }
479        addresses
480    }
481
482    fn assert_byte_patterns_match_regex(patterns: &[String], addresses: &[Address]) {
483        let regex = RegexSetBuilder::new(patterns).case_insensitive(true).build().unwrap();
484        let byte_patterns = regex
485            .patterns()
486            .iter()
487            .map(|pattern| BytePattern::new(pattern))
488            .collect::<Option<Vec<_>>>();
489        for address in addresses {
490            let hex = hex::encode(address);
491            let expected = regex.matches(&hex).into_iter().count() == regex.patterns().len();
492            let actual = byte_patterns
493                .as_ref()
494                .is_some_and(|patterns| patterns.iter().all(|pattern| pattern.matches(address)));
495            assert_eq!(actual, expected, "patterns: {patterns:?}, address: {hex}");
496        }
497    }
498
499    #[test]
500    fn byte_patterns_match_regex_prefixes_and_suffixes() {
501        let addresses = matcher_addresses();
502        let hex = hex::encode(addresses[0]).to_ascii_uppercase();
503        for len in 0..=ADDRESS_HEX_LEN {
504            assert_byte_patterns_match_regex(&[format!("^{}", &hex[..len])], &addresses);
505            assert_byte_patterns_match_regex(
506                &[format!("{}$", &hex[ADDRESS_HEX_LEN - len..])],
507                &addresses,
508            );
509            assert_byte_patterns_match_regex(
510                &[format!("^{}", &hex[..len]), format!("{}$", &hex[len..])],
511                &addresses,
512            );
513        }
514        assert_byte_patterns_match_regex(
515            &[format!("^{}", &hex[..3]), format!("{}$", &hex[ADDRESS_HEX_LEN - 3..])],
516            &addresses,
517        );
518    }
519
520    #[test]
521    fn byte_patterns_match_regex_wildcards() {
522        let addresses = matcher_addresses();
523        let hex = hex::encode(addresses[0]).to_ascii_uppercase();
524        assert_byte_patterns_match_regex(&[".".repeat(ADDRESS_HEX_LEN)], &addresses);
525        for i in 0..ADDRESS_HEX_LEN {
526            // A single constrained nibble checks alignment at every address position.
527            let mut sparse = ".".repeat(ADDRESS_HEX_LEN);
528            sparse.replace_range(i..i + 1, &hex[i..i + 1]);
529            assert_byte_patterns_match_regex(&[sparse], &addresses);
530
531            // A single wildcard checks that unconstrained nibbles are ignored.
532            let mut dense = hex.clone();
533            dense.replace_range(i..i + 1, ".");
534            assert_byte_patterns_match_regex(&[dense], &addresses);
535        }
536        let alternating = hex
537            .chars()
538            .enumerate()
539            .map(|(i, nibble)| if i.is_multiple_of(3) { nibble } else { '.' })
540            .collect::<String>();
541        assert_byte_patterns_match_regex(&[alternating], &addresses);
542    }
543
544    #[test]
545    fn byte_patterns_match_regex_impossible_patterns() {
546        let addresses = matcher_addresses();
547        for pattern in [
548            format!("^{}", "a".repeat(ADDRESS_HEX_LEN + 1)),
549            format!("{}$", "b".repeat(ADDRESS_HEX_LEN + 1)),
550            "^0Xab".into(),
551        ] {
552            assert_byte_patterns_match_regex(&[pattern], &addresses);
553        }
554        // A possible prefix must not override an impossible suffix.
555        assert_byte_patterns_match_regex(&["^0".into(), "0Xab$".into()], &addresses);
556    }
557}