Skip to main content

foundry_cheatcodes/
utils.rs

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