feat(script): revert if address(this) used by gap-editor · Pull Request #10295 · foundry-rs/foundry (original) (raw)

Motivation

Closes #10289

Users can accidentally use address(this) within forge script contracts, often intending to refer to the script contract itself for operations like transferring ownership or sending tokens during deployment. However, the address(this) in a script context refers to a temporary, locally deployed contract instance used for the simulation. This address does not exist on the target network and relying on it leads to deployment errors or incorrect state on-chain.

This PR introduces a warning mechanism to alert users when address(this) is used during a forge script execution, helping prevent these common mistakes.

Solution

  1. Introduced ScriptAddressWarnInspector:
    • Defined a new revm::Inspector implementation named ScriptAddressWarnInspector within crates/evm/evm/src/inspectors/stack.rs.
    • This inspector implements the step method, which checks if the currently executing EVM opcode is ADDRESS (0x30).
    • If the ADDRESS opcode is detected, it prints a warning message to stderr: "forge script warning: Usage of \address(this)` detected. Script contracts are ephemeral and their addresses should not be relied upon."`
  2. Integrated into InspectorStack:
    • Added an optional address_warn_inspector field to the InspectorStackInner struct.
    • Added a corresponding address_warn boolean flag and a builder method .address_warn_inspector(bool) to InspectorStackBuilder.
    • Updated the InspectorStackBuilder::build method to instantiate ScriptAddressWarnInspector if the address_warn flag is true.
    • Modified the Inspector implementation for InspectorStackRefMut to invoke the step method of the address_warn_inspector if it's present.
  3. Enabled for forge script:
    • In crates/script/src/lib.rs, within the _get_runner function (which configures the Executor for scripts), modified the ExecutorBuilder chain to call .address_warn_inspector(true). This ensures the warning inspector is always active during forge script runs.

This approach leverages the existing revm inspector system to passively detect the opcode usage without significantly impacting performance and provides a clear warning directly to the user during script execution.

PR Checklist