Skip to main content

foundry_cheatcodes/
state.rs

1//! Cheatcode state shared by both execution engines.
2
3use crate::{
4    CheatcodeAnalysis, CheatsConfig, Error, ExpectedCallTracker, Wallets,
5    evm::mock::{MockCallDataContext, MockCallReturnData},
6    inspector::ArbitraryStorage,
7};
8use alloy_primitives::{
9    Address, Bytes, U256,
10    map::{AddressHashMap, HashMap},
11};
12use alloy_rpc_types::AccessList;
13use alloy_signer_local::PrivateKeySigner;
14use foundry_common::mapping_slots::MappingSlots;
15use foundry_wallets::wallet_multi::MultiWallet;
16use proptest::test_runner::{RngAlgorithm, TestRng, TestRunner};
17use rand::Rng;
18use serde_json::Value;
19use std::{
20    collections::{BTreeMap, VecDeque},
21    fs::File,
22    io::BufReader,
23    path::PathBuf,
24    sync::Arc,
25};
26
27/// Cheatcode state that does not depend on the execution engine.
28#[derive(Clone, Debug)]
29pub struct CheatcodesCore {
30    /// Additional, user configurable context this Inspector has access to when inspecting a call.
31    pub config: Arc<CheatsConfig>,
32    /// Solar compiler instance, to grant syntactic and semantic analysis capabilities
33    pub analysis: Option<CheatcodeAnalysis>,
34    /// Address labels
35    pub labels: AddressHashMap<String>,
36    /// Test-scoped context holding data that needs to be reset every test run
37    pub test_context: TestContext,
38    /// Whether to commit FS changes such as file creations, writes and deletes.
39    /// Used to prevent duplicate changes file executing non-committing calls.
40    pub fs_commit: bool,
41    /// Serialized JSON values.
42    // **Note**: both must a BTreeMap to ensure the order of the keys is deterministic.
43    pub serialized_jsons: BTreeMap<String, BTreeMap<String, Value>>,
44    /// Optional cheatcodes `TestRunner`. Used for generating random values from uint and int
45    /// strategies.
46    test_runner: Option<TestRunner>,
47    /// Unlocked wallets used in scripts and testing of scripts.
48    pub wallets: Option<Wallets>,
49    /// Parsed secp256k1 private-key signers for repeated `vm.addr` / `vm.sign` calls.
50    pub private_key_signers: HashMap<U256, PrivateKeySigner>,
51    /// Mocked calls
52    // **Note**: inner must a BTreeMap because of special `Ord` impl for `MockCallDataContext`
53    pub mocked_calls: HashMap<Address, BTreeMap<MockCallDataContext, VecDeque<MockCallReturnData>>>,
54    /// Mocked functions. Maps target address to be mocked to pair of (calldata, mock address).
55    pub mocked_functions: HashMap<Address, HashMap<Bytes, Address>>,
56    /// Expected calls
57    pub expected_calls: ExpectedCallTracker,
58    /// Mapping slots.
59    pub mapping_slots: Option<AddressHashMap<MappingSlots>>,
60    /// Recorded logs
61    pub recorded_logs: Option<Vec<crate::Vm::Log>>,
62    /// Bumped by `recordLogs` and `getRecordedLogs*` so open frame checkpoints know the buffer
63    /// was reset.
64    pub recorded_logs_generation: u64,
65    /// Current EIP-2930 access lists.
66    pub access_list: Option<AccessList>,
67    /// Whether the next contract creation should be intercepted to return its initcode.
68    pub intercept_next_create_call: bool,
69    /// Addresses with arbitrary storage.
70    pub arbitrary_storage: Option<ArbitraryStorage>,
71}
72
73impl Default for CheatcodesCore {
74    fn default() -> Self {
75        Self::new(Default::default())
76    }
77}
78
79impl CheatcodesCore {
80    /// Creates a new `CheatcodesCore` with the given settings.
81    pub fn new(config: Arc<CheatsConfig>) -> Self {
82        Self {
83            analysis: None,
84            labels: config.labels.clone(),
85            config,
86            test_context: Default::default(),
87            fs_commit: true,
88            serialized_jsons: Default::default(),
89            test_runner: Default::default(),
90            wallets: Default::default(),
91            private_key_signers: Default::default(),
92            mocked_calls: Default::default(),
93            mocked_functions: Default::default(),
94            expected_calls: Default::default(),
95            mapping_slots: Default::default(),
96            recorded_logs: Default::default(),
97            recorded_logs_generation: Default::default(),
98            access_list: Default::default(),
99            intercept_next_create_call: Default::default(),
100            arbitrary_storage: Default::default(),
101        }
102    }
103
104    /// Enables cheatcode analysis capabilities by providing a solar compiler instance.
105    pub fn set_analysis(&mut self, analysis: CheatcodeAnalysis) {
106        self.analysis = Some(analysis);
107    }
108
109    /// Returns the configured wallets if available, else creates a new instance.
110    pub fn wallets(&mut self) -> &Wallets {
111        self.wallets.get_or_insert_with(|| Wallets::new(MultiWallet::default(), None))
112    }
113
114    /// Sets the unlocked wallets.
115    pub fn set_wallets(&mut self, wallets: Wallets) {
116        self.wallets = Some(wallets);
117    }
118
119    pub fn rng(&mut self) -> &mut impl Rng {
120        self.test_runner().rng()
121    }
122
123    pub fn test_runner(&mut self) -> &mut TestRunner {
124        self.test_runner.get_or_insert_with(|| match self.config.seed {
125            Some(seed) => TestRunner::new_with_rng(
126                proptest::test_runner::Config::default(),
127                TestRng::from_seed(RngAlgorithm::ChaCha, &seed.to_be_bytes::<32>()),
128            ),
129            None => TestRunner::new(proptest::test_runner::Config::default()),
130        })
131    }
132
133    pub fn set_seed(&mut self, seed: U256) {
134        self.test_runner = Some(TestRunner::new_with_rng(
135            proptest::test_runner::Config::default(),
136            TestRng::from_seed(RngAlgorithm::ChaCha, &seed.to_be_bytes::<32>()),
137        ));
138    }
139
140    /// Returns struct definitions from the analysis, if available.
141    pub fn struct_defs(&self) -> Option<&foundry_common::fmt::StructDefinitions> {
142        self.analysis.as_ref().and_then(|analysis| analysis.struct_defs().ok())
143    }
144
145    /// Returns existing or set a default `ArbitraryStorage` option.
146    /// Used by `setArbitraryStorage` cheatcode to track addresses with arbitrary storage.
147    pub fn arbitrary_storage(&mut self) -> &mut ArbitraryStorage {
148        self.arbitrary_storage.get_or_insert_with(ArbitraryStorage::default)
149    }
150
151    /// Answers the calls to `callee` whose calldata starts with `calldata` with `returns` in
152    /// order, and reverts every later call.
153    pub fn mock_call_sequence(&mut self, callee: Address, calldata: Bytes, returns: &[Bytes]) {
154        // A mock repeats its last return, so two reverting ends show if a call reached the first.
155        let end = MockCallReturnData {
156            reverts: true,
157            data: Error::encode("mocked call sequence has no more returns"),
158        };
159        let queue = returns
160            .iter()
161            .map(|data| MockCallReturnData { reverts: false, data: data.clone() })
162            .chain([end.clone(), end])
163            .collect();
164        self.mocked_calls
165            .entry(callee)
166            .or_default()
167            .insert(MockCallDataContext { calldata, value: None }, queue);
168    }
169
170    /// Returns whether a call to `callee` ran past the returns of a
171    /// [`Self::mock_call_sequence`] or of any other mock of `callee` with a single return, or
172    /// `None` when the mocks were cleared.
173    pub fn mock_call_sequence_exhausted(&self, callee: Address) -> Option<bool> {
174        self.mocked_calls.get(&callee).map(|mocks| mocks.values().any(|queue| queue.len() < 2))
175    }
176}
177
178/// Contains additional, test specific resources that should be kept for the duration of the test
179#[derive(Debug, Default)]
180pub struct TestContext {
181    /// Buffered readers for files opened for reading (path => BufReader mapping)
182    pub opened_read_files: HashMap<PathBuf, BufReader<File>>,
183}
184
185/// Every time we clone `Context`, we want it to be empty
186impl Clone for TestContext {
187    fn clone(&self) -> Self {
188        Default::default()
189    }
190}
191
192impl TestContext {
193    /// Clears the context.
194    pub fn clear(&mut self) {
195        self.opened_read_files.clear();
196    }
197}