1use 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#[derive(Clone, Debug)]
29pub struct CheatcodesCore {
30 pub config: Arc<CheatsConfig>,
32 pub analysis: Option<CheatcodeAnalysis>,
34 pub labels: AddressHashMap<String>,
36 pub test_context: TestContext,
38 pub fs_commit: bool,
41 pub serialized_jsons: BTreeMap<String, BTreeMap<String, Value>>,
44 test_runner: Option<TestRunner>,
47 pub wallets: Option<Wallets>,
49 pub private_key_signers: HashMap<U256, PrivateKeySigner>,
51 pub mocked_calls: HashMap<Address, BTreeMap<MockCallDataContext, VecDeque<MockCallReturnData>>>,
54 pub mocked_functions: HashMap<Address, HashMap<Bytes, Address>>,
56 pub expected_calls: ExpectedCallTracker,
58 pub mapping_slots: Option<AddressHashMap<MappingSlots>>,
60 pub recorded_logs: Option<Vec<crate::Vm::Log>>,
62 pub recorded_logs_generation: u64,
65 pub access_list: Option<AccessList>,
67 pub intercept_next_create_call: bool,
69 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 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 pub fn set_analysis(&mut self, analysis: CheatcodeAnalysis) {
106 self.analysis = Some(analysis);
107 }
108
109 pub fn wallets(&mut self) -> &Wallets {
111 self.wallets.get_or_insert_with(|| Wallets::new(MultiWallet::default(), None))
112 }
113
114 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 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 pub fn arbitrary_storage(&mut self) -> &mut ArbitraryStorage {
148 self.arbitrary_storage.get_or_insert_with(ArbitraryStorage::default)
149 }
150
151 pub fn mock_call_sequence(&mut self, callee: Address, calldata: Bytes, returns: &[Bytes]) {
154 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 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#[derive(Debug, Default)]
180pub struct TestContext {
181 pub opened_read_files: HashMap<PathBuf, BufReader<File>>,
183}
184
185impl Clone for TestContext {
187 fn clone(&self) -> Self {
188 Default::default()
189 }
190}
191
192impl TestContext {
193 pub fn clear(&mut self) {
195 self.opened_read_files.clear();
196 }
197}