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
- Introduced
ScriptAddressWarnInspector
:- Defined a new
revm::Inspector
implementation namedScriptAddressWarnInspector
withincrates/evm/evm/src/inspectors/stack.rs
. - This inspector implements the
step
method, which checks if the currently executing EVM opcode isADDRESS
(0x30). - If the
ADDRESS
opcode is detected, it prints a warning message tostderr
:"forge script warning: Usage of \
address(this)` detected. Script contracts are ephemeral and their addresses should not be relied upon."`
- Defined a new
- Integrated into
InspectorStack
:- Added an optional
address_warn_inspector
field to theInspectorStackInner
struct. - Added a corresponding
address_warn
boolean flag and a builder method.address_warn_inspector(bool)
toInspectorStackBuilder
. - Updated the
InspectorStackBuilder::build
method to instantiateScriptAddressWarnInspector
if theaddress_warn
flag is true. - Modified the
Inspector
implementation forInspectorStackRefMut
to invoke thestep
method of theaddress_warn_inspector
if it's present.
- Added an optional
- Enabled for
forge script
:- In
crates/script/src/lib.rs
, within the_get_runner
function (which configures theExecutor
for scripts), modified theExecutorBuilder
chain to call.address_warn_inspector(true)
. This ensures the warning inspector is always active duringforge script
runs.
- In
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
- Added Tests
- Added Documentation
- No Breaking changes