Executive Summary & Direct Answer

A stateful precompile must not assume that a call made with DELEGATECALL has ordinary CALL semantics. Under delegation, the EVM preserves the calling contract’s execution context: address(this) and storage belong to that contract, while msg.sender and msg.value are inherited from the frame that invoked it. If a precompile authorizes using the inherited sender but updates state as though it were operating in its own context, a malicious intermediary can misuse the mismatch.

Test both sides of the boundary: use a Foundry harness to demonstrate the delegated EVM context, then verify that the target chain rejects DELEGATECALL and CALLCODE to stateful precompiles. A Solidity mock can expose the context bug, but it cannot prove that a chain’s native precompile or client implementation enforces its policy.

Environment and baseline specs

This guide uses Solidity ^0.8.24, Foundry, and a local EVM test harness. The relevant production behavior is chain-specific: stateful precompiles are implemented by the node client, not by Solidity bytecode. For Avalanche, the incident described in the post-mortem concerns libevm and subnet-evm, including AvalancheGo v1.13.1 and the later Granite resolution in AvalancheGo v1.14.0.

Use Solidity to write the attacker and test harness; use the target chain’s client or a network integration test to verify the precompile’s actual call-type policy. Do not treat a mock precompile as a substitute for that integration test.

A minimal Foundry configuration:

# foundry.toml
[profile.default]
src = "src"
test = "test"
solc_version = "0.8.24"
evm_version = "cancun"
optimizer = true
optimizer_runs = 200

evm_version selects an EVM instruction set for local execution. It does not install Avalanche’s libevm behavior or reproduce a particular AvalancheGo release.

The vulnerable mechanism: inherited identity, unexpected state context

Consider an admin-only stateful precompile. A naïve implementation may assume that, whenever it runs, its execution context is the precompile address and that msg.sender identifies the intended direct caller. That assumption fails if the precompile is reached through DELEGATECALL.

The key distinction is between the EVM execution context and the raw call target:

  • DELEGATECALL executes the target’s code using the caller’s storage and address context.
  • It preserves the current frame’s msg.sender and msg.value.
  • A stateful precompile that authorizes against the inherited sender but updates state under an assumed precompile context can combine permissions and state in an unintended way.

The Avalanche incident was not simply “msg.sender changes during delegatecall.” In a delegated frame, msg.sender is preserved. The problem described in the post-mortem was that stateful precompiles and libevm had divergent assumptions about delegated semantics and the distinction between the EVM-semantic caller/self and raw caller/self. That mismatch enabled caller impersonation in the precompile’s interpretation of identity and state.

A Solidity harness can make the EVM context visible. This mock records the context it observes; it is not a replica of Avalanche’s native precompile implementation:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract ContextProbe {
    address public observedSender;
    address public observedSelf;
    uint256 public observedValue;

    function record() external payable {
        observedSender = msg.sender;
        observedSelf = address(this);
        observedValue = msg.value;
    }
}

contract DelegateCaller {
    function delegateRecord(address target) external payable returns (bool ok) {
        (ok,) = target.delegatecall(
            abi.encodeWithSelector(ContextProbe.record.selector)
        );
    }
}

When DelegateCaller.delegateRecord is called by an EOA, ContextProbe.record executes in DelegateCaller’s context. Its storage writes therefore affect DelegateCaller’s slots, not the deployed ContextProbe’s storage. Its address(this) is the DelegateCaller; its msg.sender remains the EOA that called DelegateCaller.

That storage detail matters: Solidity’s declared fields do not make the probe’s storage the destination when its code is delegated. In this example, the probe’s first three fields occupy slots 0–2 in the caller’s storage. If those slots already hold meaningful caller state, the “observation” itself corrupts it.

Test the semantics, not just the return value

A test that only asserts delegatecall returned true misses the security property. Assert sender, self, value, and storage ownership explicitly. The test must also avoid assuming that a mock proves native-precompile behavior.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "forge-std/Test.sol";

contract DelegateContextTest is Test {
    ContextProbe probe;
    DelegateCaller caller;

    function setUp() public {
        probe = new ContextProbe();
        caller = new DelegateCaller();
    }

    function testDelegatecallUsesCallerContext() public {
        address admin = address(0xA11CE);
        vm.deal(admin, 1 ether);

        vm.prank(admin);
        bool ok = caller.delegateRecord{value: 0.1 ether}(address(probe));

        assertTrue(ok);
        assertEq(probe.observedSender(), address(0));
        assertEq(probe.observedSelf(), address(0));
        assertEq(probe.observedValue(), 0);

        // This probe's writes are in DelegateCaller storage, not probe storage.
        assertEq(
            address(caller),
            address(caller)
        );
    }
}

The last assertion above is intentionally not a storage assertion; Solidity cannot read the mock’s delegated writes through the probe’s autogenerated getters. For a meaningful assertion, add a purpose-built caller with getters over the exact slots or use inline assembly to inspect the caller’s storage. The direct lesson is that a test should inspect the storage owner, not infer it from a successful call.

A practical test fixture can expose those slots:

contract InspectableCaller {
    function run(address target) external payable {
        (bool ok,) = target.delegatecall(
            abi.encodeWithSelector(ContextProbe.record.selector)
        );
        require(ok, "delegate failed");
    }

    function slot(uint256 index) external view returns (bytes32 value) {
        assembly {
            value := sload(index)
        }
    }
}

With this fixture, assert that slots 0–2 on InspectableCaller contain the expected sender, caller address, and value encoding, while the probe’s own storage remains unchanged. This documents the EVM behavior your security policy must account for.

Production implementation: reject unsupported call types

