foundry_cheatcodes/
fs.rs

1//! Implementations of [`Filesystem`](spec::Group::Filesystem) cheatcodes.
2
3use super::string::parse;
4use crate::{Cheatcode, Cheatcodes, CheatcodesExecutor, CheatsCtxt, Result, Vm::*};
5use alloy_dyn_abi::DynSolType;
6use alloy_json_abi::ContractObject;
7use alloy_network::AnyTransactionReceipt;
8use alloy_primitives::{Bytes, U256, hex, map::Entry};
9use alloy_provider::network::ReceiptResponse;
10use alloy_sol_types::SolValue;
11use dialoguer::{Input, Password};
12use forge_script_sequence::{BroadcastReader, TransactionWithMetadata};
13use foundry_common::fs;
14use foundry_config::fs_permissions::FsAccessKind;
15use revm::{context::CreateScheme, interpreter::CreateInputs};
16use revm_inspectors::tracing::types::CallKind;
17use semver::Version;
18use std::{
19    io::{BufRead, BufReader, Write},
20    path::{Path, PathBuf},
21    process::Command,
22    sync::mpsc,
23    thread,
24    time::{SystemTime, UNIX_EPOCH},
25};
26use walkdir::WalkDir;
27
28impl Cheatcode for existsCall {
29    fn apply(&self, state: &mut Cheatcodes) -> Result {
30        let Self { path } = self;
31        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
32        Ok(path.exists().abi_encode())
33    }
34}
35
36impl Cheatcode for fsMetadataCall {
37    fn apply(&self, state: &mut Cheatcodes) -> Result {
38        let Self { path } = self;
39        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
40
41        let metadata = path.metadata()?;
42
43        // These fields not available on all platforms; default to 0
44        let [modified, accessed, created] =
45            [metadata.modified(), metadata.accessed(), metadata.created()].map(|time| {
46                time.unwrap_or(UNIX_EPOCH).duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()
47            });
48
49        Ok(FsMetadata {
50            isDir: metadata.is_dir(),
51            isSymlink: metadata.is_symlink(),
52            length: U256::from(metadata.len()),
53            readOnly: metadata.permissions().readonly(),
54            modified: U256::from(modified),
55            accessed: U256::from(accessed),
56            created: U256::from(created),
57        }
58        .abi_encode())
59    }
60}
61
62impl Cheatcode for isDirCall {
63    fn apply(&self, state: &mut Cheatcodes) -> Result {
64        let Self { path } = self;
65        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
66        Ok(path.is_dir().abi_encode())
67    }
68}
69
70impl Cheatcode for isFileCall {
71    fn apply(&self, state: &mut Cheatcodes) -> Result {
72        let Self { path } = self;
73        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
74        Ok(path.is_file().abi_encode())
75    }
76}
77
78impl Cheatcode for projectRootCall {
79    fn apply(&self, state: &mut Cheatcodes) -> Result {
80        let Self {} = self;
81        Ok(state.config.root.display().to_string().abi_encode())
82    }
83}
84
85impl Cheatcode for unixTimeCall {
86    fn apply(&self, _state: &mut Cheatcodes) -> Result {
87        let Self {} = self;
88        let difference = SystemTime::now()
89            .duration_since(UNIX_EPOCH)
90            .map_err(|e| fmt_err!("failed getting Unix timestamp: {e}"))?;
91        Ok(difference.as_millis().abi_encode())
92    }
93}
94
95impl Cheatcode for closeFileCall {
96    fn apply(&self, state: &mut Cheatcodes) -> Result {
97        let Self { path } = self;
98        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
99
100        state.test_context.opened_read_files.remove(&path);
101
102        Ok(Default::default())
103    }
104}
105
106impl Cheatcode for copyFileCall {
107    fn apply(&self, state: &mut Cheatcodes) -> Result {
108        let Self { from, to } = self;
109        let from = state.config.ensure_path_allowed(from, FsAccessKind::Read)?;
110        let to = state.config.ensure_path_allowed(to, FsAccessKind::Write)?;
111        state.config.ensure_not_foundry_toml(&to)?;
112
113        let n = fs::copy(from, to)?;
114        Ok(n.abi_encode())
115    }
116}
117
118impl Cheatcode for createDirCall {
119    fn apply(&self, state: &mut Cheatcodes) -> Result {
120        let Self { path, recursive } = self;
121        let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
122        if *recursive { fs::create_dir_all(path) } else { fs::create_dir(path) }?;
123        Ok(Default::default())
124    }
125}
126
127impl Cheatcode for readDir_0Call {
128    fn apply(&self, state: &mut Cheatcodes) -> Result {
129        let Self { path } = self;
130        read_dir(state, path.as_ref(), 1, false)
131    }
132}
133
134impl Cheatcode for readDir_1Call {
135    fn apply(&self, state: &mut Cheatcodes) -> Result {
136        let Self { path, maxDepth } = self;
137        read_dir(state, path.as_ref(), *maxDepth, false)
138    }
139}
140
141impl Cheatcode for readDir_2Call {
142    fn apply(&self, state: &mut Cheatcodes) -> Result {
143        let Self { path, maxDepth, followLinks } = self;
144        read_dir(state, path.as_ref(), *maxDepth, *followLinks)
145    }
146}
147
148impl Cheatcode for readFileCall {
149    fn apply(&self, state: &mut Cheatcodes) -> Result {
150        let Self { path } = self;
151        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
152        Ok(fs::read_to_string(path)?.abi_encode())
153    }
154}
155
156impl Cheatcode for readFileBinaryCall {
157    fn apply(&self, state: &mut Cheatcodes) -> Result {
158        let Self { path } = self;
159        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
160        Ok(fs::read(path)?.abi_encode())
161    }
162}
163
164impl Cheatcode for readLineCall {
165    fn apply(&self, state: &mut Cheatcodes) -> Result {
166        let Self { path } = self;
167        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
168
169        // Get reader for previously opened file to continue reading OR initialize new reader
170        let reader = match state.test_context.opened_read_files.entry(path.clone()) {
171            Entry::Occupied(entry) => entry.into_mut(),
172            Entry::Vacant(entry) => entry.insert(BufReader::new(fs::open(path)?)),
173        };
174
175        let mut line: String = String::new();
176        reader.read_line(&mut line)?;
177
178        // Remove trailing newline character, preserving others for cases where it may be important
179        if line.ends_with('\n') {
180            line.pop();
181            if line.ends_with('\r') {
182                line.pop();
183            }
184        }
185
186        Ok(line.abi_encode())
187    }
188}
189
190impl Cheatcode for readLinkCall {
191    fn apply(&self, state: &mut Cheatcodes) -> Result {
192        let Self { linkPath: path } = self;
193        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
194        let target = fs::read_link(path)?;
195        Ok(target.display().to_string().abi_encode())
196    }
197}
198
199impl Cheatcode for removeDirCall {
200    fn apply(&self, state: &mut Cheatcodes) -> Result {
201        let Self { path, recursive } = self;
202        let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
203        if *recursive { fs::remove_dir_all(path) } else { fs::remove_dir(path) }?;
204        Ok(Default::default())
205    }
206}
207
208impl Cheatcode for removeFileCall {
209    fn apply(&self, state: &mut Cheatcodes) -> Result {
210        let Self { path } = self;
211        let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
212        state.config.ensure_not_foundry_toml(&path)?;
213
214        // also remove from the set if opened previously
215        state.test_context.opened_read_files.remove(&path);
216
217        if state.fs_commit {
218            fs::remove_file(&path)?;
219        }
220
221        Ok(Default::default())
222    }
223}
224
225impl Cheatcode for writeFileCall {
226    fn apply(&self, state: &mut Cheatcodes) -> Result {
227        let Self { path, data } = self;
228        write_file(state, path.as_ref(), data.as_bytes())
229    }
230}
231
232impl Cheatcode for writeFileBinaryCall {
233    fn apply(&self, state: &mut Cheatcodes) -> Result {
234        let Self { path, data } = self;
235        write_file(state, path.as_ref(), data)
236    }
237}
238
239impl Cheatcode for writeLineCall {
240    fn apply(&self, state: &mut Cheatcodes) -> Result {
241        let Self { path, data: line } = self;
242        let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
243        state.config.ensure_not_foundry_toml(&path)?;
244
245        if state.fs_commit {
246            let mut file = std::fs::OpenOptions::new().append(true).create(true).open(path)?;
247
248            writeln!(file, "{line}")?;
249        }
250
251        Ok(Default::default())
252    }
253}
254
255impl Cheatcode for getArtifactPathByCodeCall {
256    fn apply(&self, state: &mut Cheatcodes) -> Result {
257        let Self { code } = self;
258        let (artifact_id, _) = state
259            .config
260            .available_artifacts
261            .as_ref()
262            .and_then(|artifacts| artifacts.find_by_creation_code(code))
263            .ok_or_else(|| fmt_err!("no matching artifact found"))?;
264
265        Ok(artifact_id.path.to_string_lossy().abi_encode())
266    }
267}
268
269impl Cheatcode for getArtifactPathByDeployedCodeCall {
270    fn apply(&self, state: &mut Cheatcodes) -> Result {
271        let Self { deployedCode } = self;
272        let (artifact_id, _) = state
273            .config
274            .available_artifacts
275            .as_ref()
276            .and_then(|artifacts| artifacts.find_by_deployed_code(deployedCode))
277            .ok_or_else(|| fmt_err!("no matching artifact found"))?;
278
279        Ok(artifact_id.path.to_string_lossy().abi_encode())
280    }
281}
282
283impl Cheatcode for getCodeCall {
284    fn apply(&self, state: &mut Cheatcodes) -> Result {
285        let Self { artifactPath: path } = self;
286        Ok(get_artifact_code(state, path, false)?.abi_encode())
287    }
288}
289
290impl Cheatcode for getDeployedCodeCall {
291    fn apply(&self, state: &mut Cheatcodes) -> Result {
292        let Self { artifactPath: path } = self;
293        Ok(get_artifact_code(state, path, true)?.abi_encode())
294    }
295}
296
297impl Cheatcode for deployCode_0Call {
298    fn apply_full(&self, ccx: &mut CheatsCtxt, executor: &mut dyn CheatcodesExecutor) -> Result {
299        let Self { artifactPath: path } = self;
300        deploy_code(ccx, executor, path, None, None, None)
301    }
302}
303
304impl Cheatcode for deployCode_1Call {
305    fn apply_full(&self, ccx: &mut CheatsCtxt, executor: &mut dyn CheatcodesExecutor) -> Result {
306        let Self { artifactPath: path, constructorArgs: args } = self;
307        deploy_code(ccx, executor, path, Some(args), None, None)
308    }
309}
310
311impl Cheatcode for deployCode_2Call {
312    fn apply_full(&self, ccx: &mut CheatsCtxt, executor: &mut dyn CheatcodesExecutor) -> Result {
313        let Self { artifactPath: path, value } = self;
314        deploy_code(ccx, executor, path, None, Some(*value), None)
315    }
316}
317
318impl Cheatcode for deployCode_3Call {
319    fn apply_full(&self, ccx: &mut CheatsCtxt, executor: &mut dyn CheatcodesExecutor) -> Result {
320        let Self { artifactPath: path, constructorArgs: args, value } = self;
321        deploy_code(ccx, executor, path, Some(args), Some(*value), None)
322    }
323}
324
325impl Cheatcode for deployCode_4Call {
326    fn apply_full(&self, ccx: &mut CheatsCtxt, executor: &mut dyn CheatcodesExecutor) -> Result {
327        let Self { artifactPath: path, salt } = self;
328        deploy_code(ccx, executor, path, None, None, Some((*salt).into()))
329    }
330}
331
332impl Cheatcode for deployCode_5Call {
333    fn apply_full(&self, ccx: &mut CheatsCtxt, executor: &mut dyn CheatcodesExecutor) -> Result {
334        let Self { artifactPath: path, constructorArgs: args, salt } = self;
335        deploy_code(ccx, executor, path, Some(args), None, Some((*salt).into()))
336    }
337}
338
339impl Cheatcode for deployCode_6Call {
340    fn apply_full(&self, ccx: &mut CheatsCtxt, executor: &mut dyn CheatcodesExecutor) -> Result {
341        let Self { artifactPath: path, value, salt } = self;
342        deploy_code(ccx, executor, path, None, Some(*value), Some((*salt).into()))
343    }
344}
345
346impl Cheatcode for deployCode_7Call {
347    fn apply_full(&self, ccx: &mut CheatsCtxt, executor: &mut dyn CheatcodesExecutor) -> Result {
348        let Self { artifactPath: path, constructorArgs: args, value, salt } = self;
349        deploy_code(ccx, executor, path, Some(args), Some(*value), Some((*salt).into()))
350    }
351}
352
353/// Helper function to deploy contract from artifact code.
354/// Uses CREATE2 scheme if salt specified.
355fn deploy_code(
356    ccx: &mut CheatsCtxt,
357    executor: &mut dyn CheatcodesExecutor,
358    path: &str,
359    constructor_args: Option<&Bytes>,
360    value: Option<U256>,
361    salt: Option<U256>,
362) -> Result {
363    let mut bytecode = get_artifact_code(ccx.state, path, false)?.to_vec();
364    if let Some(args) = constructor_args {
365        bytecode.extend_from_slice(args);
366    }
367
368    let scheme =
369        if let Some(salt) = salt { CreateScheme::Create2 { salt } } else { CreateScheme::Create };
370
371    let outcome = executor.exec_create(
372        CreateInputs {
373            caller: ccx.caller,
374            scheme,
375            value: value.unwrap_or(U256::ZERO),
376            init_code: bytecode.into(),
377            gas_limit: ccx.gas_limit,
378        },
379        ccx,
380    )?;
381
382    if !outcome.result.result.is_ok() {
383        return Err(crate::Error::from(outcome.result.output));
384    }
385
386    let address = outcome.address.ok_or_else(|| fmt_err!("contract creation failed"))?;
387
388    Ok(address.abi_encode())
389}
390
391/// Returns the path to the json artifact depending on the input
392///
393/// Can parse following input formats:
394/// - `path/to/artifact.json`
395/// - `path/to/contract.sol`
396/// - `path/to/contract.sol:ContractName`
397/// - `path/to/contract.sol:ContractName:0.8.23`
398/// - `path/to/contract.sol:0.8.23`
399/// - `ContractName`
400/// - `ContractName:0.8.23`
401fn get_artifact_code(state: &Cheatcodes, path: &str, deployed: bool) -> Result<Bytes> {
402    let path = if path.ends_with(".json") {
403        PathBuf::from(path)
404    } else {
405        let mut parts = path.split(':');
406
407        let mut file = None;
408        let mut contract_name = None;
409        let mut version = None;
410
411        let path_or_name = parts.next().unwrap();
412        if path_or_name.contains('.') {
413            file = Some(PathBuf::from(path_or_name));
414            if let Some(name_or_version) = parts.next() {
415                if name_or_version.contains('.') {
416                    version = Some(name_or_version);
417                } else {
418                    contract_name = Some(name_or_version);
419                    version = parts.next();
420                }
421            }
422        } else {
423            contract_name = Some(path_or_name);
424            version = parts.next();
425        }
426
427        let version = if let Some(version) = version {
428            Some(Version::parse(version).map_err(|e| fmt_err!("failed parsing version: {e}"))?)
429        } else {
430            None
431        };
432
433        // Use available artifacts list if present
434        if let Some(artifacts) = &state.config.available_artifacts {
435            let filtered = artifacts
436                .iter()
437                .filter(|(id, _)| {
438                    // name might be in the form of "Counter.0.8.23"
439                    let id_name = id.name.split('.').next().unwrap();
440
441                    if let Some(path) = &file
442                        && !id.source.ends_with(path)
443                    {
444                        return false;
445                    }
446                    if let Some(name) = contract_name
447                        && id_name != name
448                    {
449                        return false;
450                    }
451                    if let Some(ref version) = version
452                        && (id.version.minor != version.minor
453                            || id.version.major != version.major
454                            || id.version.patch != version.patch)
455                    {
456                        return false;
457                    }
458                    true
459                })
460                .collect::<Vec<_>>();
461
462            let artifact = match &filtered[..] {
463                [] => Err(fmt_err!("no matching artifact found")),
464                [artifact] => Ok(*artifact),
465                filtered => {
466                    let mut filtered = filtered.to_vec();
467                    // If we know the current script/test contract solc version, try to filter by it
468                    state
469                        .config
470                        .running_artifact
471                        .as_ref()
472                        .and_then(|running| {
473                            // Firstly filter by version
474                            filtered.retain(|(id, _)| id.version == running.version);
475
476                            // Return artifact if only one matched
477                            if filtered.len() == 1 {
478                                return Some(filtered[0]);
479                            }
480
481                            // Try filtering by profile as well
482                            filtered.retain(|(id, _)| id.profile == running.profile);
483
484                            if filtered.len() == 1 { Some(filtered[0]) } else { None }
485                        })
486                        .ok_or_else(|| fmt_err!("multiple matching artifacts found"))
487                }
488            }?;
489
490            let maybe_bytecode = if deployed {
491                artifact.1.deployed_bytecode().cloned()
492            } else {
493                artifact.1.bytecode().cloned()
494            };
495
496            return maybe_bytecode
497                .ok_or_else(|| fmt_err!("no bytecode for contract; is it abstract or unlinked?"));
498        } else {
499            let path_in_artifacts =
500                match (file.map(|f| f.to_string_lossy().to_string()), contract_name) {
501                    (Some(file), Some(contract_name)) => {
502                        PathBuf::from(format!("{file}/{contract_name}.json"))
503                    }
504                    (None, Some(contract_name)) => {
505                        PathBuf::from(format!("{contract_name}.sol/{contract_name}.json"))
506                    }
507                    (Some(file), None) => {
508                        let name = file.replace(".sol", "");
509                        PathBuf::from(format!("{file}/{name}.json"))
510                    }
511                    _ => bail!("invalid artifact path"),
512                };
513
514            state.config.paths.artifacts.join(path_in_artifacts)
515        }
516    };
517
518    let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
519    let data = fs::read_to_string(path)?;
520    let artifact = serde_json::from_str::<ContractObject>(&data)?;
521    let maybe_bytecode = if deployed { artifact.deployed_bytecode } else { artifact.bytecode };
522    maybe_bytecode.ok_or_else(|| fmt_err!("no bytecode for contract; is it abstract or unlinked?"))
523}
524
525impl Cheatcode for ffiCall {
526    fn apply(&self, state: &mut Cheatcodes) -> Result {
527        let Self { commandInput: input } = self;
528
529        let output = ffi(state, input)?;
530        // TODO: check exit code?
531        if !output.stderr.is_empty() {
532            let stderr = String::from_utf8_lossy(&output.stderr);
533            error!(target: "cheatcodes", ?input, ?stderr, "non-empty stderr");
534        }
535        // we already hex-decoded the stdout in `ffi`
536        Ok(output.stdout.abi_encode())
537    }
538}
539
540impl Cheatcode for tryFfiCall {
541    fn apply(&self, state: &mut Cheatcodes) -> Result {
542        let Self { commandInput: input } = self;
543        ffi(state, input).map(|res| res.abi_encode())
544    }
545}
546
547impl Cheatcode for promptCall {
548    fn apply(&self, state: &mut Cheatcodes) -> Result {
549        let Self { promptText: text } = self;
550        prompt(state, text, prompt_input).map(|res| res.abi_encode())
551    }
552}
553
554impl Cheatcode for promptSecretCall {
555    fn apply(&self, state: &mut Cheatcodes) -> Result {
556        let Self { promptText: text } = self;
557        prompt(state, text, prompt_password).map(|res| res.abi_encode())
558    }
559}
560
561impl Cheatcode for promptSecretUintCall {
562    fn apply(&self, state: &mut Cheatcodes) -> Result {
563        let Self { promptText: text } = self;
564        parse(&prompt(state, text, prompt_password)?, &DynSolType::Uint(256))
565    }
566}
567
568impl Cheatcode for promptAddressCall {
569    fn apply(&self, state: &mut Cheatcodes) -> Result {
570        let Self { promptText: text } = self;
571        parse(&prompt(state, text, prompt_input)?, &DynSolType::Address)
572    }
573}
574
575impl Cheatcode for promptUintCall {
576    fn apply(&self, state: &mut Cheatcodes) -> Result {
577        let Self { promptText: text } = self;
578        parse(&prompt(state, text, prompt_input)?, &DynSolType::Uint(256))
579    }
580}
581
582pub(super) fn write_file(state: &Cheatcodes, path: &Path, contents: &[u8]) -> Result {
583    let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
584    // write access to foundry.toml is not allowed
585    state.config.ensure_not_foundry_toml(&path)?;
586
587    if state.fs_commit {
588        fs::write(path, contents)?;
589    }
590
591    Ok(Default::default())
592}
593
594fn read_dir(state: &Cheatcodes, path: &Path, max_depth: u64, follow_links: bool) -> Result {
595    let root = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
596    let paths: Vec<DirEntry> = WalkDir::new(root)
597        .min_depth(1)
598        .max_depth(max_depth.try_into().unwrap_or(usize::MAX))
599        .follow_links(follow_links)
600        .contents_first(false)
601        .same_file_system(true)
602        .sort_by_file_name()
603        .into_iter()
604        .map(|entry| match entry {
605            Ok(entry) => DirEntry {
606                errorMessage: String::new(),
607                path: entry.path().display().to_string(),
608                depth: entry.depth() as u64,
609                isDir: entry.file_type().is_dir(),
610                isSymlink: entry.path_is_symlink(),
611            },
612            Err(e) => DirEntry {
613                errorMessage: e.to_string(),
614                path: e.path().map(|p| p.display().to_string()).unwrap_or_default(),
615                depth: e.depth() as u64,
616                isDir: false,
617                isSymlink: false,
618            },
619        })
620        .collect();
621    Ok(paths.abi_encode())
622}
623
624fn ffi(state: &Cheatcodes, input: &[String]) -> Result<FfiResult> {
625    ensure!(
626        state.config.ffi,
627        "FFI is disabled; add the `--ffi` flag to allow tests to call external commands"
628    );
629    ensure!(!input.is_empty() && !input[0].is_empty(), "can't execute empty command");
630    let mut cmd = Command::new(&input[0]);
631    cmd.args(&input[1..]);
632
633    debug!(target: "cheatcodes", ?cmd, "invoking ffi");
634
635    let output = cmd
636        .current_dir(&state.config.root)
637        .output()
638        .map_err(|err| fmt_err!("failed to execute command {cmd:?}: {err}"))?;
639
640    // The stdout might be encoded on valid hex, or it might just be a string,
641    // so we need to determine which it is to avoid improperly encoding later.
642    let trimmed_stdout = String::from_utf8(output.stdout)?;
643    let trimmed_stdout = trimmed_stdout.trim();
644    let encoded_stdout = if let Ok(hex) = hex::decode(trimmed_stdout) {
645        hex
646    } else {
647        trimmed_stdout.as_bytes().to_vec()
648    };
649    Ok(FfiResult {
650        exitCode: output.status.code().unwrap_or(69),
651        stdout: encoded_stdout.into(),
652        stderr: output.stderr.into(),
653    })
654}
655
656fn prompt_input(prompt_text: &str) -> Result<String, dialoguer::Error> {
657    Input::new().allow_empty(true).with_prompt(prompt_text).interact_text()
658}
659
660fn prompt_password(prompt_text: &str) -> Result<String, dialoguer::Error> {
661    Password::new().with_prompt(prompt_text).interact()
662}
663
664fn prompt(
665    state: &Cheatcodes,
666    prompt_text: &str,
667    input: fn(&str) -> Result<String, dialoguer::Error>,
668) -> Result<String> {
669    let text_clone = prompt_text.to_string();
670    let timeout = state.config.prompt_timeout;
671    let (tx, rx) = mpsc::channel();
672
673    thread::spawn(move || {
674        let _ = tx.send(input(&text_clone));
675    });
676
677    match rx.recv_timeout(timeout) {
678        Ok(res) => res.map_err(|err| {
679            let _ = sh_println!();
680            err.to_string().into()
681        }),
682        Err(_) => {
683            let _ = sh_eprintln!();
684            Err("Prompt timed out".into())
685        }
686    }
687}
688
689impl Cheatcode for getBroadcastCall {
690    fn apply(&self, state: &mut Cheatcodes) -> Result {
691        let Self { contractName, chainId, txType } = self;
692
693        let latest_broadcast = latest_broadcast(
694            contractName,
695            *chainId,
696            &state.config.broadcast,
697            vec![map_broadcast_tx_type(*txType)],
698        )?;
699
700        Ok(latest_broadcast.abi_encode())
701    }
702}
703
704impl Cheatcode for getBroadcasts_0Call {
705    fn apply(&self, state: &mut Cheatcodes) -> Result {
706        let Self { contractName, chainId, txType } = self;
707
708        let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?
709            .with_tx_type(map_broadcast_tx_type(*txType));
710
711        let broadcasts = reader.read()?;
712
713        let summaries = broadcasts
714            .into_iter()
715            .flat_map(|broadcast| {
716                let results = reader.into_tx_receipts(broadcast);
717                parse_broadcast_results(results)
718            })
719            .collect::<Vec<_>>();
720
721        Ok(summaries.abi_encode())
722    }
723}
724
725impl Cheatcode for getBroadcasts_1Call {
726    fn apply(&self, state: &mut Cheatcodes) -> Result {
727        let Self { contractName, chainId } = self;
728
729        let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?;
730
731        let broadcasts = reader.read()?;
732
733        let summaries = broadcasts
734            .into_iter()
735            .flat_map(|broadcast| {
736                let results = reader.into_tx_receipts(broadcast);
737                parse_broadcast_results(results)
738            })
739            .collect::<Vec<_>>();
740
741        Ok(summaries.abi_encode())
742    }
743}
744
745impl Cheatcode for getDeployment_0Call {
746    fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
747        let Self { contractName } = self;
748        let chain_id = ccx.ecx.cfg.chain_id;
749
750        let latest_broadcast = latest_broadcast(
751            contractName,
752            chain_id,
753            &ccx.state.config.broadcast,
754            vec![CallKind::Create, CallKind::Create2],
755        )?;
756
757        Ok(latest_broadcast.contractAddress.abi_encode())
758    }
759}
760
761impl Cheatcode for getDeployment_1Call {
762    fn apply(&self, state: &mut Cheatcodes) -> Result {
763        let Self { contractName, chainId } = self;
764
765        let latest_broadcast = latest_broadcast(
766            contractName,
767            *chainId,
768            &state.config.broadcast,
769            vec![CallKind::Create, CallKind::Create2],
770        )?;
771
772        Ok(latest_broadcast.contractAddress.abi_encode())
773    }
774}
775
776impl Cheatcode for getDeploymentsCall {
777    fn apply(&self, state: &mut Cheatcodes) -> Result {
778        let Self { contractName, chainId } = self;
779
780        let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?
781            .with_tx_type(CallKind::Create)
782            .with_tx_type(CallKind::Create2);
783
784        let broadcasts = reader.read()?;
785
786        let summaries = broadcasts
787            .into_iter()
788            .flat_map(|broadcast| {
789                let results = reader.into_tx_receipts(broadcast);
790                parse_broadcast_results(results)
791            })
792            .collect::<Vec<_>>();
793
794        let deployed_addresses =
795            summaries.into_iter().map(|summary| summary.contractAddress).collect::<Vec<_>>();
796
797        Ok(deployed_addresses.abi_encode())
798    }
799}
800
801fn map_broadcast_tx_type(tx_type: BroadcastTxType) -> CallKind {
802    match tx_type {
803        BroadcastTxType::Call => CallKind::Call,
804        BroadcastTxType::Create => CallKind::Create,
805        BroadcastTxType::Create2 => CallKind::Create2,
806        _ => unreachable!("invalid tx type"),
807    }
808}
809
810fn parse_broadcast_results(
811    results: Vec<(TransactionWithMetadata, AnyTransactionReceipt)>,
812) -> Vec<BroadcastTxSummary> {
813    results
814        .into_iter()
815        .map(|(tx, receipt)| BroadcastTxSummary {
816            txHash: receipt.transaction_hash,
817            blockNumber: receipt.block_number.unwrap_or_default(),
818            txType: match tx.opcode {
819                CallKind::Call => BroadcastTxType::Call,
820                CallKind::Create => BroadcastTxType::Create,
821                CallKind::Create2 => BroadcastTxType::Create2,
822                _ => unreachable!("invalid tx type"),
823            },
824            contractAddress: tx.contract_address.unwrap_or_default(),
825            success: receipt.status(),
826        })
827        .collect()
828}
829
830fn latest_broadcast(
831    contract_name: &String,
832    chain_id: u64,
833    broadcast_path: &Path,
834    filters: Vec<CallKind>,
835) -> Result<BroadcastTxSummary> {
836    let mut reader = BroadcastReader::new(contract_name.clone(), chain_id, broadcast_path)?;
837
838    for filter in filters {
839        reader = reader.with_tx_type(filter);
840    }
841
842    let broadcast = reader.read_latest()?;
843
844    let results = reader.into_tx_receipts(broadcast);
845
846    let summaries = parse_broadcast_results(results);
847
848    summaries
849        .first()
850        .ok_or_else(|| fmt_err!("no deployment found for {contract_name} on chain {chain_id}"))
851        .cloned()
852}
853
854#[cfg(test)]
855mod tests {
856    use super::*;
857    use crate::CheatsConfig;
858    use std::sync::Arc;
859
860    fn cheats() -> Cheatcodes {
861        let config = CheatsConfig {
862            ffi: true,
863            root: PathBuf::from(&env!("CARGO_MANIFEST_DIR")),
864            ..Default::default()
865        };
866        Cheatcodes::new(Arc::new(config))
867    }
868
869    #[test]
870    fn test_ffi_hex() {
871        let msg = b"gm";
872        let cheats = cheats();
873        let args = ["echo".to_string(), hex::encode(msg)];
874        let output = ffi(&cheats, &args).unwrap();
875        assert_eq!(output.stdout, Bytes::from(msg));
876    }
877
878    #[test]
879    fn test_ffi_string() {
880        let msg = "gm";
881        let cheats = cheats();
882        let args = ["echo".to_string(), msg.to_string()];
883        let output = ffi(&cheats, &args).unwrap();
884        assert_eq!(output.stdout, Bytes::from(msg.as_bytes()));
885    }
886
887    #[test]
888    fn test_artifact_parsing() {
889        let s = include_str!("../../evm/test-data/solc-obj.json");
890        let artifact: ContractObject = serde_json::from_str(s).unwrap();
891        assert!(artifact.bytecode.is_some());
892
893        let artifact: ContractObject = serde_json::from_str(s).unwrap();
894        assert!(artifact.deployed_bytecode.is_some());
895    }
896}