Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

ERC-7746 proposes a standard interface for composable security layers that perform reusable validation at the smart contract level.

This article translates, summarizes, and expands on the following proposal.

More EIP explainers:

Overview

ERC-7746 introduces a security middleware interface called ILayer.

A security layer operates independently of the protected contract's application logic and can perform validation before and after a function executes.

Instead of implementing every security check independently in each application contract, developers can integrate reusable security layers through a common interface.

Motivation

Smart contract security checks are often embedded directly in application logic. This approach can tightly couple access control and other validation rules to the business logic, making maintenance and security updates more difficult.

Implementing similar checks separately across multiple contracts can also introduce inconsistencies.

Modular security layers

ERC-7746 proposes a middleware architecture to make security validation more modular and extensible.

Independent security providers

Specialized providers can implement reusable layers for access control, input validation, or verification of post-execution conditions.

Developers can integrate these layers rather than reimplementing every validation mechanism. They remain responsible for evaluating the layer's trust assumptions and its interaction with the protected contract.

Combining security layers

Multiple layers can be combined to address different requirements.

For example, a contract might integrate an identity-verification policy or an anomaly-detection layer, depending on the application's needs and the information available to its validation logic.

Updating security without replacing application logic

When a protected contract supports authorized changes to its layer configuration, security policies can be updated without replacing its application logic.

This can reduce deployment and maintenance overhead. The ILayer interface alone does not provide a mechanism for changing registered layers; the protected contract must implement that capability separately.

Supporting different types of validation

Security layers can perform more than access control. They can validate input ranges, enforce execution policies, and inspect relevant post-execution state.

This allows an application to enforce both preconditions and postconditions around a function call.

Specification

A contract implementing ILayer exposes two validation functions.

js
// SPDX-License-Identifier: CC0-1.0
pragma solidity 0.8.20;

interface ILayer {
    /// @notice Validates a function call before execution.
    /// @param configuration Layer-specific configuration data.
    /// @param selector The function selector being called.
    /// @param sender The address initiating the call.
    /// @param value The amount of ETH sent with the call (if any).
    /// @param data The calldata for the function call.
    /// @return beforeCallResult Arbitrary data to be passed to `afterCallValidation`.
    /// @dev MUST revert if validation fails.
    function beforeCall(
        bytes memory configuration,
        bytes4 selector,
        address sender,
        uint256 value,
        bytes memory data
    ) external returns (bytes memory);

    /// @notice Validates a function call after execution.
    /// @param configuration Layer-specific configuration data.
    /// @param selector The function selector being called.
    /// @param sender The address initiating the call.
    /// @param value The amount of ETH sent with the call (if any).
    /// @param data The calldata for the function call.
    /// @param beforeCallResult The data returned by `beforeCallValidation`.
    /// @dev MUST revert if validation fails.
    function afterCall(
        bytes memory configuration,
        bytes4 selector,
        address sender,
        uint256 value,
        bytes memory data,
        bytes memory beforeCallResult
    ) external;
}

beforeCall

js
function beforeCall(
    bytes memory configuration,
    bytes4 selector,
    address sender,
    uint256 value,
    bytes memory data
) external returns (bytes memory);

Overview

Performs validation before the protected function executes.

Details

The protected contract invokes this hook before its application logic. If validation fails, the hook must revert. On success, it returns arbitrary bytes that can be supplied to the corresponding afterCall hook.

When multiple layers are configured, their execution order is determined by the integrating contract. A propagated revert from a layer stops the enclosing execution.

Parameters

  • configuration
    • Configuration data specific to the security layer.
  • selector
    • The selector of the protected function.
  • sender
    • The address initiating the protected call.
  • value
    • The ETH value associated with the call, or zero when no ETH is supplied.
  • data
    • The calldata associated with the protected function call.

Return value

  • beforeCallResult
    • Arbitrary data to pass to afterCall, such as information needed to compare pre-execution and post-execution state.

afterCall

js
function afterCall(
    bytes memory configuration,
    bytes4 selector,
    address sender,
    uint256 value,
    bytes memory data,
    bytes memory beforeCallResult
) external;

Overview

Performs validation after the protected function executes.

Details

The hook can check whether execution satisfies an expected condition, using information returned by beforeCall together with the current execution context.

For example, a layer can record an initial balance before execution and inspect the resulting balance afterward.

If validation fails, the hook must revert. When that revert propagates through the enclosing call, the protected operation's state changes are rolled back.

The interface does not directly provide the protected function's return data as a separate parameter. A layer that needs to inspect return values requires an appropriate integration mechanism.

