{"eip":7746,"title":"Composable Security Middleware Hooks","description":"An interface for composable, runtime security checks in smart contracts.","authors":["Tim Pechersky (@peersky)"],"status":"Last Call","type":"Standards Track","category":"ERC","created":"2024-07-17","discussionsTo":"https://ethereum-magicians.org/t/erc-7746-composable-security-middleware-hooks/19471","repo":"ERCs","label":"ERC-7746","officialUrl":"https://eips.ethereum.org/EIPS/eip-7746","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-7746.md","url":"https://eips.huatuo.xyz/eip-7746/","tldr":{"en":"Defines ILayer, a middleware interface whose beforeCall/afterCall hooks let separate, upgradable security contracts validate calls to a protected contract and revert them if checks fail.","ja":"ミドルウェア用インターフェース ILayer を定義する。beforeCall / afterCall フックにより、独立していてアップグレード可能なセキュリティコントラクトが、保護対象のコントラクトへの呼び出しを検証し、チェックに失敗すればリバートさせられる。","ko":"미들웨어 인터페이스 ILayer를 정의한다. beforeCall/afterCall 훅으로 별도의 업그레이드 가능한 보안 컨트랙트가 보호 대상 컨트랙트에 대한 호출을 검증하고, 검사에 실패하면 리버트시킬 수 있다.","zh":"定义 ILayer 中间件接口，其 beforeCall/afterCall 钩子让独立、可升级的安全合约能够校验对受保护合约的调用，并在检查失败时使其回滚。"},"tags":["security","middleware","hooks","solidity","modular"],"explainers":{"en":{"lang":"en","tldr":"Defines ILayer, a middleware interface whose beforeCall/afterCall hooks let separate, upgradable security contracts validate calls to a protected contract and revert them if checks fail.","tags":["security","middleware","hooks","solidity","modular"],"related":[165,7579,6900],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-7746/","markdown":"## What problem does it solve?\n\nSecurity checks in smart contracts are usually baked into each contract: access control, rate limits, input checks and invariants all live in the same code as the business logic. That makes them hard to reuse, hard to upgrade without redeploying, and hard for specialised security providers to offer as a service.\n\nERC-7746 borrows the **middleware** pattern from web servers. A protected contract hands each incoming call to one or more external **layers** before and after running its own logic. Any layer can veto the call by reverting.\n\n## How it works\n\nA layer implements two functions:\n\n- `beforeCall(configuration, selector, sender, value, data)` runs before the protected function. It returns arbitrary bytes that are passed on to the after-hook, and must revert if validation fails.\n- `afterCall(configuration, selector, sender, value, data, beforeCallResult)` runs after the protected function and can check the outcome, again reverting on failure.\n\n`configuration` is layer-specific data, so one deployed layer can serve many contracts with different settings. Layers are called with normal (non-static) calls, so they can keep state, for example counting calls per block for rate limiting.\n\nA protected contract may register several layers and run them in a defined order. If any layer reverts, the whole call must revert. The reference implementation shows a rate-limiting layer that stops a simulated drainer contract from emptying a buggy protected contract.\n\n## Sample code\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface ILayer {\n    function beforeCall(\n        bytes memory configuration,\n        bytes4 selector,\n        address sender,\n        uint256 value,\n        bytes memory data\n    ) external returns (bytes memory);\n\n    function afterCall(\n        bytes memory configuration,\n        bytes4 selector,\n        address sender,\n        uint256 value,\n        bytes memory data,\n        bytes memory beforeCallResult\n    ) external;\n}\n\nabstract contract LayerProtected {\n    ILayer public immutable layer;\n    bytes internal layerConfig;\n\n    constructor(ILayer _layer, bytes memory _config) {\n        layer = _layer;\n        layerConfig = _config;\n    }\n\n    modifier layered() {\n        bytes memory ctx = layer.beforeCall(layerConfig, msg.sig, msg.sender, msg.value, msg.data);\n        _;\n        layer.afterCall(layerConfig, msg.sig, msg.sender, msg.value, msg.data, ctx);\n    }\n}\n\ncontract Vault is LayerProtected {\n    constructor(ILayer l, bytes memory cfg) LayerProtected(l, cfg) {}\n\n    function withdraw(uint256 amount) external layered {\n        // business logic; reverts if the layer rejects the call\n    }\n}\n```\n\n## Things to know\n\n- **Status: Last Call.** It has not reached Final.\n- The spec's prose sometimes calls the hooks `beforeCallValidation` / `afterCallValidation` and the config `layerConfig`, while the interface uses `beforeCall` / `afterCall` and `configuration`. Follow the interface.\n- A layer is fully trusted: a malicious or buggy layer can block every call or leak information. Audit layers like any other dependency, and decide who can change which layer is used.\n- Every layer adds gas and external calls on each protected function, and a stateful layer can itself be a reentrancy or denial-of-service vector.\n- Similar hook ideas appear in modular smart-account standards such as [ERC-7579](/eip-7579/) and [ERC-6900](/eip-6900/), which target accounts rather than arbitrary contracts.\n"},"ja":{"lang":"ja","tldr":"ミドルウェア用インターフェース ILayer を定義する。beforeCall / afterCall フックにより、独立していてアップグレード可能なセキュリティコントラクトが、保護対象のコントラクトへの呼び出しを検証し、チェックに失敗すればリバートさせられる。","tags":["security","middleware","hooks","solidity","modular"],"related":[165,7579,6900],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-7746/","markdown":"## 何を解決するのか\n\nスマートコントラクトのセキュリティチェックは、通常は各コントラクトに組み込まれています。アクセス制御、レート制限、入力チェック、不変条件が、ビジネスロジックと同じコードの中にあります。そのため再利用しにくく、再デプロイなしでのアップグレードも難しく、専門のセキュリティ事業者がサービスとして提供するのも困難です。\n\nERC-7746 は、Web サーバーの**ミドルウェア**パターンを借用します。保護されたコントラクトは、自身のロジックを実行する前後に、受け取った各呼び出しを 1 つ以上の外部の**レイヤー**に渡します。どのレイヤーも、リバートすることでその呼び出しを拒否できます。\n\n## 仕組み\n\nレイヤーは 2 つの関数を実装します。\n\n- `beforeCall(configuration, selector, sender, value, data)` は、保護された関数の前に実行されます。任意の bytes を返し、それが after フックに渡されます。検証に失敗した場合はリバートしなければなりません。\n- `afterCall(configuration, selector, sender, value, data, beforeCallResult)` は、保護された関数の後に実行され、結果を確認できます。こちらも失敗時にはリバートします。\n\n`configuration` はレイヤー固有のデータで、デプロイ済みの 1 つのレイヤーが、異なる設定で多数のコントラクトに対応できます。レイヤーは通常の（非 static の）呼び出しで呼ばれるため、状態を保持できます。たとえば、レート制限のためにブロックごとの呼び出し回数を数えることができます。\n\n保護されたコントラクトは複数のレイヤーを登録し、定められた順序で実行できます。いずれかのレイヤーがリバートすれば、呼び出し全体がリバートしなければなりません。リファレンス実装には、バグのある保護対象コントラクトを空にしようとする、模擬ドレイナーコントラクトを止めるレート制限レイヤーが示されています。\n\n## サンプルコード\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface ILayer {\n    function beforeCall(\n        bytes memory configuration,\n        bytes4 selector,\n        address sender,\n        uint256 value,\n        bytes memory data\n    ) external returns (bytes memory);\n\n    function afterCall(\n        bytes memory configuration,\n        bytes4 selector,\n        address sender,\n        uint256 value,\n        bytes memory data,\n        bytes memory beforeCallResult\n    ) external;\n}\n\nabstract contract LayerProtected {\n    ILayer public immutable layer;\n    bytes internal layerConfig;\n\n    constructor(ILayer _layer, bytes memory _config) {\n        layer = _layer;\n        layerConfig = _config;\n    }\n\n    modifier layered() {\n        bytes memory ctx = layer.beforeCall(layerConfig, msg.sig, msg.sender, msg.value, msg.data);\n        _;\n        layer.afterCall(layerConfig, msg.sig, msg.sender, msg.value, msg.data, ctx);\n    }\n}\n\ncontract Vault is LayerProtected {\n    constructor(ILayer l, bytes memory cfg) LayerProtected(l, cfg) {}\n\n    function withdraw(uint256 amount) external layered {\n        // business logic; reverts if the layer rejects the call\n    }\n}\n```\n\n## 知っておくべきこと\n\n- **ステータス: Last Call。** Final には到達していません。\n- 仕様の本文では、フックを `beforeCallValidation` / `afterCallValidation`、設定を `layerConfig` と呼んでいる箇所がありますが、インターフェースでは `beforeCall` / `afterCall` と `configuration` を使っています。インターフェースに従ってください。\n- レイヤーは完全に信頼されます。悪意のある、またはバグのあるレイヤーは、すべての呼び出しをブロックしたり、情報を漏らしたりする可能性があります。レイヤーは他の依存関係と同様に監査し、どのレイヤーを使うかを誰が変更できるかを決めてください。\n- レイヤーを追加するたびに、保護された関数の呼び出しごとにガスと外部呼び出しが増えます。また、状態を持つレイヤーは、それ自体がリエントランシーやサービス拒否（DoS）の経路になり得ます。\n- 同様のフックの考え方は、[ERC-7579](/eip-7579/) や [ERC-6900](/eip-6900/) のようなモジュラー型スマートアカウントの標準にも見られますが、それらは任意のコントラクトではなくアカウントを対象としています。\n"},"ko":{"lang":"ko","tldr":"미들웨어 인터페이스 ILayer를 정의한다. beforeCall/afterCall 훅으로 별도의 업그레이드 가능한 보안 컨트랙트가 보호 대상 컨트랙트에 대한 호출을 검증하고, 검사에 실패하면 리버트시킬 수 있다.","tags":["security","middleware","hooks","solidity","modular"],"related":[165,7579,6900],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-7746/","markdown":"## 어떤 문제를 해결하나요?\n\n스마트 컨트랙트의 보안 검사는 보통 각 컨트랙트 안에 박혀 있습니다. 접근 제어, 속도 제한, 입력 검사, 불변식이 비즈니스 로직과 같은 코드 안에 있습니다. 그래서 재사용하기 어렵고, 재배포 없이 업그레이드하기 어렵고, 전문 보안 업체가 서비스로 제공하기도 어렵습니다.\n\nERC-7746은 웹 서버의 **미들웨어** 패턴을 빌려 옵니다. 보호되는 컨트랙트는 자신의 로직을 실행하기 전과 후에 들어오는 각 호출을 하나 이상의 외부 **레이어**에 넘깁니다. 어떤 레이어든 리버트로 호출을 거부할 수 있습니다.\n\n## 어떻게 동작하나요?\n\n레이어는 두 함수를 구현합니다.\n\n- `beforeCall(configuration, selector, sender, value, data)`는 보호되는 함수 전에 실행됩니다. 임의의 bytes를 반환하며 이는 after 훅으로 전달되고, 검증에 실패하면 반드시 리버트해야 합니다.\n- `afterCall(configuration, selector, sender, value, data, beforeCallResult)`는 보호되는 함수 뒤에 실행되며 결과를 확인할 수 있고, 마찬가지로 실패하면 리버트합니다.\n\n`configuration`은 레이어별 데이터이므로, 배포된 레이어 하나가 서로 다른 설정으로 여러 컨트랙트를 담당할 수 있습니다. 레이어는 일반(non-static) 호출로 호출되므로 상태를 유지할 수 있습니다. 예를 들어 속도 제한을 위해 블록당 호출 횟수를 셀 수 있습니다.\n\n보호되는 컨트랙트는 여러 레이어를 등록해 정해진 순서로 실행할 수 있습니다. 어느 레이어든 리버트하면 호출 전체가 리버트해야 합니다. 레퍼런스 구현에는 버그가 있는 보호 대상 컨트랙트를 비우려는 모의 탈취 컨트랙트를 막아 내는 속도 제한 레이어가 나와 있습니다.\n\n## 샘플 코드\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface ILayer {\n    function beforeCall(\n        bytes memory configuration,\n        bytes4 selector,\n        address sender,\n        uint256 value,\n        bytes memory data\n    ) external returns (bytes memory);\n\n    function afterCall(\n        bytes memory configuration,\n        bytes4 selector,\n        address sender,\n        uint256 value,\n        bytes memory data,\n        bytes memory beforeCallResult\n    ) external;\n}\n\nabstract contract LayerProtected {\n    ILayer public immutable layer;\n    bytes internal layerConfig;\n\n    constructor(ILayer _layer, bytes memory _config) {\n        layer = _layer;\n        layerConfig = _config;\n    }\n\n    modifier layered() {\n        bytes memory ctx = layer.beforeCall(layerConfig, msg.sig, msg.sender, msg.value, msg.data);\n        _;\n        layer.afterCall(layerConfig, msg.sig, msg.sender, msg.value, msg.data, ctx);\n    }\n}\n\ncontract Vault is LayerProtected {\n    constructor(ILayer l, bytes memory cfg) LayerProtected(l, cfg) {}\n\n    function withdraw(uint256 amount) external layered {\n        // business logic; reverts if the layer rejects the call\n    }\n}\n```\n\n## 알아둘 점\n\n- **상태: Last Call.** 아직 Final에 도달하지 않았습니다.\n- 명세 본문은 때때로 훅을 `beforeCallValidation` / `afterCallValidation`, 설정을 `layerConfig`라고 부르지만, 인터페이스는 `beforeCall` / `afterCall`과 `configuration`을 사용합니다. 인터페이스를 따르세요.\n- 레이어는 완전히 신뢰됩니다. 악의적이거나 버그가 있는 레이어는 모든 호출을 막거나 정보를 유출할 수 있습니다. 레이어도 다른 의존성처럼 감사하고, 어떤 레이어를 쓸지 누가 바꿀 수 있는지 정하세요.\n- 레이어를 하나 추가할 때마다 보호되는 함수를 호출할 때마다 가스와 외부 호출이 늘어나며, 상태를 가진 레이어는 그 자체로 재진입이나 서비스 거부 공격의 경로가 될 수 있습니다.\n- 비슷한 훅 아이디어는 [ERC-7579](/eip-7579/), [ERC-6900](/eip-6900/) 같은 모듈형 스마트 계정 표준에서도 나타나는데, 이들은 임의의 컨트랙트가 아니라 계정을 대상으로 합니다.\n"},"zh":{"lang":"zh","tldr":"定义 ILayer 中间件接口，其 beforeCall/afterCall 钩子让独立、可升级的安全合约能够校验对受保护合约的调用，并在检查失败时使其回滚。","tags":["security","middleware","hooks","solidity","modular"],"related":[165,7579,6900],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-7746/","markdown":"## 它解决什么问题？\n\n智能合约中的安全检查通常被写死在每个合约里：访问控制、速率限制、输入检查和不变量都与业务逻辑放在同一份代码中。这使得它们难以复用，不重新部署就难以升级，也不便于专业的安全服务商以服务形式提供。\n\nERC-7746 借用了 Web 服务器中的**中间件（middleware）**模式。受保护的合约在运行自己的逻辑之前和之后，把每个传入的调用交给一个或多个外部**层（layer）**。任何一层都可以通过回滚来否决该调用。\n\n## 它如何运作\n\n一个层实现两个函数：\n\n- `beforeCall(configuration, selector, sender, value, data)` 在受保护函数之前运行。它返回任意字节，并传给 after 钩子；如果校验失败，必须回滚。\n- `afterCall(configuration, selector, sender, value, data, beforeCallResult)` 在受保护函数之后运行，可以检查执行结果，失败时同样回滚。\n\n`configuration` 是该层专属的数据，因此同一个已部署的层可以用不同的设置服务许多合约。层通过普通（非 static）调用来调用，所以可以保存状态，例如为速率限制统计每个区块的调用次数。\n\n受保护的合约可以注册多个层，并按既定顺序运行。只要有任何一层回滚，整个调用就必须回滚。参考实现展示了一个速率限制层，它阻止了一个模拟的掏空者合约把有漏洞的受保护合约掏空。\n\n## 示例代码\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface ILayer {\n    function beforeCall(\n        bytes memory configuration,\n        bytes4 selector,\n        address sender,\n        uint256 value,\n        bytes memory data\n    ) external returns (bytes memory);\n\n    function afterCall(\n        bytes memory configuration,\n        bytes4 selector,\n        address sender,\n        uint256 value,\n        bytes memory data,\n        bytes memory beforeCallResult\n    ) external;\n}\n\nabstract contract LayerProtected {\n    ILayer public immutable layer;\n    bytes internal layerConfig;\n\n    constructor(ILayer _layer, bytes memory _config) {\n        layer = _layer;\n        layerConfig = _config;\n    }\n\n    modifier layered() {\n        bytes memory ctx = layer.beforeCall(layerConfig, msg.sig, msg.sender, msg.value, msg.data);\n        _;\n        layer.afterCall(layerConfig, msg.sig, msg.sender, msg.value, msg.data, ctx);\n    }\n}\n\ncontract Vault is LayerProtected {\n    constructor(ILayer l, bytes memory cfg) LayerProtected(l, cfg) {}\n\n    function withdraw(uint256 amount) external layered {\n        // business logic; reverts if the layer rejects the call\n    }\n}\n```\n\n## 需要注意\n\n- **状态：Last Call。**尚未达到 Final。\n- 规范正文有时把钩子称为 `beforeCallValidation` / `afterCallValidation`，把配置称为 `layerConfig`，而接口中使用的是 `beforeCall` / `afterCall` 和 `configuration`。请以接口为准。\n- 层是被完全信任的：恶意或有缺陷的层可能阻断每一次调用或泄露信息。请像审计其他依赖一样审计各个层，并决定谁可以更改所使用的层。\n- 每增加一层，每次调用受保护函数都会增加 gas 和外部调用；有状态的层本身也可能成为重入或拒绝服务的攻击面。\n- 类似的钩子思路也出现在 [ERC-7579](/eip-7579/) 和 [ERC-6900](/eip-6900/) 等模块化智能账户标准中，不过它们针对的是账户，而不是任意合约。\n"}}}
