Skip to main content

foundry_cheatcodes/
fs.rs

1//! Implementations of [`Filesystem`](spec::Group::Filesystem) cheatcodes.
2
3use super::string::parse;
4use crate::{
5    Cheatcode, CheatcodesCore, CheatcodesExecutor, CheatsCtxt, Result, Vm::*,
6    inspector::exec_create,
7};
8use alloy_dyn_abi::DynSolType;
9use alloy_json_abi::ContractObject;
10use alloy_network::{AnyNetwork, Network, ReceiptResponse};
11use alloy_primitives::{B256, Bytes, FixedBytes, U256, hex, map::Entry};
12use alloy_sol_types::SolValue;
13use dialoguer::{Input, Password};
14use evm2::{
15    EvmFeatures,
16    bytecode::Bytecode,
17    interpreter::{Host, MessageKind, derive_create_destination},
18    version::GasId,
19};
20use forge_script_sequence::{BroadcastReader, TransactionWithMetadata};
21use foundry_common::{contracts::ContractData, fs};
22use foundry_config::fs_permissions::FsAccessKind;
23use foundry_evm_core::evm::{FoundryEvmNetwork, MessageFor};
24use foundry_evm_traces::CallKind;
25use semver::Version;
26use std::{
27    io::{BufRead, BufReader},
28    mem,
29    path::{Path, PathBuf},
30    process::Command,
31    sync::mpsc,
32    thread,
33    time::{SystemTime, UNIX_EPOCH},
34};
35use walkdir::WalkDir;
36
37/// Parsed artifact path components.
38#[derive(Debug, Default, PartialEq, Eq)]
39struct ParsedArtifactPath<'a> {
40    file: Option<PathBuf>,
41    contract_name: Option<&'a str>,
42    version: Option<Version>,
43    profile: Option<&'a str>,
44}
45
46/// Parses an artifact path string into its components.
47///
48/// Supports the following formats:
49/// - `path/to/contract.sol`
50/// - `path/to/contract.sol:ContractName`
51/// - `path/to/contract.sol:ContractName:0.8.23`
52/// - `path/to/contract.sol:ContractName:profile`
53/// - `path/to/contract.sol:0.8.23`
54/// - `path/to/contract.sol:profile`
55/// - `ContractName`
56/// - `ContractName:0.8.23`
57/// - `ContractName:profile`
58fn parse_artifact_path(path: &str) -> std::result::Result<ParsedArtifactPath<'_>, String> {
59    // A Windows drive separator belongs to the file, not the artifact's suffix fields.
60    // Recognize it on every host so parsing does not depend on the current platform.
61    let unprefixed = path.strip_prefix(r"\\?\").unwrap_or(path);
62    let drive_prefix_len = match unprefixed.as_bytes() {
63        [drive, b':', b'/' | b'\\', ..] if drive.is_ascii_alphabetic() => {
64            path.len() - unprefixed.len() + 2
65        }
66        _ => 0,
67    };
68    let mut parts = path[drive_prefix_len..].split(':');
69
70    let mut file = None;
71    let mut contract_name = None;
72    let mut version = None;
73    let mut profile = None;
74
75    let path_or_name = parts.next().unwrap();
76    let path_or_name = &path[..drive_prefix_len + path_or_name.len()];
77    if path_or_name.contains('.') {
78        file = Some(PathBuf::from(path_or_name));
79        if let Some(name_or_version_or_profile) = parts.next() {
80            if name_or_version_or_profile.contains('.')
81                || Version::parse(name_or_version_or_profile).is_ok()
82            {
83                version = Some(name_or_version_or_profile);
84            } else {
85                contract_name = Some(name_or_version_or_profile);
86                if let Some(version_or_profile) = parts.next() {
87                    if version_or_profile.contains('.')
88                        || Version::parse(version_or_profile).is_ok()
89                    {
90                        version = Some(version_or_profile);
91                    } else {
92                        profile = Some(version_or_profile);
93                    }
94                }
95            }
96        }
97    } else {
98        contract_name = Some(path_or_name);
99        if let Some(version_or_profile) = parts.next() {
100            if version_or_profile.contains('.') || Version::parse(version_or_profile).is_ok() {
101                version = Some(version_or_profile);
102            } else {
103                profile = Some(version_or_profile);
104            }
105        }
106    }
107
108    let version = if let Some(version) = version {
109        Some(Version::parse(version).map_err(|e| format!("failed parsing version: {e}"))?)
110    } else {
111        None
112    };
113
114    Ok(ParsedArtifactPath { file, contract_name, version, profile })
115}
116
117impl Cheatcode for existsCall {
118    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
119        let Self { path } = self;
120        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
121        Ok(path.exists().abi_encode())
122    }
123}
124
125impl Cheatcode for fsMetadataCall {
126    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
127        let Self { path } = self;
128        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
129
130        let metadata = path.metadata()?;
131
132        // These fields not available on all platforms; default to 0
133        let [modified, accessed, created] =
134            [metadata.modified(), metadata.accessed(), metadata.created()].map(|time| {
135                time.unwrap_or(UNIX_EPOCH).duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()
136            });
137
138        Ok(FsMetadata {
139            isDir: metadata.is_dir(),
140            isSymlink: metadata.is_symlink(),
141            length: U256::from(metadata.len()),
142            readOnly: metadata.permissions().readonly(),
143            modified: U256::from(modified),
144            accessed: U256::from(accessed),
145            created: U256::from(created),
146        }
147        .abi_encode())
148    }
149}
150
151impl Cheatcode for isDirCall {
152    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
153        let Self { path } = self;
154        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
155        Ok(path.is_dir().abi_encode())
156    }
157}
158
159impl Cheatcode for isFileCall {
160    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
161        let Self { path } = self;
162        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
163        Ok(path.is_file().abi_encode())
164    }
165}
166
167impl Cheatcode for projectRootCall {
168    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
169        let Self {} = self;
170        Ok(state.config.root.display().to_string().abi_encode())
171    }
172}
173
174impl Cheatcode for currentFilePathCall {
175    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
176        let Self {} = self;
177        let artifact = state
178            .config
179            .running_artifact
180            .as_ref()
181            .ok_or_else(|| fmt_err!("no running contract found"))?;
182        let relative = artifact.source.strip_prefix(&state.config.root).unwrap_or(&artifact.source);
183        Ok(relative.display().to_string().abi_encode())
184    }
185}
186
187impl Cheatcode for unixTimeCall {
188    fn apply_context_free(&self) -> Result {
189        let Self {} = self;
190        let difference = SystemTime::now()
191            .duration_since(UNIX_EPOCH)
192            .map_err(|e| fmt_err!("failed getting Unix timestamp: {e}"))?;
193        Ok(difference.as_millis().abi_encode())
194    }
195}
196
197impl Cheatcode for closeFileCall {
198    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
199        let Self { path } = self;
200        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
201
202        state.test_context.opened_read_files.remove(&path);
203
204        Ok(Default::default())
205    }
206}
207
208impl Cheatcode for copyFileCall {
209    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
210        let Self { from, to } = self;
211        let from = state.config.ensure_path_allowed(from, FsAccessKind::Read)?;
212        let to = state.config.ensure_path_allowed(to, FsAccessKind::Write)?;
213        state.config.ensure_not_foundry_toml(&to)?;
214
215        let n = fs::copy(from, to)?;
216        Ok(n.abi_encode())
217    }
218}
219
220impl Cheatcode for createDirCall {
221    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
222        let Self { path, recursive } = self;
223        let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
224        if *recursive { fs::create_dir_all(path) } else { fs::create_dir(path) }?;
225        Ok(Default::default())
226    }
227}
228
229impl Cheatcode for readDir_0Call {
230    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
231        let Self { path } = self;
232        read_dir(state, path.as_ref(), 1, false)
233    }
234}
235
236impl Cheatcode for readDir_1Call {
237    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
238        let Self { path, maxDepth } = self;
239        read_dir(state, path.as_ref(), *maxDepth, false)
240    }
241}
242
243impl Cheatcode for readDir_2Call {
244    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
245        let Self { path, maxDepth, followLinks } = self;
246        read_dir(state, path.as_ref(), *maxDepth, *followLinks)
247    }
248}
249
250impl Cheatcode for readFileCall {
251    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
252        let Self { path } = self;
253        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
254        Ok(fs::locked_read_to_string(path)?.abi_encode())
255    }
256}
257
258impl Cheatcode for readFileBinaryCall {
259    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
260        let Self { path } = self;
261        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
262        Ok(fs::locked_read(path)?.abi_encode())
263    }
264}
265
266impl Cheatcode for readLineCall {
267    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
268        let Self { path } = self;
269        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
270
271        // Get reader for previously opened file to continue reading OR initialize new reader
272        let reader = match state.test_context.opened_read_files.entry(path.clone()) {
273            Entry::Occupied(entry) => entry.into_mut(),
274            Entry::Vacant(entry) => entry.insert(BufReader::new(fs::open(path)?)),
275        };
276
277        let mut line: String = String::new();
278        reader.read_line(&mut line)?;
279
280        // Remove trailing newline character, preserving others for cases where it may be important
281        if line.ends_with('\n') {
282            line.pop();
283            if line.ends_with('\r') {
284                line.pop();
285            }
286        }
287
288        Ok(line.abi_encode())
289    }
290}
291
292impl Cheatcode for readLinkCall {
293    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
294        let Self { linkPath: path } = self;
295        // Validate the resolved target, but keep the link itself for read_link.
296        state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
297        let target = fs::read_link(state.config.root.join(path))?;
298        Ok(target.display().to_string().abi_encode())
299    }
300}
301
302impl Cheatcode for removeDirCall {
303    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
304        let Self { path, recursive } = self;
305        let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
306        state.config.ensure_not_foundry_toml(&path)?;
307        if *recursive { fs::remove_dir_all(path) } else { fs::remove_dir(path) }?;
308        Ok(Default::default())
309    }
310}
311
312impl Cheatcode for removeFileCall {
313    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
314        let Self { path } = self;
315        let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
316        state.config.ensure_not_foundry_toml(&path)?;
317
318        // also remove from the set if opened previously
319        state.test_context.opened_read_files.remove(&path);
320
321        if state.fs_commit {
322            fs::remove_file(&path)?;
323        }
324
325        Ok(Default::default())
326    }
327}
328
329impl Cheatcode for writeFileCall {
330    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
331        let Self { path, data } = self;
332        write_file(state, path.as_ref(), data.as_bytes())
333    }
334}
335
336impl Cheatcode for writeFileBinaryCall {
337    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
338        let Self { path, data } = self;
339        write_file(state, path.as_ref(), data)
340    }
341}
342
343impl Cheatcode for writeLineCall {
344    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
345        let Self { path, data: line } = self;
346        let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
347        state.config.ensure_not_foundry_toml(&path)?;
348
349        if state.fs_commit {
350            fs::locked_write_line(path, line)?;
351        }
352
353        Ok(Default::default())
354    }
355}
356
357impl Cheatcode for getArtifactPathByCodeCall {
358    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
359        let Self { code } = self;
360        let (artifact_id, _) = state
361            .config
362            .available_artifacts
363            .as_ref()
364            .and_then(|artifacts| artifacts.find_by_creation_code(code))
365            .ok_or_else(|| fmt_err!("no matching artifact found"))?;
366
367        Ok(artifact_id.path.to_string_lossy().abi_encode())
368    }
369}
370
371impl Cheatcode for getArtifactPathByDeployedCodeCall {
372    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
373        let Self { deployedCode } = self;
374        let (artifact_id, _) = state
375            .config
376            .available_artifacts
377            .as_ref()
378            .and_then(|artifacts| artifacts.find_by_deployed_code(deployedCode))
379            .ok_or_else(|| fmt_err!("no matching artifact found"))?;
380
381        Ok(artifact_id.path.to_string_lossy().abi_encode())
382    }
383}
384
385impl Cheatcode for getCodeCall {
386    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
387        let Self { artifactPath: path } = self;
388        Ok(get_artifact_code(state, path, false)?.abi_encode())
389    }
390}
391
392impl Cheatcode for getDeployedCodeCall {
393    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
394        let Self { artifactPath: path } = self;
395        Ok(get_artifact_code(state, path, true)?.abi_encode())
396    }
397}
398
399impl Cheatcode for getSelectorsCall {
400    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
401        let Self { artifactPath: path } = self;
402        let selectors: Vec<FixedBytes<4>> = match get_artifact_source(state, path)? {
403            ArtifactSource::InMemory(data) => data.abi.functions().map(|f| f.selector()).collect(),
404            ArtifactSource::Disk(path) => {
405                let data = read_artifact_file(state, &path)?;
406                // Parse as raw JSON rather than `ContractObject` so we can still read selectors
407                // from artifacts with unlinked bytecode (which `ContractObject` rejects).
408                let json: serde_json::Value = serde_json::from_str(&data)?;
409                let abi =
410                    json.get("abi").ok_or_else(|| fmt_err!("no `abi` field in artifact JSON"))?;
411                let abi: alloy_json_abi::JsonAbi =
412                    serde_json::from_value(abi.clone()).map_err(|e| fmt_err!("{e}"))?;
413                abi.functions().map(|f| f.selector()).collect()
414            }
415        };
416        Ok(selectors.abi_encode())
417    }
418}
419
420impl Cheatcode for deployCode_0Call {
421    fn apply_full<FEN: FoundryEvmNetwork>(
422        &self,
423        ccx: &mut CheatsCtxt<'_, '_, FEN>,
424        executor: &mut dyn CheatcodesExecutor<FEN>,
425    ) -> Result {
426        let Self { artifactPath: path } = self;
427        deploy_code(ccx, executor, path, None, None, None)
428    }
429}
430
431impl Cheatcode for deployCode_1Call {
432    fn apply_full<FEN: FoundryEvmNetwork>(
433        &self,
434        ccx: &mut CheatsCtxt<'_, '_, FEN>,
435        executor: &mut dyn CheatcodesExecutor<FEN>,
436    ) -> Result {
437        let Self { artifactPath: path, constructorArgs: args } = self;
438        deploy_code(ccx, executor, path, Some(args), None, None)
439    }
440}
441
442impl Cheatcode for deployCode_2Call {
443    fn apply_full<FEN: FoundryEvmNetwork>(
444        &self,
445        ccx: &mut CheatsCtxt<'_, '_, FEN>,
446        executor: &mut dyn CheatcodesExecutor<FEN>,
447    ) -> Result {
448        let Self { artifactPath: path, value } = self;
449        deploy_code(ccx, executor, path, None, Some(*value), None)
450    }
451}
452
453impl Cheatcode for deployCode_3Call {
454    fn apply_full<FEN: FoundryEvmNetwork>(
455        &self,
456        ccx: &mut CheatsCtxt<'_, '_, FEN>,
457        executor: &mut dyn CheatcodesExecutor<FEN>,
458    ) -> Result {
459        let Self { artifactPath: path, constructorArgs: args, value } = self;
460        deploy_code(ccx, executor, path, Some(args), Some(*value), None)
461    }
462}
463
464impl Cheatcode for deployCode_4Call {
465    fn apply_full<FEN: FoundryEvmNetwork>(
466        &self,
467        ccx: &mut CheatsCtxt<'_, '_, FEN>,
468        executor: &mut dyn CheatcodesExecutor<FEN>,
469    ) -> Result {
470        let Self { artifactPath: path, salt } = self;
471        deploy_code(ccx, executor, path, None, None, Some((*salt).into()))
472    }
473}
474
475impl Cheatcode for deployCode_5Call {
476    fn apply_full<FEN: FoundryEvmNetwork>(
477        &self,
478        ccx: &mut CheatsCtxt<'_, '_, FEN>,
479        executor: &mut dyn CheatcodesExecutor<FEN>,
480    ) -> Result {
481        let Self { artifactPath: path, constructorArgs: args, salt } = self;
482        deploy_code(ccx, executor, path, Some(args), None, Some((*salt).into()))
483    }
484}
485
486impl Cheatcode for deployCode_6Call {
487    fn apply_full<FEN: FoundryEvmNetwork>(
488        &self,
489        ccx: &mut CheatsCtxt<'_, '_, FEN>,
490        executor: &mut dyn CheatcodesExecutor<FEN>,
491    ) -> Result {
492        let Self { artifactPath: path, value, salt } = self;
493        deploy_code(ccx, executor, path, None, Some(*value), Some((*salt).into()))
494    }
495}
496
497impl Cheatcode for deployCode_7Call {
498    fn apply_full<FEN: FoundryEvmNetwork>(
499        &self,
500        ccx: &mut CheatsCtxt<'_, '_, FEN>,
501        executor: &mut dyn CheatcodesExecutor<FEN>,
502    ) -> Result {
503        let Self { artifactPath: path, constructorArgs: args, value, salt } = self;
504        deploy_code(ccx, executor, path, Some(args), Some(*value), Some((*salt).into()))
505    }
506}
507
508/// Helper function to deploy contract from artifact code.
509/// Uses CREATE2 scheme if salt specified.
510fn deploy_code<FEN: FoundryEvmNetwork>(
511    ccx: &mut CheatsCtxt<'_, '_, FEN>,
512    executor: &mut dyn CheatcodesExecutor<FEN>,
513    path: &str,
514    constructor_args: Option<&Bytes>,
515    value: Option<U256>,
516    salt: Option<U256>,
517) -> Result {
518    // Synthetic creation bypasses the CREATE opcode's static-context check.
519    if ccx.is_static {
520        return Err(crate::Error::from(Bytes::new()));
521    }
522
523    let mut bytecode = get_artifact_code(&ccx.state.core, path, false)?.to_vec();
524    if let Some(args) = constructor_args {
525        bytecode.extend_from_slice(args);
526    }
527
528    let depth = ccx.depth();
529
530    // The nested EVM executes the synthetic create one level deeper, so resolve the prank at the
531    // original depth just as the native create inspector would.
532    let prank_changes =
533        ccx.state.get_prank(depth).and_then(|prank| prank.changes_for(depth, ccx.caller));
534    let caller = prank_changes.as_ref().and_then(|changes| changes.caller).unwrap_or(ccx.caller);
535
536    let value = value.unwrap_or(U256::ZERO);
537    let kind = if salt.is_some() { MessageKind::Create2 } else { MessageKind::Create };
538    let salt = salt.map(B256::from).unwrap_or_default();
539    let init_code_len = bytecode.len();
540
541    // Charge the caller as the CREATE and CREATE2 opcodes would, before changing any state.
542    let version = ccx.evm_env().version;
543    let gas_params = &version.gas_params;
544    let mut cost = if kind == MessageKind::Create2 {
545        gas_params.create2_cost(init_code_len)
546    } else {
547        gas_params.get(GasId::Create)
548    };
549    if version.feature(EvmFeatures::EIP3860) {
550        if init_code_len > version.max_initcode_size {
551            ccx.gas.spend_all();
552            return Err(fmt_err!("initcode size limit exceeded"));
553        }
554        cost = cost.saturating_add(gas_params.initcode_cost(init_code_len));
555    }
556    let create_state_gas = gas_params.create_state_gas();
557    if ccx.gas.spend(cost).is_err() {
558        ccx.gas.spend_all();
559        return Err(fmt_err!("out of gas"));
560    }
561
562    // EIP-8037: charge the account creation state gas if the creation can proceed and the
563    // destination is empty.
564    let mut charged_create_state_gas = false;
565    if version.feature(EvmFeatures::EIP8037) {
566        let (balance, nonce) = {
567            let account = ccx.evm.state_mut().account(&caller)?;
568            (account.balance(), account.nonce())
569        };
570        if balance >= value && nonce != u64::MAX {
571            let created_address = derive_create_destination(kind, &caller, &salt, &bytecode, nonce);
572            if ccx
573                .evm
574                .state_mut()
575                .account(&created_address)?
576                .is_empty_for_new_account_gas(version.features)
577            {
578                if ccx.gas.spend_state(create_state_gas).is_err() {
579                    ccx.gas.spend_all();
580                    return Err(fmt_err!("out of gas"));
581                }
582                charged_create_state_gas = true;
583            }
584        }
585    }
586
587    // The call to the cheatcode already kept back 1/64 of the caller's gas, as the CREATE opcode
588    // would, so forward all of the remaining gas to the create frame.
589    let gas_limit = ccx.gas.remaining();
590    // This cannot fail as it does not exceed `remaining`.
591    let _ = ccx.gas.spend(gas_limit);
592
593    // Broadcast the synthetic create only if it was requested by the broadcaster at the broadcast
594    // depth, as for native creates.
595    if let Some(broadcast) = &mut ccx.state.broadcast
596        && depth == broadcast.depth
597        && ccx.caller == broadcast.original_caller
598    {
599        broadcast.deploy_from_code = true;
600    }
601
602    if let Some(changes) = prank_changes {
603        if let Some(new_origin) = changes.origin {
604            ccx.state.set_origin(ccx.evm.tx_env().origin, new_origin);
605        }
606        if let Some(used) = changes.used {
607            ccx.state.pranks.insert(depth, used);
608        }
609    }
610
611    let input = Bytes::from(bytecode);
612    let message = MessageFor::<FEN> {
613        kind,
614        depth: u16::try_from(depth + 1).unwrap_or(u16::MAX),
615        gas_limit,
616        reservoir: ccx.gas.reservoir(),
617        caller,
618        code: Bytecode::new_raw(input.clone()),
619        input: input.into(),
620        value,
621        salt,
622        ..Default::default()
623    };
624    // Restore the outer marker afterwards, as constructors can call `deployCode` too.
625    let outer_deploy_code_depth = ccx.state.deploy_code_depth.replace(depth);
626    let outer_create_state_gas = mem::replace(
627        &mut ccx.state.deploy_code_create_state_gas,
628        if charged_create_state_gas { create_state_gas } else { 0 },
629    );
630    let outer_output = ccx.state.deploy_code_output.take();
631    let outcome = exec_create(executor, message, ccx);
632    ccx.state.deploy_code_depth = outer_deploy_code_depth;
633    ccx.state.deploy_code_create_state_gas = outer_create_state_gas;
634    // A create that runs isolated as the root of its own nested transaction returns no data from
635    // a failed code deposit.
636    let returned = mem::replace(&mut ccx.state.deploy_code_output, outer_output)
637        .filter(|(_, isolated)| *isolated == ccx.state.in_isolation_context)
638        .map(|(output, _)| output);
639
640    // Clear the flag in case the synthetic create was not broadcast, and end a single-call
641    // broadcast at the original depth as native create cleanup would.
642    if let Some(broadcast) = &mut ccx.state.broadcast {
643        broadcast.deploy_from_code = false;
644        if broadcast.single_call && depth == broadcast.depth {
645            let original_origin = broadcast.original_origin;
646            ccx.state.broadcast = None;
647            ccx.state.set_origin(ccx.evm.tx_env().origin, original_origin);
648        }
649    }
650
651    // Restore the prank state at the original depth as native create cleanup would.
652    if let Some(prank) = ccx.state.get_prank(depth).copied()
653        && depth == prank.depth
654    {
655        ccx.state.set_origin(ccx.evm.tx_env().origin, prank.prank_origin);
656        if prank.single_call {
657            ccx.state.pranks.remove(&depth);
658        }
659    }
660
661    let mut outcome = outcome?;
662    // Return the create frame's gas to the caller as the CREATE opcode does. Settling is a no-op
663    // for a result the EVM already settled.
664    outcome.gas.settle_gas(outcome.stop);
665    ccx.gas.merge_child_gas(outcome.gas, outcome.stop);
666    // Refund the upfront state charge if the account was not created, as the CREATE opcode does.
667    if charged_create_state_gas && (outcome.created_address.is_none() || !outcome.is_success()) {
668        ccx.gas.refill_reservoir(create_state_gas);
669    }
670
671    if !outcome.is_success() {
672        // A constructor whose returned code could not be deposited reverts with it.
673        return Err(crate::Error::from(returned.unwrap_or(outcome.output)));
674    }
675
676    let address = outcome.created_address.ok_or_else(|| fmt_err!("contract creation failed"))?;
677
678    Ok(address.abi_encode())
679}
680
681/// Resolved location of an artifact referenced by a cheatcode path argument.
682enum ArtifactSource<'a> {
683    /// The artifact was matched in the in-memory `available_artifacts` list.
684    InMemory(&'a ContractData),
685    /// The artifact must be read from the given path on disk.
686    Disk(PathBuf),
687}
688
689/// Resolves a cheatcode artifact reference to its source.
690///
691/// Can parse the following input formats:
692/// - `path/to/artifact.json`
693/// - `path/to/contract.sol`
694/// - `path/to/contract.sol:ContractName`
695/// - `path/to/contract.sol:ContractName:0.8.23`
696/// - `path/to/contract.sol:ContractName:profile`
697/// - `path/to/contract.sol:0.8.23`
698/// - `path/to/contract.sol:profile`
699/// - `ContractName`
700/// - `ContractName:0.8.23`
701/// - `ContractName:profile`
702fn get_artifact_source<'a>(state: &'a CheatcodesCore, path: &str) -> Result<ArtifactSource<'a>> {
703    if path.ends_with(".json") {
704        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
705        return Ok(ArtifactSource::Disk(path));
706    }
707
708    let artifacts =
709        state.config.available_artifacts.as_ref().or(state.config.artifact_lookup.as_ref());
710    let resolve_source = |file: PathBuf| {
711        let cwd = state
712            .config
713            .running_artifact
714            .as_ref()
715            .and_then(|artifact| artifact.source.parent())
716            .unwrap_or(&state.config.paths.root);
717        let relative_cwd = cwd.strip_prefix(&state.config.paths.root).unwrap_or(cwd);
718        let has_matching_remapping = state.config.paths.remappings.iter().any(|remapping| {
719            remapping.context.as_ref().is_none_or(|context| relative_cwd.starts_with(context))
720                && file.strip_prefix(&remapping.name).is_ok()
721        });
722
723        if has_matching_remapping {
724            state.config.paths.resolve_library_import(cwd, &file).map_or(file, |resolved| {
725                resolved.strip_prefix(&state.config.paths.root).unwrap_or(&resolved).to_path_buf()
726            })
727        } else {
728            file
729        }
730    };
731    let exact_identifier = path
732        .rsplit_once(':')
733        .map(|(source, contract)| (resolve_source(PathBuf::from(source)), contract))
734        .filter(|(source, contract)| {
735            artifacts.into_iter().flat_map(|artifacts| artifacts.iter()).any(|(id, _)| {
736                id.source == *source
737                    && id.name.split('.').next().is_some_and(|name| name == *contract)
738            })
739        });
740
741    let parsed = match parse_artifact_path(path) {
742        Ok(parsed) => parsed,
743        Err(_) if exact_identifier.is_some() => {
744            ParsedArtifactPath { file: None, contract_name: None, version: None, profile: None }
745        }
746        Err(error) => return Err(fmt_err!("failed to parse artifact path: {error}")),
747    };
748    let ParsedArtifactPath { file, contract_name, version, profile } = parsed;
749    let file = file.map(resolve_source);
750
751    // Use the artifact lookup if present.
752    if let Some(artifacts) = artifacts {
753        let ambiguous_file_profile =
754            file.is_some() && version.is_none() && profile.is_none() && contract_name.is_some();
755        let filter_artifacts = |treat_ambiguous_as_profile: bool| -> Vec<_> {
756            artifacts
757                .iter()
758                .filter(|(id, _)| {
759                    if let Some((source, contract)) = &exact_identifier {
760                        return id.source == *source
761                            && id.name.split('.').next().is_some_and(|name| name == *contract);
762                    }
763
764                    // name might be in the form of "Counter.0.8.23"
765                    let id_name = id.name.split('.').next().unwrap();
766
767                    if let Some(path) = &file
768                        && !id.source.ends_with(path)
769                    {
770                        return false;
771                    }
772                    if let Some(ref version) = version
773                        && (id.version.minor != version.minor
774                            || id.version.major != version.major
775                            || id.version.patch != version.patch)
776                    {
777                        return false;
778                    }
779                    if let Some(profile) = profile
780                        && id.profile != profile
781                    {
782                        return false;
783                    }
784                    if let Some(name) = contract_name {
785                        if treat_ambiguous_as_profile && ambiguous_file_profile {
786                            return id.profile == name;
787                        }
788
789                        return id_name == name;
790                    }
791
792                    true
793                })
794                .collect()
795        };
796
797        let mut filtered = filter_artifacts(false);
798        if filtered.is_empty() && ambiguous_file_profile {
799            filtered = filter_artifacts(true);
800        }
801
802        let artifact = match &filtered[..] {
803            [] => None,
804            [artifact] => Some(Ok(*artifact)),
805            filtered => {
806                let mut filtered = filtered.to_vec();
807                // If we know the current script/test contract solc version, try to filter by it
808                Some(
809                    state
810                        .config
811                        .running_artifact
812                        .as_ref()
813                        .and_then(|running| {
814                            // Only filter by running version if user did NOT specify a version
815                            if exact_identifier.is_some() || version.is_none() {
816                                filtered.retain(|(id, _)| id.version == running.version);
817
818                                // Return artifact if only one matched
819                                if filtered.len() == 1 {
820                                    return Some(filtered[0]);
821                                }
822                            }
823
824                            // Only filter by running profile if user did NOT specify a profile
825                            if exact_identifier.is_some() || profile.is_none() {
826                                filtered.retain(|(id, _)| id.profile == running.profile);
827
828                                return (filtered.len() == 1).then(|| filtered[0]);
829                            }
830
831                            None
832                        })
833                        .ok_or_else(|| fmt_err!("multiple matching artifacts found")),
834                )
835            }
836        };
837
838        if let Some(artifact) = artifact {
839            return Ok(ArtifactSource::InMemory(artifact?.1));
840        }
841    }
842
843    // Fallback: construct path manually when no artifacts list or no match found
844    let path_in_artifacts = match (file.map(|f| f.to_string_lossy().to_string()), contract_name) {
845        (Some(file), Some(contract_name)) => PathBuf::from(format!("{file}/{contract_name}.json")),
846        (None, Some(contract_name)) => {
847            PathBuf::from(format!("{contract_name}.sol/{contract_name}.json"))
848        }
849        (Some(file), None) => {
850            let name = file.replace(".sol", "");
851            PathBuf::from(format!("{file}/{name}.json"))
852        }
853        _ => bail!("invalid artifact path"),
854    };
855
856    let path = state.config.paths.artifacts.join(path_in_artifacts);
857    let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
858    Ok(ArtifactSource::Disk(path))
859}
860
861/// Reads an artifact JSON file, mapping I/O errors to a helpful message when the
862/// lookup fell through the in-memory artifacts list.
863fn read_artifact_file(state: &CheatcodesCore, path: &Path) -> Result<String> {
864    fs::read_to_string(path).map_err(|e| {
865        if state.config.available_artifacts.is_some() {
866            fmt_err!("no matching artifact found")
867        } else {
868            e.into()
869        }
870    })
871}
872
873/// Returns the bytecode from a JSON artifact file.
874///
875/// See [`get_artifact_source`] for the supported path formats.
876///
877/// This function is safe to use with contracts that have library dependencies.
878/// `alloy_json_abi::ContractObject` validates bytecode during JSON parsing and will
879/// reject artifacts with unlinked library placeholders.
880fn get_artifact_code(state: &CheatcodesCore, path: &str, deployed: bool) -> Result<Bytes> {
881    let maybe_bytecode = match get_artifact_source(state, path)? {
882        ArtifactSource::InMemory(data) => {
883            if deployed { data.deployed_bytecode() } else { data.bytecode() }.cloned()
884        }
885        ArtifactSource::Disk(path) => {
886            let data = read_artifact_file(state, &path)?;
887            let artifact = serde_json::from_str::<ContractObject>(&data)?;
888            if deployed { artifact.deployed_bytecode } else { artifact.bytecode }
889        }
890    };
891    maybe_bytecode.ok_or_else(|| fmt_err!("no bytecode for contract; is it abstract or unlinked?"))
892}
893
894impl Cheatcode for ffiCall {
895    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
896        let Self { commandInput: input } = self;
897        let stdout = ffi_stdout(state, input)?;
898        Ok(decode_ffi_stdout(&stdout).abi_encode())
899    }
900}
901
902impl Cheatcode for ffiUintCall {
903    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
904        let Self { commandInput: input } = self;
905        parse(&ffi_stdout(state, input)?, &DynSolType::Uint(256))
906    }
907}
908
909impl Cheatcode for ffiStringCall {
910    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
911        let Self { commandInput: input } = self;
912        Ok(ffi_stdout(state, input)?.abi_encode())
913    }
914}
915
916impl Cheatcode for ffiBytesCall {
917    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
918        let Self { commandInput: input } = self;
919        let stdout = ffi_stdout(state, input)?;
920        Ok(hex::decode(&stdout)
921            .map_err(|err| fmt_err!("failed parsing ffi stdout as bytes: {err}"))?
922            .abi_encode())
923    }
924}
925
926impl Cheatcode for tryFfiCall {
927    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
928        let Self { commandInput: input } = self;
929        ffi(state, input).map(|res| res.abi_encode())
930    }
931}
932
933impl Cheatcode for promptCall {
934    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
935        let Self { promptText: text } = self;
936        prompt(state, text, prompt_input).map(|res| res.abi_encode())
937    }
938}
939
940impl Cheatcode for promptSecretCall {
941    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
942        let Self { promptText: text } = self;
943        prompt(state, text, prompt_password).map(|res| res.abi_encode())
944    }
945}
946
947impl Cheatcode for promptSecretUintCall {
948    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
949        let Self { promptText: text } = self;
950        parse(&prompt(state, text, prompt_password)?, &DynSolType::Uint(256))
951    }
952}
953
954impl Cheatcode for promptAddressCall {
955    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
956        let Self { promptText: text } = self;
957        parse(&prompt(state, text, prompt_input)?, &DynSolType::Address)
958    }
959}
960
961impl Cheatcode for promptUintCall {
962    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
963        let Self { promptText: text } = self;
964        parse(&prompt(state, text, prompt_input)?, &DynSolType::Uint(256))
965    }
966}
967
968pub(super) fn write_file(state: &CheatcodesCore, path: &Path, contents: &[u8]) -> Result {
969    let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
970    // write access to foundry.toml is not allowed
971    state.config.ensure_not_foundry_toml(&path)?;
972
973    if state.fs_commit {
974        fs::locked_write(path, contents)?;
975    }
976
977    Ok(Default::default())
978}
979
980fn read_dir(state: &CheatcodesCore, path: &Path, max_depth: u64, follow_links: bool) -> Result {
981    let root = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
982    let paths: Vec<DirEntry> = WalkDir::new(root)
983        .min_depth(1)
984        .max_depth(max_depth.try_into().unwrap_or(usize::MAX))
985        .follow_links(follow_links)
986        .contents_first(false)
987        .same_file_system(true)
988        .sort_by_file_name()
989        .into_iter()
990        .map(|entry| match entry {
991            Ok(entry) => DirEntry {
992                errorMessage: String::new(),
993                path: entry.path().display().to_string(),
994                depth: entry.depth() as u64,
995                isDir: entry.file_type().is_dir(),
996                isSymlink: entry.path_is_symlink(),
997            },
998            Err(e) => DirEntry {
999                errorMessage: e.to_string(),
1000                path: e.path().map(|p| p.display().to_string()).unwrap_or_default(),
1001                depth: e.depth() as u64,
1002                isDir: false,
1003                isSymlink: false,
1004            },
1005        })
1006        .collect();
1007    Ok(paths.abi_encode())
1008}
1009
1010fn ffi(state: &CheatcodesCore, input: &[String]) -> Result<FfiResult> {
1011    let output = ffi_command(state, input)?;
1012
1013    let stdout = String::from_utf8(output.stdout)?;
1014    let stdout = stdout.trim();
1015    Ok(FfiResult {
1016        exitCode: output.status.code().unwrap_or(69),
1017        stdout: decode_ffi_stdout(stdout),
1018        stderr: output.stderr.into(),
1019    })
1020}
1021
1022fn ffi_stdout(state: &CheatcodesCore, input: &[String]) -> Result<String> {
1023    let output = ffi_command(state, input)?;
1024    let stdout = String::from_utf8(output.stdout)?;
1025    if !output.status.success() {
1026        return Err(fmt_err!(
1027            "ffi command {:?} exited with code {}. stderr: {}",
1028            input,
1029            output.status.code().unwrap_or(69),
1030            String::from_utf8_lossy(&output.stderr)
1031        ));
1032    }
1033    if !output.stderr.is_empty() {
1034        let stderr = String::from_utf8_lossy(&output.stderr);
1035        warn!(target: "cheatcodes", ?input, ?stderr, "ffi command wrote to stderr");
1036    }
1037    Ok(stdout.trim().to_string())
1038}
1039
1040fn decode_ffi_stdout(stdout: &str) -> Bytes {
1041    hex::decode(stdout).unwrap_or_else(|_| stdout.as_bytes().to_vec()).into()
1042}
1043
1044fn ffi_command(state: &CheatcodesCore, input: &[String]) -> Result<std::process::Output> {
1045    ensure!(
1046        state.config.ffi,
1047        "FFI is disabled; add the `--ffi` flag to allow tests to call external commands"
1048    );
1049    ensure!(!input.is_empty() && !input[0].is_empty(), "can't execute empty command");
1050    let mut cmd = Command::new(&input[0]);
1051    cmd.args(&input[1..]);
1052
1053    debug!(target: "cheatcodes", ?cmd, "invoking ffi");
1054
1055    cmd.current_dir(&state.config.root)
1056        .output()
1057        .map_err(|err| fmt_err!("failed to execute command {cmd:?}: {err}"))
1058}
1059
1060fn prompt_input(prompt_text: &str) -> Result<String, dialoguer::Error> {
1061    Input::new().allow_empty(true).with_prompt(prompt_text).interact_text()
1062}
1063
1064fn prompt_password(prompt_text: &str) -> Result<String, dialoguer::Error> {
1065    Password::new().with_prompt(prompt_text).interact()
1066}
1067
1068fn prompt(
1069    state: &CheatcodesCore,
1070    prompt_text: &str,
1071    input: fn(&str) -> Result<String, dialoguer::Error>,
1072) -> Result<String> {
1073    let text_clone = prompt_text.to_string();
1074    let timeout = state.config.prompt_timeout;
1075    let (tx, rx) = mpsc::channel();
1076
1077    thread::spawn(move || {
1078        let _ = tx.send(input(&text_clone));
1079    });
1080
1081    match rx.recv_timeout(timeout) {
1082        Ok(res) => res.map_err(|err| {
1083            let _ = sh_println!();
1084            err.to_string().into()
1085        }),
1086        Err(_) => {
1087            let _ = sh_eprintln!();
1088            Err("Prompt timed out".into())
1089        }
1090    }
1091}
1092
1093impl Cheatcode for getBroadcastCall {
1094    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
1095        let Self { contractName, chainId, txType } = self;
1096
1097        let latest_broadcast = latest_broadcast::<AnyNetwork>(
1098            contractName,
1099            *chainId,
1100            &state.config.broadcast,
1101            vec![map_broadcast_tx_type(*txType)],
1102        )?;
1103
1104        Ok(latest_broadcast.abi_encode())
1105    }
1106}
1107
1108impl Cheatcode for getBroadcasts_0Call {
1109    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
1110        let Self { contractName, chainId, txType } = self;
1111
1112        let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?
1113            .with_tx_type(map_broadcast_tx_type(*txType));
1114
1115        let broadcasts = reader.read::<AnyNetwork>()?;
1116
1117        let summaries = broadcasts
1118            .into_iter()
1119            .flat_map(|broadcast| {
1120                let results = reader.into_tx_receipts(broadcast);
1121                parse_broadcast_results(results)
1122            })
1123            .collect::<Vec<_>>();
1124
1125        Ok(summaries.abi_encode())
1126    }
1127}
1128
1129impl Cheatcode for getBroadcasts_1Call {
1130    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
1131        let Self { contractName, chainId } = self;
1132
1133        let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?;
1134
1135        let broadcasts = reader.read::<AnyNetwork>()?;
1136
1137        let summaries = broadcasts
1138            .into_iter()
1139            .flat_map(|broadcast| {
1140                let results = reader.into_tx_receipts(broadcast);
1141                parse_broadcast_results(results)
1142            })
1143            .collect::<Vec<_>>();
1144
1145        Ok(summaries.abi_encode())
1146    }
1147}
1148
1149impl Cheatcode for getDeployment_0Call {
1150    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
1151        let Self { contractName } = self;
1152        let chain_id = ccx.chain_id();
1153
1154        let latest_broadcast = latest_broadcast::<AnyNetwork>(
1155            contractName,
1156            chain_id,
1157            &ccx.state.core.config.broadcast,
1158            vec![CallKind::Create, CallKind::Create2],
1159        )?;
1160
1161        Ok(latest_broadcast.contractAddress.abi_encode())
1162    }
1163}
1164
1165impl Cheatcode for getDeployment_1Call {
1166    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
1167        let Self { contractName, chainId } = self;
1168
1169        let latest_broadcast = latest_broadcast::<AnyNetwork>(
1170            contractName,
1171            *chainId,
1172            &state.config.broadcast,
1173            vec![CallKind::Create, CallKind::Create2],
1174        )?;
1175
1176        Ok(latest_broadcast.contractAddress.abi_encode())
1177    }
1178}
1179
1180impl Cheatcode for getDeploymentsCall {
1181    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
1182        let Self { contractName, chainId } = self;
1183
1184        let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?
1185            .with_tx_type(CallKind::Create)
1186            .with_tx_type(CallKind::Create2);
1187
1188        let broadcasts = reader.read::<AnyNetwork>()?;
1189
1190        let summaries = broadcasts
1191            .into_iter()
1192            .flat_map(|broadcast| {
1193                let results = reader.into_tx_receipts(broadcast);
1194                parse_broadcast_results(results)
1195            })
1196            .collect::<Vec<_>>();
1197
1198        let deployed_addresses =
1199            summaries.into_iter().map(|summary| summary.contractAddress).collect::<Vec<_>>();
1200
1201        Ok(deployed_addresses.abi_encode())
1202    }
1203}
1204
1205fn map_broadcast_tx_type(tx_type: BroadcastTxType) -> CallKind {
1206    match tx_type {
1207        BroadcastTxType::Call => CallKind::Call,
1208        BroadcastTxType::Create => CallKind::Create,
1209        BroadcastTxType::Create2 => CallKind::Create2,
1210        _ => unreachable!("invalid tx type"),
1211    }
1212}
1213
1214fn parse_broadcast_results<N: Network>(
1215    results: Vec<(TransactionWithMetadata<N>, N::ReceiptResponse)>,
1216) -> Vec<BroadcastTxSummary> {
1217    results
1218        .into_iter()
1219        .map(|(tx, receipt)| BroadcastTxSummary {
1220            txHash: receipt.transaction_hash(),
1221            blockNumber: receipt.block_number().unwrap_or_default(),
1222            txType: match tx.call_kind {
1223                CallKind::Call => BroadcastTxType::Call,
1224                CallKind::Create => BroadcastTxType::Create,
1225                CallKind::Create2 => BroadcastTxType::Create2,
1226                _ => unreachable!("invalid tx type"),
1227            },
1228            contractAddress: tx.contract_address.unwrap_or_default(),
1229            success: receipt.status(),
1230        })
1231        .collect()
1232}
1233
1234fn latest_broadcast<N: Network>(
1235    contract_name: &String,
1236    chain_id: u64,
1237    broadcast_path: &Path,
1238    filters: Vec<CallKind>,
1239) -> Result<BroadcastTxSummary>
1240where
1241    N::TxEnvelope: for<'d> serde::Deserialize<'d>,
1242{
1243    let mut reader = BroadcastReader::new(contract_name.clone(), chain_id, broadcast_path)?;
1244
1245    for filter in filters {
1246        reader = reader.with_tx_type(filter);
1247    }
1248
1249    let broadcast = reader.read_latest::<N>()?;
1250
1251    let results = reader.into_tx_receipts(broadcast);
1252
1253    let summaries = parse_broadcast_results(results);
1254
1255    summaries
1256        .first()
1257        .ok_or_else(|| fmt_err!("no deployment found for {contract_name} on chain {chain_id}"))
1258        .cloned()
1259}
1260
1261#[cfg(test)]
1262mod tests {
1263    use super::*;
1264    use crate::CheatsConfig;
1265    use alloy_primitives::{Bloom, address, b256};
1266    use foundry_common::ContractsByArtifact;
1267    use foundry_compilers::{
1268        ArtifactId,
1269        artifacts::{
1270            BytecodeObject, CompactBytecode, CompactContractBytecode, remappings::Remapping,
1271        },
1272    };
1273    use std::{env, fs as stdfs, str::FromStr, sync::Arc};
1274    use tempfile::TempDir;
1275
1276    fn cheats() -> CheatcodesCore {
1277        let config = CheatsConfig {
1278            ffi: true,
1279            root: PathBuf::from(&env!("CARGO_MANIFEST_DIR")),
1280            ..Default::default()
1281        };
1282        CheatcodesCore::new(Arc::new(config))
1283    }
1284
1285    #[test]
1286    fn test_ffi_hex() {
1287        let msg = b"gm";
1288        let cheats = cheats();
1289        let args = ["echo".to_string(), hex::encode(msg)];
1290        let output = ffi(&cheats, &args).unwrap();
1291        assert_eq!(output.stdout, Bytes::from(msg));
1292    }
1293
1294    #[test]
1295    fn test_ffi_string() {
1296        let msg = "gm";
1297        let cheats = cheats();
1298        let args = ["echo".to_string(), msg.to_string()];
1299        let output = ffi(&cheats, &args).unwrap();
1300        assert_eq!(output.stdout, Bytes::from(msg.as_bytes()));
1301    }
1302
1303    #[test]
1304    fn test_ffi_fails_on_error_code() {
1305        let mut cheats = cheats();
1306
1307        // Use a command that is guaranteed to fail with a non-zero exit code on any platform.
1308        #[cfg(unix)]
1309        let args = vec!["false".to_string()];
1310        #[cfg(windows)]
1311        let args = vec!["cmd".to_string(), "/c".to_string(), "exit 1".to_string()];
1312
1313        let result = Cheatcode::apply_context(&ffiCall { commandInput: args }, &mut cheats);
1314
1315        // Assert that the cheatcode returned an error.
1316        assert!(result.is_err(), "Expected ffi cheatcode to fail, but it succeeded");
1317
1318        // Assert that the error message contains the expected information.
1319        let err_msg = result.unwrap_err().to_string();
1320        assert!(
1321            err_msg.contains("exited with code 1"),
1322            "Error message did not contain exit code: {err_msg}"
1323        );
1324    }
1325
1326    #[test]
1327    fn test_artifact_parsing() {
1328        let s = include_str!("../../evm/test-data/solc-obj.json");
1329        let artifact: ContractObject = serde_json::from_str(s).unwrap();
1330        assert!(artifact.bytecode.is_some());
1331
1332        let artifact: ContractObject = serde_json::from_str(s).unwrap();
1333        assert!(artifact.deployed_bytecode.is_some());
1334    }
1335
1336    #[test]
1337    fn test_alloy_json_abi_rejects_unlinked_bytecode() {
1338        let artifact_json = r#"{
1339            "abi": [],
1340            "bytecode": "0x73__$987e73aeca5e61ce83e4cb0814d87beda9$__63baf2f868"
1341        }"#;
1342
1343        let result: Result<ContractObject, _> = serde_json::from_str(artifact_json);
1344        assert!(result.is_err(), "should reject unlinked bytecode with placeholders");
1345        let err = result.unwrap_err().to_string();
1346        assert!(err.contains("expected bytecode, found unlinked bytecode with placeholder"));
1347    }
1348
1349    #[test]
1350    fn test_parse_artifact_path_file_only() {
1351        let parsed = super::parse_artifact_path("path/to/Contract.sol").unwrap();
1352        assert_eq!(parsed.file, Some(PathBuf::from("path/to/Contract.sol")));
1353        assert_eq!(parsed.contract_name, None);
1354        assert_eq!(parsed.version, None);
1355        assert_eq!(parsed.profile, None);
1356    }
1357
1358    #[test]
1359    fn test_parse_artifact_path_windows_drive() {
1360        for file in [
1361            "C:/project/src/Contract.sol",
1362            r"C:\project\src\Contract.sol",
1363            r"\\?\C:\project\src\Contract.sol",
1364            r"\\server\share\Contract.sol",
1365        ] {
1366            for (suffix, contract_name, version, profile) in [
1367                ("", None, None, None),
1368                (":MyContract", Some("MyContract"), None, None),
1369                (":0.8.23", None, Some(Version::new(0, 8, 23)), None),
1370                (":MyContract:0.8.23", Some("MyContract"), Some(Version::new(0, 8, 23)), None),
1371                (":MyContract:optimized", Some("MyContract"), None, Some("optimized")),
1372            ] {
1373                let input = format!("{file}{suffix}");
1374                assert_eq!(
1375                    parse_artifact_path(&input).unwrap(),
1376                    ParsedArtifactPath {
1377                        file: Some(PathBuf::from(file)),
1378                        contract_name,
1379                        version,
1380                        profile,
1381                    },
1382                    "{input}"
1383                );
1384            }
1385        }
1386
1387        // A one-letter contract name must still allow version and profile suffixes.
1388        assert_eq!(parse_artifact_path("C:0.8.23").unwrap().version, Some(Version::new(0, 8, 23)));
1389        assert_eq!(parse_artifact_path("C:optimized").unwrap().profile, Some("optimized"));
1390    }
1391
1392    #[test]
1393    fn test_parse_artifact_path_file_and_contract() {
1394        let parsed = super::parse_artifact_path("path/to/Contract.sol:MyContract").unwrap();
1395        assert_eq!(parsed.file, Some(PathBuf::from("path/to/Contract.sol")));
1396        assert_eq!(parsed.contract_name, Some("MyContract"));
1397        assert_eq!(parsed.version, None);
1398        assert_eq!(parsed.profile, None);
1399    }
1400
1401    #[test]
1402    fn test_parse_artifact_path_file_contract_version() {
1403        let parsed = super::parse_artifact_path("path/to/Contract.sol:MyContract:0.8.23").unwrap();
1404        assert_eq!(parsed.file, Some(PathBuf::from("path/to/Contract.sol")));
1405        assert_eq!(parsed.contract_name, Some("MyContract"));
1406        assert_eq!(parsed.version, Some(semver::Version::new(0, 8, 23)));
1407        assert_eq!(parsed.profile, None);
1408    }
1409
1410    #[test]
1411    fn test_parse_artifact_path_file_contract_profile() {
1412        let parsed =
1413            super::parse_artifact_path("path/to/Contract.sol:MyContract:optimized").unwrap();
1414        assert_eq!(parsed.file, Some(PathBuf::from("path/to/Contract.sol")));
1415        assert_eq!(parsed.contract_name, Some("MyContract"));
1416        assert_eq!(parsed.version, None);
1417        assert_eq!(parsed.profile, Some("optimized"));
1418    }
1419
1420    #[test]
1421    fn test_parse_artifact_path_file_and_version() {
1422        let parsed = super::parse_artifact_path("path/to/Contract.sol:0.8.18").unwrap();
1423        assert_eq!(parsed.file, Some(PathBuf::from("path/to/Contract.sol")));
1424        assert_eq!(parsed.contract_name, None);
1425        assert_eq!(parsed.version, Some(semver::Version::new(0, 8, 18)));
1426        assert_eq!(parsed.profile, None);
1427    }
1428
1429    #[test]
1430    fn test_parse_artifact_path_file_and_profile() {
1431        // The parser keeps the two-part file form ambiguous. Artifact lookup can resolve this
1432        // segment as a profile when no contract name matches.
1433        let parsed = super::parse_artifact_path("Contract.sol:paris").unwrap();
1434        assert_eq!(parsed.file, Some(PathBuf::from("Contract.sol")));
1435        assert_eq!(parsed.contract_name, Some("paris"));
1436        assert_eq!(parsed.version, None);
1437        assert_eq!(parsed.profile, None);
1438    }
1439
1440    fn test_artifact(
1441        source: &str,
1442        name: &str,
1443        profile: &str,
1444        bytecode: Bytes,
1445    ) -> (ArtifactId, CompactContractBytecode) {
1446        (
1447            ArtifactId {
1448                path: PathBuf::from(format!("{source}/{name}.json")),
1449                name: name.to_owned(),
1450                source: PathBuf::from(source),
1451                version: Version::new(0, 8, 30),
1452                build_id: String::new(),
1453                profile: profile.to_owned(),
1454            },
1455            CompactContractBytecode {
1456                abi: Some(Default::default()),
1457                bytecode: Some(CompactBytecode {
1458                    object: BytecodeObject::Bytecode(bytecode),
1459                    source_map: None,
1460                    link_references: Default::default(),
1461                }),
1462                deployed_bytecode: None,
1463            },
1464        )
1465    }
1466
1467    #[test]
1468    fn test_get_artifact_code_resolves_file_profile_ambiguity() {
1469        let default_bytecode = Bytes::from_static(&[0x60, 0x01]);
1470        let paris_bytecode = Bytes::from_static(&[0x60, 0x02]);
1471        let source = "src/GetCodeProfile.t.sol";
1472        let artifacts = ContractsByArtifact::new([
1473            test_artifact(source, "GetCodeProfile", "default", default_bytecode),
1474            test_artifact(source, "GetCodeProfile", "paris", paris_bytecode.clone()),
1475        ]);
1476        let config = CheatsConfig {
1477            available_artifacts: Some(artifacts),
1478            root: PathBuf::from(&env!("CARGO_MANIFEST_DIR")),
1479            ..Default::default()
1480        };
1481        let cheats = CheatcodesCore::new(Arc::new(config));
1482
1483        let bytecode =
1484            super::get_artifact_code(&cheats, "src/GetCodeProfile.t.sol:paris", false).unwrap();
1485
1486        assert_eq!(bytecode, paris_bytecode);
1487    }
1488
1489    #[test]
1490    fn test_get_artifact_code_exact_colon_path_uses_running_profile() {
1491        let default_bytecode = Bytes::from_static(&[0x60, 0x01]);
1492        let optimized_bytecode = Bytes::from_static(&[0x60, 0x02]);
1493        let versioned_bytecode = Bytes::from_static(&[0x60, 0x03]);
1494        let source = "src/Colon:Path.sol";
1495        let default = test_artifact(source, "Target", "default", default_bytecode);
1496        let optimized =
1497            test_artifact(source, "Target.optimized", "optimized", optimized_bytecode.clone());
1498        let mut versioned = test_artifact(
1499            source,
1500            "Target.0.8.29.optimized",
1501            "optimized",
1502            versioned_bytecode.clone(),
1503        );
1504        versioned.0.version = Version::new(0, 8, 29);
1505        let artifacts = ContractsByArtifact::new([default, optimized, versioned]);
1506        for (patch, expected) in [(30, optimized_bytecode), (29, versioned_bytecode)] {
1507            let running_artifact = ArtifactId {
1508                source: PathBuf::from("test/Runner.t.sol"),
1509                name: "Runner".to_owned(),
1510                path: PathBuf::from("test/Runner.t.sol/Runner.json"),
1511                version: Version::new(0, 8, patch),
1512                build_id: String::new(),
1513                profile: "optimized".to_owned(),
1514            };
1515            let config = CheatsConfig {
1516                available_artifacts: Some(artifacts.clone()),
1517                running_artifact: Some(running_artifact),
1518                root: PathBuf::from(&env!("CARGO_MANIFEST_DIR")),
1519                ..Default::default()
1520            };
1521            let cheats = CheatcodesCore::new(Arc::new(config));
1522            let bytecode =
1523                super::get_artifact_code(&cheats, "src/Colon:Path.sol:Target", false).unwrap();
1524            assert_eq!(bytecode, expected);
1525        }
1526    }
1527
1528    #[test]
1529    fn test_get_artifact_code_prefers_contract_name_over_file_profile_ambiguity() {
1530        let profile_bytecode = Bytes::from_static(&[0x60, 0x02]);
1531        let contract_bytecode = Bytes::from_static(&[0x60, 0x03]);
1532        let source = "src/GetCodeProfile.t.sol";
1533        let artifacts = ContractsByArtifact::new([
1534            test_artifact(source, "GetCodeProfile", "paris", profile_bytecode),
1535            test_artifact(source, "paris", "default", contract_bytecode.clone()),
1536        ]);
1537        let config = CheatsConfig {
1538            available_artifacts: Some(artifacts),
1539            root: PathBuf::from(&env!("CARGO_MANIFEST_DIR")),
1540            ..Default::default()
1541        };
1542        let cheats = CheatcodesCore::new(Arc::new(config));
1543
1544        let bytecode =
1545            super::get_artifact_code(&cheats, "src/GetCodeProfile.t.sol:paris", false).unwrap();
1546
1547        assert_eq!(bytecode, contract_bytecode);
1548    }
1549
1550    #[test]
1551    fn test_get_artifact_code_resolves_remapping() {
1552        let bytecode = Bytes::from_static(&[0x60, 0x01]);
1553        let artifacts = ContractsByArtifact::new([test_artifact(
1554            "src/Something.sol",
1555            "Something",
1556            "default",
1557            bytecode.clone(),
1558        )]);
1559        let root = PathBuf::from(&env!("CARGO_MANIFEST_DIR"));
1560        let paths = foundry_compilers::ProjectPathsConfig::builder()
1561            .remapping(Remapping::from_str("@example/=src/").unwrap())
1562            .build_with_root(&root);
1563        let config = CheatsConfig {
1564            available_artifacts: Some(artifacts),
1565            root,
1566            paths,
1567            ..Default::default()
1568        };
1569        let cheats = CheatcodesCore::new(Arc::new(config));
1570
1571        let resolved =
1572            super::get_artifact_code(&cheats, "@example/Something.sol:Something", false).unwrap();
1573
1574        assert_eq!(resolved, bytecode);
1575    }
1576
1577    #[test]
1578    fn test_get_artifact_code_remaps_exact_paths_before_profile_selection() {
1579        for file in ["Target.sol", "Colon:Path.sol"] {
1580            let source = format!("src/{file}");
1581            let remapped = format!("lib/alternate/{file}");
1582            let default_bytecode = Bytes::from_static(&[0x60, 0x02]);
1583            let optimized_bytecode = Bytes::from_static(&[0x60, 0x03]);
1584            let artifacts = ContractsByArtifact::new([
1585                test_artifact(&source, "Target", "default", Bytes::from_static(&[0x60, 0x01])),
1586                test_artifact(&remapped, "Target", "default", default_bytecode.clone()),
1587                test_artifact(
1588                    &remapped,
1589                    "Target.optimized",
1590                    "optimized",
1591                    optimized_bytecode.clone(),
1592                ),
1593            ]);
1594            for (profile, expected) in
1595                [("default", default_bytecode), ("optimized", optimized_bytecode)]
1596            {
1597                let root = PathBuf::from(&env!("CARGO_MANIFEST_DIR"));
1598                let paths = foundry_compilers::ProjectPathsConfig::builder()
1599                    .remapping(Remapping::from_str("src/=lib/alternate/").unwrap())
1600                    .build_with_root(&root);
1601                let config = CheatsConfig {
1602                    available_artifacts: Some(artifacts.clone()),
1603                    running_artifact: Some(
1604                        test_artifact("test/Runner.t.sol", "Runner", profile, Bytes::new()).0,
1605                    ),
1606                    root,
1607                    paths,
1608                    ..Default::default()
1609                };
1610                let cheats = CheatcodesCore::new(Arc::new(config));
1611                let resolved =
1612                    super::get_artifact_code(&cheats, &format!("{source}:Target"), false).unwrap();
1613                assert_eq!(resolved, expected, "{source} in {profile} profile");
1614            }
1615        }
1616    }
1617
1618    #[test]
1619    fn test_get_artifact_code_preserves_project_path_on_library_collision() {
1620        let root_bytecode = Bytes::from_static(&[0x60, 0x01]);
1621        let library_bytecode = Bytes::from_static(&[0x60, 0x02]);
1622        let artifacts = ContractsByArtifact::new([
1623            test_artifact("src/Thing.sol", "RootThing", "default", root_bytecode.clone()),
1624            test_artifact("lib/src/Thing.sol", "LibThing", "default", library_bytecode),
1625        ]);
1626        let temp = TempDir::new().unwrap();
1627        let library = temp.path().join("lib");
1628        stdfs::create_dir_all(library.join("src")).unwrap();
1629        stdfs::write(library.join("src/Thing.sol"), "").unwrap();
1630        let paths = foundry_compilers::ProjectPathsConfig::builder()
1631            .remappings([])
1632            .lib(library)
1633            .build_with_root(temp.path());
1634        let config = CheatsConfig {
1635            available_artifacts: Some(artifacts),
1636            root: temp.path().to_path_buf(),
1637            paths,
1638            ..Default::default()
1639        };
1640        let cheats = CheatcodesCore::new(Arc::new(config));
1641
1642        let resolved = super::get_artifact_code(&cheats, "src/Thing.sol:RootThing", false).unwrap();
1643
1644        assert_eq!(resolved, root_bytecode);
1645    }
1646
1647    #[test]
1648    fn test_parse_artifact_path_contract_only() {
1649        let parsed = super::parse_artifact_path("MyContract").unwrap();
1650        assert_eq!(parsed.file, None);
1651        assert_eq!(parsed.contract_name, Some("MyContract"));
1652        assert_eq!(parsed.version, None);
1653        assert_eq!(parsed.profile, None);
1654    }
1655
1656    #[test]
1657    fn test_parse_artifact_path_contract_and_version() {
1658        let parsed = super::parse_artifact_path("MyContract:0.8.23").unwrap();
1659        assert_eq!(parsed.file, None);
1660        assert_eq!(parsed.contract_name, Some("MyContract"));
1661        assert_eq!(parsed.version, Some(semver::Version::new(0, 8, 23)));
1662        assert_eq!(parsed.profile, None);
1663    }
1664
1665    #[test]
1666    fn test_parse_artifact_path_contract_and_profile() {
1667        let parsed = super::parse_artifact_path("MyContract:optimized").unwrap();
1668        assert_eq!(parsed.file, None);
1669        assert_eq!(parsed.contract_name, Some("MyContract"));
1670        assert_eq!(parsed.version, None);
1671        assert_eq!(parsed.profile, Some("optimized"));
1672    }
1673
1674    #[test]
1675    fn test_parse_artifact_path_profile_names() {
1676        // Test various profile name patterns
1677        for profile in ["v1", "v2", "paris", "optimized", "default", "prod", "dev"] {
1678            let path = format!("MyContract:{profile}");
1679            let parsed = super::parse_artifact_path(&path).unwrap();
1680            assert_eq!(parsed.contract_name, Some("MyContract"));
1681            assert_eq!(parsed.profile, Some(profile));
1682            assert_eq!(parsed.version, None);
1683        }
1684    }
1685
1686    #[test]
1687    fn test_parse_artifact_path_invalid_version() {
1688        // Invalid semver should be treated as profile
1689        let parsed = super::parse_artifact_path("MyContract:invalid").unwrap();
1690        assert_eq!(parsed.contract_name, Some("MyContract"));
1691        assert_eq!(parsed.profile, Some("invalid"));
1692        assert_eq!(parsed.version, None);
1693    }
1694
1695    fn unique_temp_dir(prefix: &str) -> PathBuf {
1696        env::temp_dir().join(format!(
1697            "foundry-cheatcodes-{prefix}-{}",
1698            SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos()
1699        ))
1700    }
1701
1702    #[test]
1703    fn test_latest_broadcast_reads_tempo_sequences() {
1704        let root = unique_temp_dir("tempo-broadcast");
1705        let broadcast_path = root.join("broadcast");
1706        let sequence_dir = broadcast_path.join("Counter.s.sol").join("31337");
1707        stdfs::create_dir_all(&sequence_dir).unwrap();
1708
1709        let tx_hash = "0x04548a0ea27e2cccc1479af3c2ff02da4d4d3ea46af8e8d7edaa49f6ea27073f";
1710        let block_hash = "0x860f788b251ece768e63b0d3906d156f652d843848b71c7fe81faacd49139d66";
1711        let from = "0xa70ab0448e66cd77995bfbba5c5b64b41a85f3fd";
1712        let contract_address = "0x20c0000000000000000000000000000000000000";
1713        let zero_bloom = format!("{:#x}", Bloom::ZERO);
1714
1715        let sequence = serde_json::json!({
1716            "transactions": [{
1717                "hash": tx_hash,
1718                "transactionType": "CREATE",
1719                "contractName": "Counter",
1720                "contractAddress": contract_address,
1721                "function": serde_json::Value::Null,
1722                "arguments": serde_json::Value::Null,
1723                "transaction": {
1724                    "type": "0x76",
1725                    "from": from,
1726                    "to": serde_json::Value::Null,
1727                    "data": "0x",
1728                    "value": "0x0",
1729                    "gas": "0x5208",
1730                    "nonce": "0x0",
1731                    "accessList": [],
1732                    "calls": [],
1733                    "nonceKey": "0x0",
1734                    "feePayerSignature": serde_json::Value::Null,
1735                    "validBefore": serde_json::Value::Null,
1736                    "validAfter": serde_json::Value::Null,
1737                    "keyAuthorization": serde_json::Value::Null,
1738                    "aaAuthorizationList": []
1739                },
1740                "additionalContracts": [],
1741                "isFixedGasLimit": false
1742            }],
1743            "receipts": [{
1744                "type": "0x76",
1745                "status": "0x1",
1746                "cumulativeGasUsed": "0x5208",
1747                "logs": [],
1748                "logsBloom": zero_bloom,
1749                "transactionHash": tx_hash,
1750                "transactionIndex": "0x0",
1751                "blockHash": block_hash,
1752                "blockNumber": "0x7",
1753                "gasUsed": "0x5208",
1754                "effectiveGasPrice": "0x1",
1755                "from": from,
1756                "to": serde_json::Value::Null,
1757                "contractAddress": contract_address,
1758                "feePayer": from
1759            }],
1760            "libraries": [],
1761            "pending": [],
1762            "returns": {},
1763            "timestamp": 1,
1764            "chain": 31337,
1765            "commit": serde_json::Value::Null
1766        });
1767
1768        fs::write_json_file(&sequence_dir.join("run-1.json"), &sequence).unwrap();
1769
1770        let latest = latest_broadcast::<AnyNetwork>(
1771            &"Counter".to_owned(),
1772            31337,
1773            &broadcast_path,
1774            vec![CallKind::Create],
1775        )
1776        .unwrap();
1777
1778        assert_eq!(
1779            latest.txHash,
1780            b256!("04548a0ea27e2cccc1479af3c2ff02da4d4d3ea46af8e8d7edaa49f6ea27073f")
1781        );
1782        assert_eq!(latest.blockNumber, 7);
1783        assert!(matches!(latest.txType, BroadcastTxType::Create));
1784        assert_eq!(latest.contractAddress, address!("20c0000000000000000000000000000000000000"));
1785        assert!(latest.success);
1786
1787        stdfs::remove_dir_all(root).unwrap();
1788    }
1789}