Skip to main content

foundry_evm/inspectors/
script.rs

1use alloy_primitives::Address;
2use evm2::{
3    EvmTypesHost, Inspector, InspectorConfig,
4    interpreter::{Interpreter, op},
5};
6use foundry_evm_core::utils::opcodes;
7
8/// Revert reason for `address(this)` in a script contract.
9const ADDRESS_IN_SCRIPT: &[u8] = b"Usage of `address(this)` detected in script contract. Script contracts are ephemeral and their addresses should not be relied upon.";
10
11/// An inspector that enforces certain rules during script execution.
12///
13/// Currently, it reverts if the `ADDRESS` opcode is used within the script's main contract.
14#[derive(Clone, Debug, Default)]
15pub struct ScriptExecutionInspector {
16    /// The address of the script contract being executed.
17    pub script_address: Address,
18}
19
20impl<T: EvmTypesHost> Inspector<T> for ScriptExecutionInspector {
21    fn inspector_config(&self) -> InspectorConfig {
22        InspectorConfig::new().with_steps(opcodes([op::ADDRESS]))
23    }
24
25    fn step(&mut self, interp: &mut Interpreter<'_, '_, T>) {
26        // Check if both target and bytecode address are the same as script contract address
27        // (allow calling external libraries when bytecode address is different).
28        let message = interp.message();
29        if interp.opcode() == op::ADDRESS
30            && message.destination == self.script_address
31            && message.code_address == self.script_address
32        {
33            foundry_cheatcodes::revert_frame(interp, ADDRESS_IN_SCRIPT);
34        }
35    }
36}