foundry_evm/inspectors/
logs.rs1use alloy_primitives::Log;
2use alloy_sol_types::{SolEvent, SolInterface, SolValue};
3use foundry_common::{ErrorExt, fmt::ConsoleFmt, sh_println};
4use foundry_evm_core::{
5 InspectorExt, abi::console, constants::HARDHAT_CONSOLE_ADDRESS, decode::decode_console_log,
6};
7use revm::{
8 Inspector,
9 context::ContextTr,
10 interpreter::{CallInputs, CallOutcome, Gas, InstructionResult, InterpreterResult},
11};
12
13#[derive(Clone, Debug)]
17pub enum LogCollector {
18 Capture { logs: Vec<Log> },
20 LiveLogs,
22}
23
24impl LogCollector {
25 pub fn into_captured_logs(self) -> Option<Vec<Log>> {
26 match self {
27 Self::Capture { logs } => Some(logs),
28 Self::LiveLogs => None,
29 }
30 }
31
32 #[cold]
33 fn do_hardhat_log<CTX: ContextTr>(
34 &mut self,
35 context: &mut CTX,
36 inputs: &CallInputs,
37 ) -> Option<CallOutcome> {
38 if let Err(err) = self.hardhat_log(&inputs.input.bytes(context)) {
39 let result = InstructionResult::Revert;
40 let output = err.abi_encode_revert();
41 return Some(CallOutcome {
42 result: InterpreterResult { result, output, gas: Gas::new(inputs.gas_limit) },
43 memory_offset: inputs.return_memory_offset.clone(),
44 was_precompile_called: true,
45 precompile_call_logs: vec![],
46 });
47 }
48 None
49 }
50
51 fn hardhat_log(&mut self, data: &[u8]) -> alloy_sol_types::Result<()> {
52 let decoded = console::hh::ConsoleCalls::abi_decode(data)?;
53 self.push_msg(&decoded.fmt(Default::default()));
54 Ok(())
55 }
56
57 fn push_raw_log(&mut self, log: Log) {
58 match self {
59 Self::Capture { logs } => logs.push(log),
60 Self::LiveLogs => {
61 if let Some(msg) = decode_console_log(&log) {
62 sh_println!("{msg}").expect("fail printing to stdout");
63 } else {
64 sh_println!("console.log({:?}, {})", log.data.topics(), log.data.data)
67 .expect("fail printing to stdout");
68 }
69 }
70 }
71 }
72
73 fn push_msg(&mut self, msg: &str) {
74 match self {
75 Self::Capture { logs } => logs.push(new_console_log(msg)),
76 Self::LiveLogs => sh_println!("{msg}").expect("fail printing to stdout"),
77 }
78 }
79}
80
81impl<CTX: ContextTr> Inspector<CTX> for LogCollector {
82 fn log(&mut self, _context: &mut CTX, log: Log) {
83 self.push_raw_log(log);
84 }
85
86 fn call(&mut self, context: &mut CTX, inputs: &mut CallInputs) -> Option<CallOutcome> {
87 if inputs.target_address == HARDHAT_CONSOLE_ADDRESS {
88 return self.do_hardhat_log(context, inputs);
89 }
90 None
91 }
92}
93
94impl InspectorExt for LogCollector {
95 fn console_log(&mut self, msg: &str) {
96 self.push_msg(msg);
97 }
98}
99
100fn new_console_log(msg: &str) -> Log {
102 Log::new_unchecked(
103 HARDHAT_CONSOLE_ADDRESS,
104 vec![console::ds::log::SIGNATURE_HASH],
105 msg.abi_encode().into(),
106 )
107}