foundry_evm/inspectors/
chisel_state.rs1use alloy_primitives::U256;
2use evm2::{
3 EvmTypesHost, Inspector,
4 interpreter::{Host, Interpreter},
5};
6
7#[derive(Clone, Debug, Default)]
9pub struct ChiselState {
10 pub final_pc: Option<usize>,
12 pub state: Option<(Vec<U256>, Vec<u8>)>,
15 at_final_pc: bool,
17}
18
19impl ChiselState {
20 #[inline]
22 pub const fn new(final_pc: Option<usize>) -> Self {
23 Self { final_pc, state: None, at_final_pc: false }
24 }
25}
26
27fn is_root_frame<T: EvmTypesHost>(interp: &mut Interpreter<'_, '_, T>) -> bool {
29 interp.message().depth == interp.host().initial_call_depth()
30}
31
32impl<T: EvmTypesHost> Inspector<T> for ChiselState {
33 fn initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, T>) {
34 if is_root_frame(interp) {
35 self.state = None;
36 self.at_final_pc = false;
37 }
38 }
39
40 #[cold]
41 fn step(&mut self, interp: &mut Interpreter<'_, '_, T>) {
42 if is_root_frame(interp) {
43 self.at_final_pc = self.final_pc == Some(interp.pc());
46 }
47 }
48
49 #[cold]
50 fn step_end(&mut self, interp: &mut Interpreter<'_, '_, T>) {
51 if is_root_frame(interp)
56 && (self.at_final_pc
57 || self.final_pc.is_some_and(|pc| interp.pc() == pc + 1)
58 || (self.state.is_none() && interp.result().is_err()))
59 {
60 self.state =
61 Some((interp.stack().as_slice().to_vec(), interp.memory().as_slice().to_vec()));
62 }
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69 use alloy_network::TransactionBuilder;
70 use alloy_primitives::{Address, hex};
71 use evm2::{
72 bytecode::Bytecode,
73 evm::{AccountInfo, InMemoryDB},
74 };
75 use foundry_evm_core::evm::{
76 EthEvmNetwork, EvmEnv, EvmFactoryFor, FoundryEvmFactory, FoundryTxConversion, SpecFor,
77 TransactionRequestFor, TypesFor,
78 };
79
80 fn execute(inspector: ChiselState, code: &str) -> ChiselState {
81 let target = Address::with_last_byte(0x40);
82 let child = Address::with_last_byte(0x20);
83 let mut db = InMemoryDB::default();
84 for (address, code) in [(target, code), (child, "61cafe5f52600700")] {
85 db.insert_account_info(
86 &address,
87 AccountInfo::default()
88 .with_code(Bytecode::new_legacy(hex::decode(code).unwrap().into())),
89 );
90 }
91 let factory = EvmFactoryFor::<EthEvmNetwork>::default();
92 let spec = SpecFor::<EthEvmNetwork>::default();
93 let mut evm =
94 factory.create_evm(db, EvmEnv::new(spec, factory.version(spec, 1), Default::default()));
95 evm.set_inspector(inspector);
96 let request = TransactionRequestFor::<EthEvmNetwork>::default()
97 .with_from(Address::with_last_byte(0x30))
98 .with_to(target)
99 .with_nonce(0)
100 .with_chain_id(1)
101 .with_gas_limit(1_000_000)
102 .with_max_fee_per_gas(0)
103 .with_max_priority_fee_per_gas(0);
104 let tx = TypesFor::<EthEvmNetwork>::tx_from_request(request).unwrap();
105 let result = evm.transact(&tx).unwrap().commit();
106 assert!(result.status);
107 *evm.clear_inspector_as::<ChiselState>().unwrap()
108 }
109
110 #[test]
111 fn captures_final_state_without_an_executed_source_match() {
112 for final_pc in [None, Some(100)] {
113 let inspector = execute(ChiselState::new(final_pc), "6113375f52602a00");
115 assert_eq!(
116 inspector.state,
117 Some((vec![U256::from(42)], U256::from(0x1337).to_be_bytes::<32>().to_vec()))
118 );
119 }
120 }
121
122 #[test]
123 fn preserves_source_snapshot_after_push_and_jump() {
124 for (code, final_pc, expected_stack) in [
125 ("6113375f52602a00", 0, vec![U256::from(0x1337)]),
127 ("602a600656fe5b5000", 4, vec![U256::from(42)]),
129 ] {
130 let inspector = execute(ChiselState::new(Some(final_pc)), code);
131 assert_eq!(inspector.state, Some((expected_stack, vec![])));
132 }
133 }
134
135 #[test]
136 fn nested_calls_do_not_replace_root_state() {
137 for (final_pc, expected_stack) in [(None, vec![U256::from(42)]), (Some(4), vec![])] {
138 let inspector =
141 execute(ChiselState::new(final_pc), "6113375f525f5f5f5f5f60205af150602a00");
142 assert_eq!(
143 inspector.state,
144 Some((expected_stack, U256::from(0x1337).to_be_bytes::<32>().to_vec()))
145 );
146 }
147 }
148
149 #[test]
150 fn resets_snapshot_between_executions() {
151 let inspector = execute(ChiselState::new(Some(4)), "6113375f52602a00");
152 let inspector = execute(inspector, "602b00");
154 assert_eq!(inspector.state, Some((vec![U256::from(43)], vec![])));
155 }
156}