Skip to main content

foundry_evm/inspectors/
logs.rs

1use alloy_primitives::Log;
2use alloy_sol_types::{SolEvent, SolInterface, SolValue};
3use evm2::{
4    EvmTypesHost, Inspector,
5    interpreter::{InstrStop, Interpreter, Message, MessageResult},
6};
7use foundry_cheatcodes::message_result;
8use foundry_common::{ErrorExt, fmt::ConsoleFmt, sh_println};
9use foundry_evm_core::{
10    abi::console, constants::HARDHAT_CONSOLE_ADDRESS, decode::decode_console_log,
11};
12
13/// An inspector that collects logs during execution.
14///
15/// The inspector collects logs from the `LOG` opcodes as well as Hardhat-style `console.sol` logs.
16#[derive(Clone, Debug)]
17pub enum LogCollector {
18    /// The collected logs. Includes both `LOG` opcodes and Hardhat-style `console.sol` logs.
19    Capture { logs: Vec<Log> },
20    /// Print logs directly to stdout.
21    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<T: EvmTypesHost>(
34        &mut self,
35        interp: &Interpreter<'_, '_, T>,
36        message: &Message<T>,
37    ) -> Option<MessageResult<T>> {
38        if let Err(err) = self.hardhat_log(message.input.as_bytes(interp.memory())) {
39            return Some(message_result(message, InstrStop::Revert, err.abi_encode_revert()));
40        }
41        None
42    }
43
44    fn hardhat_log(&mut self, data: &[u8]) -> alloy_sol_types::Result<()> {
45        let decoded = console::hh::ConsoleCalls::abi_decode(data)?;
46        for line in decoded.fmt(Default::default()).lines() {
47            self.console_log(line);
48        }
49        Ok(())
50    }
51
52    fn push_raw_log(&mut self, log: Log) {
53        match self {
54            Self::Capture { logs } => logs.push(log),
55            Self::LiveLogs => {
56                if let Some(msg) = decode_console_log(&log) {
57                    sh_println!("{msg}").expect("fail printing to stdout");
58                } else {
59                    // This case should not happen if the users call through forge-std.
60                    // We print the log data for the user nonetheless.
61                    sh_println!("console.log({:?}, {})", log.data.topics(), log.data.data)
62                        .expect("fail printing to stdout");
63                }
64            }
65        }
66    }
67
68    /// Records a `console.log` message, such as one emitted by a cheatcode.
69    pub fn console_log(&mut self, msg: &str) {
70        match self {
71            Self::Capture { logs } => logs.push(new_console_log(msg)),
72            Self::LiveLogs => sh_println!("{msg}").expect("fail printing to stdout"),
73        }
74    }
75}
76
77impl<T: EvmTypesHost> Inspector<T> for LogCollector {
78    fn log(&mut self, log: &Log, _host: &mut T::Host<'_>) {
79        self.push_raw_log(log.clone());
80    }
81
82    fn call(
83        &mut self,
84        interp: &mut Interpreter<'_, '_, T>,
85        message: &mut Message<T>,
86    ) -> Option<MessageResult<T>> {
87        if message.destination == HARDHAT_CONSOLE_ADDRESS {
88            return self.do_hardhat_log::<T>(interp, message);
89        }
90        None
91    }
92}
93
94/// Creates a `console.log(string)` event.
95fn new_console_log(msg: &str) -> Log {
96    Log::new_unchecked(
97        HARDHAT_CONSOLE_ADDRESS,
98        vec![console::ds::log::SIGNATURE_HASH],
99        msg.abi_encode().into(),
100    )
101}