Skip to main content

foundry_cheatcodes/
lib.rs

1//! # foundry-cheatcodes
2//!
3//! Foundry cheatcodes implementations.
4
5#![cfg_attr(not(test), warn(unused_crate_dependencies))]
6#![cfg_attr(docsrs, feature(doc_cfg))]
7#![allow(elided_lifetimes_in_paths)] // Cheats context uses 3 lifetimes
8
9#[macro_use]
10extern crate foundry_common;
11
12#[macro_use]
13pub extern crate foundry_cheatcodes_spec as spec;
14
15#[macro_use]
16extern crate tracing;
17
18use alloy_primitives::{Address, B256, U256};
19use evm2::interpreter::GasTracker;
20use foundry_evm_core::{
21    backend::{Backend, CowBackend, LocalForkId},
22    evm::{
23        BlockEnvFor, EvmEnvFor, EvmFactoryFor, FoundryEvmFactory, FoundryEvmFor, FoundryEvmNetwork,
24        SpecFor, evm_env,
25    },
26    fork::CreateFork,
27};
28
29pub use Vm::ForgeContext;
30pub use config::CheatsConfig;
31pub use error::{Error, ErrorKind, Result};
32pub use inspector::{
33    BroadcastableTransaction, BroadcastableTransactions, Cheatcodes, CheatcodesExecutor,
34    StorageHook, decode_cheatcode_call, message_result, revert_frame,
35};
36pub use spec::{CheatcodeDef, Vm};
37
38#[macro_use]
39mod error;
40
41mod base64;
42
43mod config;
44
45mod crypto;
46
47mod version;
48
49mod env;
50pub use env::{current_execution_context, set_execution_context};
51
52mod evm;
53pub use evm::{RecordAccess, prank::Prank};
54
55mod expected_emit;
56
57mod external_storage;
58
59mod fs;
60
61mod inspector;
62pub use inspector::CheatcodeAnalysis;
63
64mod json;
65
66#[cfg(feature = "monad")]
67mod monad;
68
69mod script;
70pub use script::{Wallets, WalletsInner};
71
72mod state;
73pub use state::CheatcodesCore;
74
75mod string;
76pub use string::parse_value;
77
78mod tempo;
79
80mod test;
81pub use test::{
82    expect::{ExpectedCallTracker, ExpectedCallType},
83    revert_handlers::{DUMMY_CALL_OUTPUT, DUMMY_CREATE_ADDRESS, expect_revert_mismatch},
84};
85
86mod toml;
87
88mod utils;
89
90/// Cheatcode implementation.
91pub(crate) trait Cheatcode: CheatcodeDef {
92    /// Applies this cheatcode to the given state.
93    ///
94    /// Implement this function if you need cheatcode state but no access to the EVM context.
95    fn apply_context(&self, _state: &mut CheatcodesCore) -> Result {
96        self.apply_context_free()
97    }
98
99    /// Applies this cheatcode to the given context.
100    ///
101    /// Implement this function if you need access to the EVM data.
102    #[inline(always)]
103    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
104        self.apply_context(&mut ccx.state.core)
105    }
106
107    /// Applies this cheatcode to the given context and executor.
108    ///
109    /// Implement this function if you need access to the executor.
110    #[inline(always)]
111    fn apply_full<FEN: FoundryEvmNetwork>(
112        &self,
113        ccx: &mut CheatsCtxt<'_, '_, FEN>,
114        executor: &mut dyn CheatcodesExecutor<FEN>,
115    ) -> Result {
116        let _ = executor;
117        self.apply_stateful(ccx)
118    }
119
120    /// Applies this cheatcode without accessing cheatcode state or the EVM context.
121    ///
122    /// This may still read or modify external host state, such as environment variables.
123    fn apply_context_free(&self) -> Result {
124        unimplemented!("{}", Self::CHEATCODE.func.id)
125    }
126}
127
128/// Backend access of the cheatcode inspector while an execution runs.
129///
130/// Implemented for [`Backend`] and [`CowBackend`], so fuzzed calls keep their lazy copy-on-write
131/// clone: read-only cheatcodes never clone the backend.
132pub trait CheatcodesBackend<FEN: FoundryEvmNetwork> {
133    /// Returns the backend for reading.
134    fn backend(&self) -> &Backend<FEN>;
135
136    /// Returns the backend for modification.
137    fn backend_mut(&mut self) -> &mut Backend<FEN>;
138}
139
140impl<FEN: FoundryEvmNetwork> CheatcodesBackend<FEN> for Backend<FEN> {
141    fn backend(&self) -> &Self {
142        self
143    }
144
145    fn backend_mut(&mut self) -> &mut Self {
146        self
147    }
148}
149
150impl<FEN: FoundryEvmNetwork> CheatcodesBackend<FEN> for CowBackend<'_, FEN> {
151    fn backend(&self) -> &Backend<FEN> {
152        self
153    }
154
155    fn backend_mut(&mut self) -> &mut Backend<FEN> {
156        self
157    }
158}
159
160/// The cheatcode context.
161pub struct CheatsCtxt<'a, 'evm, FEN: FoundryEvmNetwork> {
162    /// The cheatcodes inspector state.
163    pub(crate) state: &'a mut Cheatcodes<FEN>,
164    /// The running EVM.
165    pub(crate) evm: &'a mut FoundryEvmFor<'evm, FEN>,
166    /// The backend the EVM runs over.
167    pub(crate) backend: &'a mut dyn CheatcodesBackend<FEN>,
168    /// The original `msg.sender`.
169    pub(crate) caller: Address,
170    /// Gas of the current cheatcode call, returned to the caller.
171    pub(crate) gas: &'a mut GasTracker,
172    /// Whether the current cheatcode call is static.
173    pub(crate) is_static: bool,
174    /// Call depth of the frame calling the cheatcode.
175    pub(crate) depth: usize,
176}
177
178impl<'evm, FEN: FoundryEvmNetwork> CheatsCtxt<'_, 'evm, FEN> {
179    pub(crate) fn ensure_not_precompile(&self, address: &Address) -> Result<()> {
180        if self.is_precompile(address) { Err(precompile_error(address)) } else { Ok(()) }
181    }
182
183    /// Returns whether `address` is one of the EVM's registered precompiles.
184    ///
185    /// Checks the provider's registered addresses rather than `PrecompileProvider::contains`:
186    /// networks such as Tempo also dispatch storage-backed system contracts as precompiles, and
187    /// cheatcodes like `vm.store` must keep working on their state.
188    pub(crate) fn is_precompile(&self, address: &Address) -> bool {
189        self.evm.precompiles().addresses().contains(address)
190    }
191
192    /// Returns the backend.
193    #[inline]
194    pub(crate) fn db(&self) -> &Backend<FEN> {
195        self.backend.backend()
196    }
197
198    /// Returns the backend for modification.
199    #[inline]
200    pub(crate) fn db_mut(&mut self) -> &mut Backend<FEN> {
201        self.backend.backend_mut()
202    }
203
204    /// Returns the running EVM and the backend for modification.
205    #[inline]
206    pub(crate) fn evm_db_mut(&mut self) -> (&mut FoundryEvmFor<'evm, FEN>, &mut Backend<FEN>) {
207        (&mut *self.evm, self.backend.backend_mut())
208    }
209
210    /// Returns the current call depth.
211    #[inline]
212    pub(crate) const fn depth(&self) -> usize {
213        self.depth
214    }
215
216    /// Returns the depth of the frame that called the cheatcode, whose scope its writes join.
217    #[inline]
218    pub(crate) const fn caller_depth(&self) -> usize {
219        self.depth.saturating_sub(1)
220    }
221
222    /// Returns the active hardfork: the one the calls and creates started next run with.
223    ///
224    /// Cheatcode calls run on the running EVM, which keeps its spec while a change requested by
225    /// `vm.setEvmVersion` or deferred by an in-flight operation applies to new frames.
226    #[inline]
227    pub(crate) fn spec(&self) -> SpecFor<FEN> {
228        self.state
229            .execution_evm_version
230            .or_else(|| self.db().lifecycle().pending_env().map(|env| env.spec))
231            .unwrap_or_else(|| self.evm.config_spec_id())
232    }
233
234    /// Returns the running environment with [`Self::spec`], for transactions a cheatcode executes
235    /// with the requested spec.
236    pub(crate) fn evm_env(&self) -> EvmEnvFor<FEN> {
237        let env = evm_env(self.evm);
238        let spec = self.spec();
239        if spec == env.spec {
240            return env;
241        }
242        EvmFactoryFor::<FEN>::default().env_with_spec(env, spec)
243    }
244
245    /// Returns the chain ID.
246    #[inline]
247    pub(crate) fn chain_id(&self) -> u64 {
248        self.state
249            .env_overrides
250            .get(self.active_fork_id())
251            .and_then(|overrides| overrides.chain_id)
252            .unwrap_or(self.evm.version().chain_id)
253    }
254
255    /// Returns the block number.
256    #[inline]
257    pub(crate) const fn block_number(&self) -> U256 {
258        self.evm.block().number
259    }
260
261    /// Returns the block timestamp.
262    #[inline]
263    pub(crate) const fn timestamp(&self) -> U256 {
264        self.evm.block().timestamp
265    }
266
267    /// Returns the block base fee.
268    #[inline]
269    pub(crate) fn basefee(&self) -> u64 {
270        self.evm.block().basefee.saturating_to()
271    }
272
273    /// Returns the block slot number.
274    #[inline]
275    pub(crate) fn slot_num(&self) -> u64 {
276        self.evm.block().slot_num.saturating_to()
277    }
278
279    /// Updates the block environment of the running EVM.
280    #[inline]
281    pub(crate) fn update_block(&mut self, f: impl FnOnce(&mut BlockEnvFor<FEN>)) {
282        let mut block = *self.evm.block();
283        f(&mut block);
284        self.evm.set_block(block);
285    }
286
287    /// Returns the transaction origin (`tx.origin`), including prank and broadcast overrides.
288    #[inline]
289    pub(crate) fn tx_caller(&self) -> Address {
290        self.state.origin_override.unwrap_or(self.evm.tx_env().origin)
291    }
292
293    /// Returns the transaction blob versioned hashes.
294    #[inline]
295    pub(crate) fn tx_blob_hashes(&self) -> Vec<B256> {
296        self.evm.tx_env().blob_hashes.iter().map(|hash| B256::from(*hash)).collect()
297    }
298
299    /// Returns the active fork ID, if any.
300    #[inline]
301    pub(crate) fn active_fork_id(&self) -> Option<LocalForkId> {
302        self.db().active_fork_id()
303    }
304
305    /// Returns the active fork URL, if any.
306    #[inline]
307    pub(crate) fn active_fork_url(&self) -> Option<String> {
308        self.db().active_fork_url()
309    }
310
311    /// Returns the active fork block number, if any.
312    #[inline]
313    pub(crate) fn active_fork_block_number(&self) -> Option<u64> {
314        self.db().active_fork_block_number()
315    }
316
317    /// Returns the active fork options, if any.
318    #[inline]
319    pub(crate) fn active_fork_options(&self) -> Option<CreateFork> {
320        self.db().active_fork_options()
321    }
322
323    /// Returns whether a fork is active.
324    #[inline]
325    pub(crate) fn is_forked_mode(&self) -> bool {
326        self.db().is_forked_mode()
327    }
328
329    /// Returns whether `account` persists across forks.
330    #[inline]
331    pub(crate) fn is_persistent(&self, account: &Address) -> bool {
332        self.db().is_persistent(account)
333    }
334}
335
336#[cold]
337fn precompile_error(address: &Address) -> Error {
338    fmt_err!("cannot use precompile {address} as an argument")
339}