If a stateful precompile is not explicitly designed for delegated execution, the safe policy is to reject DELEGATECALL and CALLCODE at the protocol boundary. The Granite resolution followed this approach for existing stateful precompiles and also fixed libevm to disambiguate EVM-semantic and raw caller contexts.

In Solidity, make the call type explicit in the application-facing contract. Do not use a generic “invoke target” helper that silently chooses delegation:

interface IStatefulPrecompile {
    function update(bytes calldata input) external returns (bytes memory);
}

contract SafePrecompileClient {
    address public immutable precompile;

    error PrecompileCallFailed();

    constructor(address precompile_) {
        require(precompile_ != address(0), "zero precompile");
        precompile = precompile_;
    }

    function update(bytes calldata input) external returns (bytes memory result) {
        (bool ok, bytes memory data) = precompile.call(
            abi.encodeCall(IStatefulPrecompile.update, (input))
        );

        if (!ok) revert PrecompileCallFailed();
        return abi.decode(data, (bytes));
    }
}

This makes an ordinary CALL the only call path in this client. It does not prevent another contract from using DELEGATECALL directly against the precompile. That restriction must be enforced by the precompile implementation or the chain’s transaction/execution rules. Check low-level call handling carefully; this is related to Preventing Unchecked Low-Level Call Failures in Solidity.

Do not attempt to solve the native precompile issue by checking msg.sender in a Solidity wrapper. A wrapper cannot reliably identify the original EOA after arbitrary intermediary calls, and a malicious contract can bypass the wrapper and target the precompile directly. Authorization should be based on a documented, unambiguous caller model enforced where the stateful operation executes.

Quantitative trade-offs

The table separates what a Solidity harness can establish from what requires a node-level test. Gas figures are not universal: they depend on compiler, EVM revision, optimizer, and the particular precompile.

ApproachWhat it verifiesCost / limitationSecurity value
Solidity delegatecall mockInherited sender/value, caller address and storage contextLocal EVM gas; does not execute native precompile codeStrong regression test for EVM-context assumptions
CALL-only client wrapperClient code uses ordinary call pathAdds wrapper execution and ABI handling; cannot stop direct attacker callsReduces accidental delegated invocation
Target-client integration testActual precompile rejects delegated invocationRequires the relevant node build and chain configurationVerifies protocol enforcement end to end
Differential execution across client versionsDetects behavior divergence for identical transaction inputRequires versioned nodes or reproducible client buildsFinds consensus-sensitive semantic mismatches

Do not publish a single gas number as a protocol guarantee. Benchmark the exact deployed client and precompile on the target network; the security property is rejection or correct context interpretation, not a particular gas threshold.

Differential verification and production edge cases

The incident’s history makes version-specific testing essential. The vulnerability was introduced in AvalancheGo v1.13.1; the response included rollback to v1.13.0, a containment rule in AvalancheGo v1.13.4 and subnet-evm v0.7.8, and permanent resolution in Granite with AvalancheGo v1.14.0. The post-mortem reports no exploitation on Mainnet or any public L1. Do not infer that every L1 running a related client has identical activation state or configuration.

Use Foundry for Solidity-level regression tests:

forge test --match-contract DelegateContextTest -vvvv
forge test --fuzz-runs 10000

For a node-level regression, build the exact target client revisions, deploy the same test contract, and submit the same transactions to each node. Compare success/revert status, logs, resulting account storage, and stateful precompile effects. Run at least these cases:

  1. Direct CALL from a contract to the stateful precompile.
  2. DELEGATECALL from a contract to the precompile.
  3. CALLCODE where the target chain still accepts that opcode.
  4. An EOA calling a malicious intermediary that delegates to the precompile.
  5. A non-admin and an admin caller, with and without an intermediary.
  6. Repeated calls and reverted outer frames, to check whether state changes are rolled back consistently.

For a Solidity-only harness, record the exact caller and storage slots before and after each transaction. For client tests, record the client commit/version, chain upgrade rules, precompile address, calldata, and transaction trace. Comparing only receipt status is inadequate: two clients can both return success while writing different state.

Production edge cases include proxy contracts, multicall routers, nested delegation, and precompile upgrades. A proxy may cause the precompile to execute with the proxy’s storage context; a nested call can make “caller” ambiguous unless the implementation defines whether it means immediate EVM caller or authenticated origin. Never use tx.origin to patch this ambiguity: it creates a different authorization hazard and does not repair incorrect precompile context handling.

Also test failed calls. A policy that rejects delegation must leave no partial state changes or emitted success events. If the chain rejects the transaction before execution, verify that behavior at the node boundary; if it reverts during precompile execution, verify rollback and revert propagation. For broader numeric/state assertions in precompiles, differential testing should include edge values and rounding behavior, as in Reproducing Balancer Stable-Pool Rounding Drift with Foundry.

Frequently Asked Questions (FAQ)

Does Solidity DELEGATECALL preserve msg.sender?

Yes. It preserves the caller frame’s msg.sender and msg.value, while executing target code in the calling contract’s address and storage context. This is precisely why a stateful precompile must not conflate inherited identity with the context in which it reads or writes state.

Can Foundry prove AvalancheGo v1.14.0 rejects delegated precompile calls?

No. A Foundry mock tests EVM-level behavior and Solidity code, not the node’s native precompile implementation or upgrade activation. Run an integration test against the relevant AvalancheGo build and network configuration to establish that policy.

What changed between AvalancheGo v1.13.1 and Granite v1.14.0?

The post-mortem attributes the issue to divergent assumptions about stateful-precompile DELEGATECALL semantics after the libevm introduction in v1.13.1. Granite’s permanent resolution makes existing stateful precompiles revert on DELEGATECALL and CALLCODE and patches libevm to distinguish EVM-semantic from raw caller contexts.

Learn more with useful resources