Skip to main content

foundry_cheatcodes/
utils.rs

1//! Implementations of [`Utilities`](spec::Group::Utilities) cheatcodes.
2
3use crate::{Cheatcode, Cheatcodes, CheatcodesExecutor, CheatsCtxt, Result, Vm::*};
4use alloy_dyn_abi::{DynSolType, DynSolValue, Resolver, TypedData, eip712_parser::EncodeType};
5use alloy_ens::namehash;
6use alloy_primitives::{B64, Bytes, I256, U256, aliases::B32, keccak256, map::HashMap};
7use alloy_rlp::{Decodable, Encodable};
8use alloy_sol_types::SolValue;
9use foundry_common::{TYPE_BINDING_PREFIX, fs};
10use foundry_config::fs_permissions::FsAccessKind;
11use foundry_evm_core::{constants::DEFAULT_CREATE2_DEPLOYER, evm::FoundryEvmNetwork};
12use foundry_evm_fuzz::strategies::BoundMutator;
13use proptest::prelude::Strategy;
14use rand::{Rng, RngCore, seq::SliceRandom};
15use revm::context::{ContextTr, JournalTr};
16use std::path::PathBuf;
17
18/// Contains locations of traces ignored via cheatcodes.
19///
20/// The way we identify location in traces is by (node_idx, item_idx) tuple where node_idx is an
21/// index of a call trace node, and item_idx is a value between 0 and `node.ordering.len()` where i
22/// represents point after ith item, and 0 represents the beginning of the node trace.
23#[derive(Debug, Default, Clone)]
24pub struct IgnoredTraces {
25    /// Mapping from (start_node_idx, start_item_idx) to (end_node_idx, end_item_idx) representing
26    /// ranges of trace nodes to ignore.
27    pub ignored: HashMap<(usize, usize), (usize, usize)>,
28    /// Keeps track of (start_node_idx, start_item_idx) of the last `vm.pauseTracing` call.
29    pub last_pause_call: Option<(usize, usize)>,
30}
31
32impl Cheatcode for labelCall {
33    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
34        let Self { account, newLabel } = self;
35        state.labels.insert(*account, newLabel.clone());
36        Ok(Default::default())
37    }
38}
39
40impl Cheatcode for getLabelCall {
41    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
42        let Self { account } = self;
43        Ok(match state.labels.get(account) {
44            Some(label) => label.abi_encode(),
45            None => format!("unlabeled:{account}").abi_encode(),
46        })
47    }
48}
49
50impl Cheatcode for computeCreateAddressCall {
51    fn apply<FEN: FoundryEvmNetwork>(&self, _state: &mut Cheatcodes<FEN>) -> Result {
52        let Self { nonce, deployer } = self;
53        ensure!(*nonce <= U256::from(u64::MAX), "nonce must be less than 2^64");
54        Ok(deployer.create(nonce.to()).abi_encode())
55    }
56}
57
58impl Cheatcode for computeCreate2Address_0Call {
59    fn apply<FEN: FoundryEvmNetwork>(&self, _state: &mut Cheatcodes<FEN>) -> Result {
60        let Self { salt, initCodeHash, deployer } = self;
61        Ok(deployer.create2(salt, initCodeHash).abi_encode())
62    }
63}
64
65impl Cheatcode for computeCreate2Address_1Call {
66    fn apply<FEN: FoundryEvmNetwork>(&self, _state: &mut Cheatcodes<FEN>) -> Result {
67        let Self { salt, initCodeHash } = self;
68        Ok(DEFAULT_CREATE2_DEPLOYER.create2(salt, initCodeHash).abi_encode())
69    }
70}
71
72impl Cheatcode for ensNamehashCall {
73    fn apply<FEN: FoundryEvmNetwork>(&self, _state: &mut Cheatcodes<FEN>) -> Result {
74        let Self { name } = self;
75        Ok(namehash(name).abi_encode())
76    }
77}
78
79impl Cheatcode for bound_0Call {
80    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
81        let Self { current, min, max } = *self;
82        let Some(mutated) = U256::bound(current, min, max, state.test_runner()) else {
83            bail!("cannot bound {current} in [{min}, {max}] range")
84        };
85        Ok(mutated.abi_encode())
86    }
87}
88
89impl Cheatcode for bound_1Call {
90    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
91        let Self { current, min, max } = *self;
92        let Some(mutated) = I256::bound(current, min, max, state.test_runner()) else {
93            bail!("cannot bound {current} in [{min}, {max}] range")
94        };
95        Ok(mutated.abi_encode())
96    }
97}
98
99impl Cheatcode for randomUint_0Call {
100    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
101        random_uint(state, None, None)
102    }
103}
104
105impl Cheatcode for randomUint_1Call {
106    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
107        let Self { min, max } = *self;
108        random_uint(state, None, Some((min, max)))
109    }
110}
111
112impl Cheatcode for randomUint_2Call {
113    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
114        let Self { bits } = *self;
115        random_uint(state, Some(bits), None)
116    }
117}
118
119impl Cheatcode for randomAddressCall {
120    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
121        Ok(DynSolValue::type_strategy(&DynSolType::Address)
122            .new_tree(state.test_runner())
123            .unwrap()
124            .current()
125            .abi_encode())
126    }
127}
128
129impl Cheatcode for randomInt_0Call {
130    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
131        random_int(state, None)
132    }
133}
134
135impl Cheatcode for randomInt_1Call {
136    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
137        let Self { bits } = *self;
138        random_int(state, Some(bits))
139    }
140}
141
142impl Cheatcode for randomBoolCall {
143    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
144        let rand_bool: bool = state.rng().random();
145        Ok(rand_bool.abi_encode())
146    }
147}
148
149impl Cheatcode for randomBytesCall {
150    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
151        let Self { len } = *self;
152        let len = usize::try_from(len)
153            .map_err(|_| fmt_err!("bytes length cannot exceed {}", usize::MAX))?;
154        let mut bytes = vec![0u8; len];
155        state.rng().fill_bytes(&mut bytes);
156        Ok(bytes.abi_encode())
157    }
158}
159
160impl Cheatcode for randomBytes4Call {
161    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
162        let rand_u32 = state.rng().next_u32();
163        Ok(B32::from(rand_u32).abi_encode())
164    }
165}
166
167impl Cheatcode for randomBytes8Call {
168    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
169        let rand_u64 = state.rng().next_u64();
170        Ok(B64::from(rand_u64).abi_encode())
171    }
172}
173
174impl Cheatcode for pauseTracingCall {
175    fn apply_full<FEN: FoundryEvmNetwork>(
176        &self,
177        ccx: &mut CheatsCtxt<'_, '_, FEN>,
178        executor: &mut dyn CheatcodesExecutor<FEN>,
179    ) -> Result {
180        let Some(tracer) = executor.tracing_inspector() else {
181            // No tracer -> nothing to pause
182            return Ok(Default::default());
183        };
184
185        // If paused earlier, ignore the call
186        if ccx.state.ignored_traces.last_pause_call.is_some() {
187            return Ok(Default::default());
188        }
189
190        let cur_node = &tracer.traces().nodes().last().expect("no trace nodes");
191        ccx.state.ignored_traces.last_pause_call = Some((cur_node.idx, cur_node.ordering.len()));
192
193        Ok(Default::default())
194    }
195}
196
197impl Cheatcode for resumeTracingCall {
198    fn apply_full<FEN: FoundryEvmNetwork>(
199        &self,
200        ccx: &mut CheatsCtxt<'_, '_, FEN>,
201        executor: &mut dyn CheatcodesExecutor<FEN>,
202    ) -> Result {
203        let Some(tracer) = executor.tracing_inspector() else {
204            // No tracer -> nothing to unpause
205            return Ok(Default::default());
206        };
207
208        let Some(start) = ccx.state.ignored_traces.last_pause_call.take() else {
209            // Nothing to unpause
210            return Ok(Default::default());
211        };
212
213        let node = &tracer.traces().nodes().last().expect("no trace nodes");
214        ccx.state.ignored_traces.ignored.insert(start, (node.idx, node.ordering.len()));
215
216        Ok(Default::default())
217    }
218}
219
220impl Cheatcode for interceptInitcodeCall {
221    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
222        let Self {} = self;
223        if state.intercept_next_create_call {
224            bail!("vm.interceptInitcode() has already been called")
225        }
226        state.intercept_next_create_call = true;
227        Ok(Default::default())
228    }
229}
230
231impl Cheatcode for setArbitraryStorage_0Call {
232    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
233        let Self { target } = self;
234        ccx.state.arbitrary_storage().mark_arbitrary(target, false);
235
236        Ok(Default::default())
237    }
238}
239
240impl Cheatcode for setArbitraryStorage_1Call {
241    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
242        let Self { target, overwrite } = self;
243        ccx.state.arbitrary_storage().mark_arbitrary(target, *overwrite);
244
245        Ok(Default::default())
246    }
247}
248
249impl Cheatcode for copyStorageCall {
250    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
251        let Self { from, to } = self;
252
253        ensure!(
254            !ccx.state.has_arbitrary_storage(to),
255            "target address cannot have arbitrary storage"
256        );
257
258        if let Ok(from_account) = ccx.ecx.journal_mut().load_account(*from) {
259            let from_storage = from_account.storage.clone();
260            if ccx.ecx.journal_mut().load_account(*to).is_ok() {
261                // SAFETY: We ensured the account was already loaded.
262                ccx.ecx.journal_mut().evm_state_mut().get_mut(to).unwrap().storage = from_storage;
263                if let Some(arbitrary_storage) = &mut ccx.state.arbitrary_storage {
264                    arbitrary_storage.mark_copy(from, to);
265                }
266            }
267        }
268
269        Ok(Default::default())
270    }
271}
272
273impl Cheatcode for sortCall {
274    fn apply<FEN: FoundryEvmNetwork>(&self, _state: &mut Cheatcodes<FEN>) -> Result {
275        let Self { array } = self;
276
277        let mut sorted_values = array.clone();
278        sorted_values.sort();
279
280        Ok(sorted_values.abi_encode())
281    }
282}
283
284impl Cheatcode for shuffleCall {
285    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
286        let Self { array } = self;
287
288        let mut shuffled_values = array.clone();
289        let rng = state.rng();
290        shuffled_values.shuffle(rng);
291
292        Ok(shuffled_values.abi_encode())
293    }
294}
295
296impl Cheatcode for setSeedCall {
297    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
298        let Self { seed } = self;
299        ccx.state.set_seed(*seed);
300        Ok(Default::default())
301    }
302}
303
304fn random_uint<FEN: FoundryEvmNetwork>(
305    state: &mut Cheatcodes<FEN>,
306    bits: Option<U256>,
307    bounds: Option<(U256, U256)>,
308) -> Result {
309    if let Some(bits) = bits {
310        let bits = usize::try_from(bits)
311            .ok()
312            .filter(|bits| *bits <= 256)
313            .ok_or_else(|| fmt_err!("number of bits cannot exceed 256"))?;
314        return Ok(DynSolValue::type_strategy(&DynSolType::Uint(bits))
315            .new_tree(state.test_runner())
316            .unwrap()
317            .current()
318            .abi_encode());
319    }
320
321    if let Some((min, max)) = bounds {
322        ensure!(min <= max, "min must be less than or equal to max");
323        let exclusive_modulo = max - min;
324        let mut random_number: U256 = state.rng().random();
325        if exclusive_modulo != U256::MAX {
326            let inclusive_modulo = exclusive_modulo + U256::from(1);
327            random_number %= inclusive_modulo;
328        }
329        random_number += min;
330        return Ok(random_number.abi_encode());
331    }
332
333    Ok(DynSolValue::type_strategy(&DynSolType::Uint(256))
334        .new_tree(state.test_runner())
335        .unwrap()
336        .current()
337        .abi_encode())
338}
339
340fn random_int<FEN: FoundryEvmNetwork>(state: &mut Cheatcodes<FEN>, bits: Option<U256>) -> Result {
341    let bits = bits.unwrap_or(U256::from(256));
342    let bits = usize::try_from(bits)
343        .ok()
344        .filter(|bits| *bits <= 256)
345        .ok_or_else(|| fmt_err!("number of bits cannot exceed 256"))?;
346    Ok(DynSolValue::type_strategy(&DynSolType::Int(bits))
347        .new_tree(state.test_runner())
348        .unwrap()
349        .current()
350        .abi_encode())
351}
352
353impl Cheatcode for eip712HashType_0Call {
354    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
355        let Self { typeNameOrDefinition } = self;
356
357        let type_def = get_canonical_type_def(typeNameOrDefinition, state, None)?;
358
359        Ok(keccak256(type_def.as_bytes()).to_vec())
360    }
361}
362
363impl Cheatcode for eip712HashType_1Call {
364    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
365        let Self { bindingsPath, typeName } = self;
366
367        let path = state.config.ensure_path_allowed(bindingsPath, FsAccessKind::Read)?;
368        let type_def = get_type_def_from_bindings(typeName, path, &state.config.root)?;
369
370        Ok(keccak256(type_def.as_bytes()).to_vec())
371    }
372}
373
374impl Cheatcode for eip712HashStruct_0Call {
375    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
376        let Self { typeNameOrDefinition, abiEncodedData } = self;
377
378        let type_def = get_canonical_type_def(typeNameOrDefinition, state, None)?;
379        let primary = &type_def[..type_def.find('(').unwrap_or(type_def.len())];
380
381        get_struct_hash(primary, &type_def, abiEncodedData)
382    }
383}
384
385impl Cheatcode for eip712HashStruct_1Call {
386    fn apply<FEN: FoundryEvmNetwork>(&self, state: &mut Cheatcodes<FEN>) -> Result {
387        let Self { bindingsPath, typeName, abiEncodedData } = self;
388
389        let path = state.config.ensure_path_allowed(bindingsPath, FsAccessKind::Read)?;
390        let type_def = get_type_def_from_bindings(typeName, path, &state.config.root)?;
391
392        get_struct_hash(typeName, &type_def, abiEncodedData)
393    }
394}
395
396impl Cheatcode for eip712HashTypedDataCall {
397    fn apply<FEN: FoundryEvmNetwork>(&self, _state: &mut Cheatcodes<FEN>) -> Result {
398        let Self { jsonData } = self;
399        let typed_data: TypedData = serde_json::from_str(jsonData)?;
400        let digest = typed_data.eip712_signing_hash()?;
401
402        Ok(digest.to_vec())
403    }
404}
405
406/// Returns EIP-712 canonical type definition from the provided string type representation or type
407/// name. If type name provided, then it looks up bindings from file generated by `forge bind-json`.
408fn get_canonical_type_def<FEN: FoundryEvmNetwork>(
409    name_or_def: &String,
410    state: &mut Cheatcodes<FEN>,
411    path: Option<PathBuf>,
412) -> Result<String> {
413    let type_def = if name_or_def.contains('(') {
414        // If the input contains '(', it must be the type definition.
415        EncodeType::parse(name_or_def).and_then(|parsed| parsed.canonicalize())?
416    } else {
417        // Otherwise, it must be the type name.
418        let path = path.as_ref().unwrap_or(&state.config.bind_json_path);
419        let path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
420        get_type_def_from_bindings(name_or_def, path, &state.config.root)?
421    };
422
423    Ok(type_def)
424}
425
426/// Returns the EIP-712 type definition from the bindings in the provided path.
427/// Assumes that read validation for the path has already been checked.
428fn get_type_def_from_bindings(name: &String, path: PathBuf, root: &PathBuf) -> Result<String> {
429    let content = fs::read_to_string(&path)?;
430
431    let type_defs: HashMap<&str, &str> = content
432        .lines()
433        .filter_map(|line| {
434            let relevant = line.trim().strip_prefix(TYPE_BINDING_PREFIX)?;
435            let (name, def) = relevant.split_once('=')?;
436            Some((name.trim(), def.trim().strip_prefix('"')?.strip_suffix("\";")?))
437        })
438        .collect();
439
440    match type_defs.get(name.as_str()) {
441        Some(value) => Ok(value.to_string()),
442        None => {
443            let bindings =
444                type_defs.keys().map(|k| format!(" - {k}")).collect::<Vec<String>>().join("\n");
445
446            bail!(
447                "'{}' not found in '{}'.{}",
448                name,
449                path.strip_prefix(root).unwrap_or(&path).to_string_lossy(),
450                if bindings.is_empty() {
451                    String::new()
452                } else {
453                    format!("\nAvailable bindings:\n{bindings}\n")
454                }
455            );
456        }
457    }
458}
459
460/// Returns the EIP-712 struct hash for provided name, definition and ABI encoded data.
461fn get_struct_hash(primary: &str, type_def: &String, abi_encoded_data: &Bytes) -> Result {
462    let mut resolver = Resolver::default();
463
464    // Populate the resolver by ingesting the canonical type definition, and then get the
465    // corresponding `DynSolType` of the primary type.
466    resolver
467        .ingest_string(type_def)
468        .map_err(|e| fmt_err!("Resolver failed to ingest type definition: {e}"))?;
469
470    let resolved_sol_type = resolver
471        .resolve(primary)
472        .map_err(|e| fmt_err!("Failed to resolve EIP-712 primary type '{primary}': {e}"))?;
473
474    // ABI-decode the bytes into `DynSolValue::CustomStruct`.
475    let sol_value = resolved_sol_type.abi_decode(abi_encoded_data.as_ref()).map_err(|e| {
476        fmt_err!("Failed to ABI decode using resolved_sol_type directly for '{primary}': {e}.")
477    })?;
478
479    // Use the resolver to properly encode the data.
480    let encoded_data: Vec<u8> = resolver
481        .encode_data(&sol_value)
482        .map_err(|e| fmt_err!("Failed to EIP-712 encode data for struct '{primary}': {e}"))?
483        .ok_or_else(|| fmt_err!("EIP-712 data encoding returned 'None' for struct '{primary}'"))?;
484
485    // Compute the type hash of the primary type.
486    let type_hash = resolver
487        .type_hash(primary)
488        .map_err(|e| fmt_err!("Failed to compute typeHash for EIP712 type '{primary}': {e}"))?;
489
490    // Compute the struct hash of the concatenated type hash and encoded data.
491    let mut bytes_to_hash = Vec::with_capacity(32 + encoded_data.len());
492    bytes_to_hash.extend_from_slice(type_hash.as_slice());
493    bytes_to_hash.extend_from_slice(&encoded_data);
494
495    Ok(keccak256(&bytes_to_hash).to_vec())
496}
497
498impl Cheatcode for toRlpCall {
499    fn apply<FEN: FoundryEvmNetwork>(&self, _state: &mut Cheatcodes<FEN>) -> Result {
500        let Self { data } = self;
501
502        let mut buf = Vec::new();
503        data.encode(&mut buf);
504
505        Ok(Bytes::from(buf).abi_encode())
506    }
507}
508
509impl Cheatcode for fromRlpCall {
510    fn apply<FEN: FoundryEvmNetwork>(&self, _state: &mut Cheatcodes<FEN>) -> Result {
511        let Self { rlp } = self;
512
513        let decoded: Vec<Bytes> = Vec::<Bytes>::decode(&mut rlp.as_ref())
514            .map_err(|e| fmt_err!("Failed to decode RLP: {e}"))?;
515
516        Ok(decoded.abi_encode())
517    }
518}