1use 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 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 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 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 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
353fn 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
391fn 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 if let Some(artifacts) = &state.config.available_artifacts {
435 let filtered = artifacts
436 .iter()
437 .filter(|(id, _)| {
438 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 state
469 .config
470 .running_artifact
471 .as_ref()
472 .and_then(|running| {
473 filtered.retain(|(id, _)| id.version == running.version);
475
476 if filtered.len() == 1 {
478 return Some(filtered[0]);
479 }
480
481 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
531 if output.exitCode != 0 {
533 return Err(fmt_err!(
535 "ffi command {:?} exited with code {}. stderr: {}",
536 input,
537 output.exitCode,
538 String::from_utf8_lossy(&output.stderr)
539 ));
540 }
541
542 if !output.stderr.is_empty() {
544 let stderr = String::from_utf8_lossy(&output.stderr);
545 warn!(target: "cheatcodes", ?input, ?stderr, "ffi command wrote to stderr");
546 }
547
548 Ok(output.stdout.abi_encode())
550 }
551}
552
553impl Cheatcode for tryFfiCall {
554 fn apply(&self, state: &mut Cheatcodes) -> Result {
555 let Self { commandInput: input } = self;
556 ffi(state, input).map(|res| res.abi_encode())
557 }
558}
559
560impl Cheatcode for promptCall {
561 fn apply(&self, state: &mut Cheatcodes) -> Result {
562 let Self { promptText: text } = self;
563 prompt(state, text, prompt_input).map(|res| res.abi_encode())
564 }
565}
566
567impl Cheatcode for promptSecretCall {
568 fn apply(&self, state: &mut Cheatcodes) -> Result {
569 let Self { promptText: text } = self;
570 prompt(state, text, prompt_password).map(|res| res.abi_encode())
571 }
572}
573
574impl Cheatcode for promptSecretUintCall {
575 fn apply(&self, state: &mut Cheatcodes) -> Result {
576 let Self { promptText: text } = self;
577 parse(&prompt(state, text, prompt_password)?, &DynSolType::Uint(256))
578 }
579}
580
581impl Cheatcode for promptAddressCall {
582 fn apply(&self, state: &mut Cheatcodes) -> Result {
583 let Self { promptText: text } = self;
584 parse(&prompt(state, text, prompt_input)?, &DynSolType::Address)
585 }
586}
587
588impl Cheatcode for promptUintCall {
589 fn apply(&self, state: &mut Cheatcodes) -> Result {
590 let Self { promptText: text } = self;
591 parse(&prompt(state, text, prompt_input)?, &DynSolType::Uint(256))
592 }
593}
594
595pub(super) fn write_file(state: &Cheatcodes, path: &Path, contents: &[u8]) -> Result {
596 let path = state.config.ensure_path_allowed(path, FsAccessKind::Write)?;
597 state.config.ensure_not_foundry_toml(&path)?;
599
600 if state.fs_commit {
601 fs::write(path, contents)?;
602 }
603
604 Ok(Default::default())
605}
606
607fn read_dir(state: &Cheatcodes, path: &Path, max_depth: u64, follow_links: bool) -> Result {
608 let root = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
609 let paths: Vec<DirEntry> = WalkDir::new(root)
610 .min_depth(1)
611 .max_depth(max_depth.try_into().unwrap_or(usize::MAX))
612 .follow_links(follow_links)
613 .contents_first(false)
614 .same_file_system(true)
615 .sort_by_file_name()
616 .into_iter()
617 .map(|entry| match entry {
618 Ok(entry) => DirEntry {
619 errorMessage: String::new(),
620 path: entry.path().display().to_string(),
621 depth: entry.depth() as u64,
622 isDir: entry.file_type().is_dir(),
623 isSymlink: entry.path_is_symlink(),
624 },
625 Err(e) => DirEntry {
626 errorMessage: e.to_string(),
627 path: e.path().map(|p| p.display().to_string()).unwrap_or_default(),
628 depth: e.depth() as u64,
629 isDir: false,
630 isSymlink: false,
631 },
632 })
633 .collect();
634 Ok(paths.abi_encode())
635}
636
637fn ffi(state: &Cheatcodes, input: &[String]) -> Result<FfiResult> {
638 ensure!(
639 state.config.ffi,
640 "FFI is disabled; add the `--ffi` flag to allow tests to call external commands"
641 );
642 ensure!(!input.is_empty() && !input[0].is_empty(), "can't execute empty command");
643 let mut cmd = Command::new(&input[0]);
644 cmd.args(&input[1..]);
645
646 debug!(target: "cheatcodes", ?cmd, "invoking ffi");
647
648 let output = cmd
649 .current_dir(&state.config.root)
650 .output()
651 .map_err(|err| fmt_err!("failed to execute command {cmd:?}: {err}"))?;
652
653 let trimmed_stdout = String::from_utf8(output.stdout)?;
656 let trimmed_stdout = trimmed_stdout.trim();
657 let encoded_stdout = if let Ok(hex) = hex::decode(trimmed_stdout) {
658 hex
659 } else {
660 trimmed_stdout.as_bytes().to_vec()
661 };
662 Ok(FfiResult {
663 exitCode: output.status.code().unwrap_or(69),
664 stdout: encoded_stdout.into(),
665 stderr: output.stderr.into(),
666 })
667}
668
669fn prompt_input(prompt_text: &str) -> Result<String, dialoguer::Error> {
670 Input::new().allow_empty(true).with_prompt(prompt_text).interact_text()
671}
672
673fn prompt_password(prompt_text: &str) -> Result<String, dialoguer::Error> {
674 Password::new().with_prompt(prompt_text).interact()
675}
676
677fn prompt(
678 state: &Cheatcodes,
679 prompt_text: &str,
680 input: fn(&str) -> Result<String, dialoguer::Error>,
681) -> Result<String> {
682 let text_clone = prompt_text.to_string();
683 let timeout = state.config.prompt_timeout;
684 let (tx, rx) = mpsc::channel();
685
686 thread::spawn(move || {
687 let _ = tx.send(input(&text_clone));
688 });
689
690 match rx.recv_timeout(timeout) {
691 Ok(res) => res.map_err(|err| {
692 let _ = sh_println!();
693 err.to_string().into()
694 }),
695 Err(_) => {
696 let _ = sh_eprintln!();
697 Err("Prompt timed out".into())
698 }
699 }
700}
701
702impl Cheatcode for getBroadcastCall {
703 fn apply(&self, state: &mut Cheatcodes) -> Result {
704 let Self { contractName, chainId, txType } = self;
705
706 let latest_broadcast = latest_broadcast(
707 contractName,
708 *chainId,
709 &state.config.broadcast,
710 vec![map_broadcast_tx_type(*txType)],
711 )?;
712
713 Ok(latest_broadcast.abi_encode())
714 }
715}
716
717impl Cheatcode for getBroadcasts_0Call {
718 fn apply(&self, state: &mut Cheatcodes) -> Result {
719 let Self { contractName, chainId, txType } = self;
720
721 let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?
722 .with_tx_type(map_broadcast_tx_type(*txType));
723
724 let broadcasts = reader.read()?;
725
726 let summaries = broadcasts
727 .into_iter()
728 .flat_map(|broadcast| {
729 let results = reader.into_tx_receipts(broadcast);
730 parse_broadcast_results(results)
731 })
732 .collect::<Vec<_>>();
733
734 Ok(summaries.abi_encode())
735 }
736}
737
738impl Cheatcode for getBroadcasts_1Call {
739 fn apply(&self, state: &mut Cheatcodes) -> Result {
740 let Self { contractName, chainId } = self;
741
742 let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?;
743
744 let broadcasts = reader.read()?;
745
746 let summaries = broadcasts
747 .into_iter()
748 .flat_map(|broadcast| {
749 let results = reader.into_tx_receipts(broadcast);
750 parse_broadcast_results(results)
751 })
752 .collect::<Vec<_>>();
753
754 Ok(summaries.abi_encode())
755 }
756}
757
758impl Cheatcode for getDeployment_0Call {
759 fn apply_stateful(&self, ccx: &mut CheatsCtxt) -> Result {
760 let Self { contractName } = self;
761 let chain_id = ccx.ecx.cfg.chain_id;
762
763 let latest_broadcast = latest_broadcast(
764 contractName,
765 chain_id,
766 &ccx.state.config.broadcast,
767 vec![CallKind::Create, CallKind::Create2],
768 )?;
769
770 Ok(latest_broadcast.contractAddress.abi_encode())
771 }
772}
773
774impl Cheatcode for getDeployment_1Call {
775 fn apply(&self, state: &mut Cheatcodes) -> Result {
776 let Self { contractName, chainId } = self;
777
778 let latest_broadcast = latest_broadcast(
779 contractName,
780 *chainId,
781 &state.config.broadcast,
782 vec![CallKind::Create, CallKind::Create2],
783 )?;
784
785 Ok(latest_broadcast.contractAddress.abi_encode())
786 }
787}
788
789impl Cheatcode for getDeploymentsCall {
790 fn apply(&self, state: &mut Cheatcodes) -> Result {
791 let Self { contractName, chainId } = self;
792
793 let reader = BroadcastReader::new(contractName.clone(), *chainId, &state.config.broadcast)?
794 .with_tx_type(CallKind::Create)
795 .with_tx_type(CallKind::Create2);
796
797 let broadcasts = reader.read()?;
798
799 let summaries = broadcasts
800 .into_iter()
801 .flat_map(|broadcast| {
802 let results = reader.into_tx_receipts(broadcast);
803 parse_broadcast_results(results)
804 })
805 .collect::<Vec<_>>();
806
807 let deployed_addresses =
808 summaries.into_iter().map(|summary| summary.contractAddress).collect::<Vec<_>>();
809
810 Ok(deployed_addresses.abi_encode())
811 }
812}
813
814fn map_broadcast_tx_type(tx_type: BroadcastTxType) -> CallKind {
815 match tx_type {
816 BroadcastTxType::Call => CallKind::Call,
817 BroadcastTxType::Create => CallKind::Create,
818 BroadcastTxType::Create2 => CallKind::Create2,
819 _ => unreachable!("invalid tx type"),
820 }
821}
822
823fn parse_broadcast_results(
824 results: Vec<(TransactionWithMetadata, AnyTransactionReceipt)>,
825) -> Vec<BroadcastTxSummary> {
826 results
827 .into_iter()
828 .map(|(tx, receipt)| BroadcastTxSummary {
829 txHash: receipt.transaction_hash,
830 blockNumber: receipt.block_number.unwrap_or_default(),
831 txType: match tx.opcode {
832 CallKind::Call => BroadcastTxType::Call,
833 CallKind::Create => BroadcastTxType::Create,
834 CallKind::Create2 => BroadcastTxType::Create2,
835 _ => unreachable!("invalid tx type"),
836 },
837 contractAddress: tx.contract_address.unwrap_or_default(),
838 success: receipt.status(),
839 })
840 .collect()
841}
842
843fn latest_broadcast(
844 contract_name: &String,
845 chain_id: u64,
846 broadcast_path: &Path,
847 filters: Vec<CallKind>,
848) -> Result<BroadcastTxSummary> {
849 let mut reader = BroadcastReader::new(contract_name.clone(), chain_id, broadcast_path)?;
850
851 for filter in filters {
852 reader = reader.with_tx_type(filter);
853 }
854
855 let broadcast = reader.read_latest()?;
856
857 let results = reader.into_tx_receipts(broadcast);
858
859 let summaries = parse_broadcast_results(results);
860
861 summaries
862 .first()
863 .ok_or_else(|| fmt_err!("no deployment found for {contract_name} on chain {chain_id}"))
864 .cloned()
865}
866
867#[cfg(test)]
868mod tests {
869 use super::*;
870 use crate::CheatsConfig;
871 use std::sync::Arc;
872
873 fn cheats() -> Cheatcodes {
874 let config = CheatsConfig {
875 ffi: true,
876 root: PathBuf::from(&env!("CARGO_MANIFEST_DIR")),
877 ..Default::default()
878 };
879 Cheatcodes::new(Arc::new(config))
880 }
881
882 #[test]
883 fn test_ffi_hex() {
884 let msg = b"gm";
885 let cheats = cheats();
886 let args = ["echo".to_string(), hex::encode(msg)];
887 let output = ffi(&cheats, &args).unwrap();
888 assert_eq!(output.stdout, Bytes::from(msg));
889 }
890
891 #[test]
892 fn test_ffi_string() {
893 let msg = "gm";
894 let cheats = cheats();
895 let args = ["echo".to_string(), msg.to_string()];
896 let output = ffi(&cheats, &args).unwrap();
897 assert_eq!(output.stdout, Bytes::from(msg.as_bytes()));
898 }
899
900 #[test]
901 fn test_ffi_fails_on_error_code() {
902 let mut cheats = cheats();
903
904 #[cfg(unix)]
906 let args = vec!["false".to_string()];
907 #[cfg(windows)]
908 let args = vec!["cmd".to_string(), "/c".to_string(), "exit 1".to_string()];
909
910 let result = ffiCall { commandInput: args }.apply(&mut cheats);
911
912 assert!(result.is_err(), "Expected ffi cheatcode to fail, but it succeeded");
914
915 let err_msg = result.unwrap_err().to_string();
917 assert!(
918 err_msg.contains("exited with code 1"),
919 "Error message did not contain exit code: {err_msg}"
920 );
921 }
922
923 #[test]
924 fn test_artifact_parsing() {
925 let s = include_str!("../../evm/test-data/solc-obj.json");
926 let artifact: ContractObject = serde_json::from_str(s).unwrap();
927 assert!(artifact.bytecode.is_some());
928
929 let artifact: ContractObject = serde_json::from_str(s).unwrap();
930 assert!(artifact.deployed_bytecode.is_some());
931 }
932}