Parameters

  • configuration
    • Configuration data specific to the layer.
  • selector
    • The selector of the executed function.
  • sender
    • The address initiating the protected call.
  • value
    • The ETH value associated with the call.
  • data
    • The original calldata.
  • beforeCallResult
    • The data returned by beforeCall.

Rationale

Flexibility and customization

Layer-specific configuration allows one validation implementation to be reused by multiple protected contracts with different policies.

For example, one contract can configure a rate limit while another can configure which accounts are permitted to perform particular operations, provided the selected layer supports those policies.

The configuration format and authorization rules depend on the layer and its integration.

Stateful validation

The hooks are not restricted to view functions. A security layer can maintain state and use previous activity when validating subsequent calls.

For example, a rate-limit layer can count operations associated with a particular address over a defined period and reject operations exceeding the configured threshold.

Reverting when validation fails

A layer must revert when its validation fails.

Pre-execution validation can reject a prohibited operation before the application logic runs. Post-execution validation can reject an operation that violates an expected invariant after execution.

These checks reduce the risk associated with the conditions they cover, but they do not eliminate the need to secure the application logic itself.

Gas-cost trade-offs

Invoking security layers adds execution overhead, including external-call costs and any storage operations performed by the layers.

The additional cost may be justified when a layer provides useful security guarantees. Lower-cost execution environments, including some layer-2 networks, can make such integrations more economical.

Developers should measure the actual overhead and evaluate the security benefits for their particular deployment.

Reference implementation

The proposal links to reference implementations:

The original article describes a Protected contract that uses a RateLimitLayer to limit the number of protected calls within a block.

RateLimitLayer.sol
// SPDX-License-Identifier: CC0-1.0
pragma solidity =0.8.20;
import "../ILayer.sol";

contract RateLimitLayer is ILayer {
    mapping(address => mapping(bytes4 => uint256)) usage;
    mapping(address => mapping(bytes4 => uint256)) usageUpdatedAtBlock;

    function beforeCallValidation(
        bytes memory,
        bytes4 messageSig,
        address,
        uint256,
        bytes memory
    ) public returns (bytes memory) {
        if (usageUpdatedAtBlock[msg.sender][messageSig] != block.number) {
            usage[msg.sender][messageSig] = 0;
            usageUpdatedAtBlock[msg.sender][messageSig] = block.number;
        } else {
            usage[msg.sender][messageSig] += 1;
        }
        return "";
    }

    function afterCallValidation(
        bytes memory layerConfig,
        bytes4 messageSig,
        address,
        uint256,
        bytes memory,
        bytes memory
    ) public view {
        uint256 blockQuota = uint256(bytes32(layerConfig));
        require(usage[msg.sender][messageSig] < blockQuota, "Rate limited");
    }
}

The example tracks usage and the block number for each calling contract and function selector. The quota is obtained from the supplied configuration.

The original code is retained unchanged. Several implementation details require attention:

  • The example uses beforeCallValidation and afterCallValidation, whereas the interface shown above declares beforeCall and afterCall. These names must be reconciled with the interface used by the implementation.
  • The counters are keyed by msg.sender, which normally identifies the protected contract calling the layer, not the original user. The example does not use the separate sender argument. It therefore does not independently enforce a per-user quota.
  • The quota is configurable rather than hard-coded to ten calls.
  • The first call in a new block initializes the counter to zero. Boundary behavior should be verified with tests for the intended quota.

The examples have not been independently compiled or audited as part of this translation.

Security

A security layer becomes part of the protected contract's security and availability assumptions.

A malicious or compromised layer can weaken validation, reject legitimate calls, or perform unexpected external interactions. Integrators should evaluate the implementation, its administrators, upgrade permissions, and dependencies.

Centralized security providers may be able to change policies or selectively permit operations. Open-source code, independent audits, and transparent governance can improve the ability to assess those risks, although they do not guarantee security.

Protected contracts must also consider reentrancy, authorization of configuration changes, bypass paths, and gas-related denial of service. Every protected execution path must invoke the appropriate hooks and propagate validation failures for the intended safeguards to be effective.

Citation

Tim Pechersky (@peersky), "ERC-7746: Composable Security Middleware Hooks [DRAFT]," Ethereum Improvement Proposals, no. 7746, July 2024. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-7746.

Conclusion

ERC-7746 proposes composable middleware hooks for validating smart contract operations before and after execution.

The architecture enables reusable security checks and configurable validation policies while leaving their integration, governance, and trust model to the implementing application.

Questions are welcome via Twitter @cardene777.

Other publications:

https://chaldene.net/