1#![cfg_attr(not(test), warn(unused_crate_dependencies))]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5#![allow(rustdoc::bare_urls, rustdoc::invalid_html_tags)]
7
8use serde::{Deserialize, Serialize};
9use std::{borrow::Cow, fmt};
10
11mod cheatcode;
12pub use cheatcode::{Cheatcode, CheatcodeDef, Group, Safety, Status};
13
14mod function;
15pub use function::{Function, Mutability, Visibility};
16
17mod items;
18pub use items::{Enum, EnumVariant, Error, Event, Struct, StructField};
19
20mod symbolic;
21pub use symbolic::SymbolicVm;
22
23mod vm;
24pub use vm::Vm;
25
26#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
29#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
30#[serde(rename_all = "camelCase")]
31pub struct Cheatcodes<'a> {
32 #[serde(borrow)]
34 pub errors: Cow<'a, [Error<'a>]>,
35 #[serde(borrow)]
37 pub events: Cow<'a, [Event<'a>]>,
38 #[serde(borrow)]
40 pub enums: Cow<'a, [Enum<'a>]>,
41 #[serde(borrow)]
43 pub structs: Cow<'a, [Struct<'a>]>,
44 #[serde(borrow)]
46 pub cheatcodes: Cow<'a, [Cheatcode<'a>]>,
47}
48
49impl fmt::Display for Cheatcodes<'_> {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 for error in self.errors.iter() {
52 writeln!(f, "{error}")?;
53 }
54 for event in self.events.iter() {
55 writeln!(f, "{event}")?;
56 }
57 for enumm in self.enums.iter() {
58 writeln!(f, "{enumm}")?;
59 }
60 for strukt in self.structs.iter() {
61 writeln!(f, "{strukt}")?;
62 }
63 for cheatcode in self.cheatcodes.iter() {
64 writeln!(f, "{}", cheatcode.func)?;
65 }
66 Ok(())
67 }
68}
69
70impl Default for Cheatcodes<'static> {
71 fn default() -> Self {
72 Self::new()
73 }
74}
75
76impl Cheatcodes<'static> {
77 pub fn new() -> Self {
79 Self {
80 structs: Cow::Owned(vec![
83 Vm::Log::STRUCT.clone(),
84 Vm::Rpc::STRUCT.clone(),
85 Vm::EthGetLogs::STRUCT.clone(),
86 Vm::EthStorageProof::STRUCT.clone(),
87 Vm::EthGetProof::STRUCT.clone(),
88 Vm::DirEntry::STRUCT.clone(),
89 Vm::FsMetadata::STRUCT.clone(),
90 Vm::Wallet::STRUCT.clone(),
91 Vm::FfiResult::STRUCT.clone(),
92 Vm::ChainInfo::STRUCT.clone(),
93 Vm::Chain::STRUCT.clone(),
94 Vm::AccountAccess::STRUCT.clone(),
95 Vm::StorageAccess::STRUCT.clone(),
96 Vm::Gas::STRUCT.clone(),
97 Vm::DebugStep::STRUCT.clone(),
98 Vm::BroadcastTxSummary::STRUCT.clone(),
99 Vm::SignedDelegation::STRUCT.clone(),
100 Vm::PotentialRevert::STRUCT.clone(),
101 Vm::AccessListItem::STRUCT.clone(),
102 Vm::ConfigurableAccountOwner::STRUCT.clone(),
103 Vm::ConfigurableAccountConfig::STRUCT.clone(),
104 Vm::OwnerKey::STRUCT.clone(),
105 ]),
106 enums: Cow::Owned(vec![
107 Vm::CallerMode::ENUM.clone(),
108 Vm::AccountAccessKind::ENUM.clone(),
109 Vm::ForgeContext::ENUM.clone(),
110 Vm::BroadcastTxType::ENUM.clone(),
111 Vm::OwnerKeyType::ENUM.clone(),
112 ]),
113 errors: Vm::VM_ERRORS.iter().copied().cloned().collect(),
114 events: Cow::Borrowed(&[]),
115 cheatcodes: Vm::CHEATCODES.iter().copied().cloned().collect(),
117 }
118 }
119}
120
121#[cfg(test)]
122#[expect(clippy::disallowed_macros)]
123mod tests {
124 use super::*;
125 use std::{fs, path::Path};
126
127 const JSON_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/cheatcodes.json");
128 #[cfg(feature = "schema")]
129 const SCHEMA_PATH: &str =
130 concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/cheatcodes.schema.json");
131 const IFACE_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../../testdata/utils/Vm.sol");
132
133 fn json_cheatcodes() -> String {
135 serde_json::to_string_pretty(&Cheatcodes::new()).unwrap()
136 }
137
138 #[cfg(feature = "schema")]
140 fn json_schema() -> String {
141 serde_json::to_string_pretty(&schemars::schema_for!(Cheatcodes<'_>)).unwrap()
142 }
143
144 fn sol_iface() -> String {
145 let mut cheats = Cheatcodes::new();
146 cheats.errors = Default::default(); let cheats = cheats.to_string().trim().replace('\n', "\n ");
148 format!(
149 "\
150// Automatically generated from `foundry-cheatcodes` Vm definitions. Do not modify manually.
151// This interface is just for internal testing purposes. Use `forge-std` instead.
152
153// SPDX-License-Identifier: MIT OR Apache-2.0
154pragma solidity >=0.6.2 <0.9.0;
155pragma experimental ABIEncoderV2;
156
157interface Vm {{
158 {cheats}
159}}
160"
161 )
162 }
163
164 #[test]
165 fn spec_up_to_date() {
166 ensure_file_contents(Path::new(JSON_PATH), &json_cheatcodes());
167 }
168
169 #[test]
170 #[cfg(feature = "schema")]
171 fn schema_up_to_date() {
172 ensure_file_contents(Path::new(SCHEMA_PATH), &json_schema());
173 }
174
175 #[test]
176 fn iface_up_to_date() {
177 ensure_file_contents(Path::new(IFACE_PATH), &sol_iface());
178 }
179
180 fn ensure_file_contents(file: &Path, contents: &str) {
183 if let Ok(old_contents) = fs::read_to_string(file)
184 && normalize_newlines(&old_contents) == normalize_newlines(contents)
185 {
186 return;
188 }
189
190 eprintln!("\n\x1b[31;1merror\x1b[0m: {} was not up-to-date, updating\n", file.display());
191 if std::env::var("CI").is_ok() {
192 eprintln!(" NOTE: run `cargo cheats` locally and commit the updated files\n");
193 }
194 if let Some(parent) = file.parent() {
195 let _ = fs::create_dir_all(parent);
196 }
197 fs::write(file, contents).unwrap();
198 panic!("some file was not up to date and has been updated, simply re-run the tests");
199 }
200
201 fn normalize_newlines(s: &str) -> String {
202 s.replace("\r\n", "\n")
203 }
204}