{"eip":7509,"title":"Entity Component System","description":"Represent entities comprising components of data, with systems which operate on entities' components.","authors":["Rickey (@HelloRickey)"],"status":"Draft","type":"Standards Track","category":"ERC","created":"2023-09-05","discussionsTo":"https://ethereum-magicians.org/t/a-new-proposal-of-entity-component-system/15665","repo":"ERCs","label":"ERC-7509","officialUrl":"https://eips.ethereum.org/EIPS/eip-7509","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-7509.md","url":"https://eips.huatuo.xyz/eip-7509/","tldr":{"en":"Standard interfaces for building on-chain apps and games with the Entity Component System pattern: a World registry, data-holding Component contracts, and free-form System contracts that operate on them.","ja":"Entity Component System パターンでオンチェーンのアプリやゲームを構築するための標準インターフェース。World レジストリ、データを保持する Component コントラクト、それらを操作する自由形式の System コントラクトで構成される。","ko":"Entity Component System 패턴으로 온체인 앱과 게임을 만들기 위한 표준 인터페이스. World 레지스트리, 데이터를 담는 Component 컨트랙트, 그리고 이를 다루는 자유 형식의 System 컨트랙트로 구성된다.","zh":"用实体组件系统（Entity Component System）模式构建链上应用和游戏的标准接口：World 注册表、保存数据的 Component 合约，以及对其进行操作的自由形式 System 合约。"},"tags":["gaming","architecture","ecs","composability"],"explainers":{"en":{"lang":"en","tldr":"Standard interfaces for building on-chain apps and games with the Entity Component System pattern: a World registry, data-holding Component contracts, and free-form System contracts that operate on them.","tags":["gaming","architecture","ecs","composability"],"related":[2535,1155],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-7509/","markdown":"## What problem does it solve?\n\nEntity Component System (ECS) is a common architecture in game engines. Instead of deep class hierarchies, it splits a program into three things:\n\n- **Entities**: plain IDs (\"player #42\", \"sword #7\").\n- **Components**: reusable data attached to entities (position, HP, inventory).\n- **Systems**: logic that reads and writes component data (movement, combat).\n\nFully on-chain games and multi-contract apps face the same problems ECS solves: data and logic tangled together, painful upgrades, and little reuse between projects. ERC-7509 defines a minimal set of contract interfaces so that ECS-style apps share one vocabulary, and so that components written by one team can be plugged into another's world.\n\n## How it works\n\nA **World** contract (`IWorld`) is the container and registry:\n\n- `createEntity()` returns a new unique `uint256` ID; `setEntityState` toggles it available/unavailable.\n- `registerComponent(addr)` / `registerSystem(addr)` add contracts to the world, each with its own on/off state.\n- `addComponent(entityId, componentAddr)` / `removeComponent` / `hasComponent` / `getEntityComponents` manage which components an entity carries.\n\nA **Component** contract (`IComponent`) stores data per entity:\n\n- `world()` returns the world it belongs to.\n- `types()` returns type descriptors (from a shared `Types` library) for how its `bytes` data is encoded, so outside callers know how to decode it.\n- `set(entityId, data)` and `get(entityId)` read and write the encoded data. A second `get(entityId, params)` allows parameterised lookups, such as \"HP for this entity at level N\".\n\nA **System** is any contract with no required interface. Once registered and enabled, it can call component `set` functions to change state.\n\nTypical flow: deploy World → create entities → deploy and register components → attach components to entities → deploy and register systems → call systems.\n\n## Sample code\n\nA simple position component and a movement system:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IWorld {\n    function entityExists(uint256) external view returns (bool);\n    function getEntityState(uint256) external view returns (bool);\n    function hasComponent(uint256, address) external view returns (bool);\n    function getSystemState(address) external view returns (bool);\n}\n\ncontract PositionComponent {\n    address public immutable world;\n    mapping(uint256 =\u003e bytes) private data;\n\n    constructor(address _world) { world = _world; }\n\n    function set(uint256 id, bytes memory d) external {\n        IWorld w = IWorld(world);\n        require(w.getSystemState(msg.sender), \"system not enabled\");\n        require(w.getEntityState(id) \u0026\u0026 w.hasComponent(id, address(this)), \"entity\");\n        data[id] = d;\n    }\n\n    function get(uint256 id) external view returns (bytes memory) { return data[id]; }\n    // types() and get(id, params) omitted for brevity\n}\n\ncontract MoveSystem {\n    PositionComponent public immutable pos;\n    constructor(PositionComponent p) { pos = p; }\n\n    function move(uint256 id, int32 dx, int32 dy) external {\n        (int32 x, int32 y) = abi.decode(pos.get(id), (int32, int32));\n        pos.set(id, abi.encode(x + dx, y + dy));\n    }\n}\n```\n\n## Things to know\n\n- Status is **Draft**.\n- Administrative functions (`createEntity`, `addComponent`, `registerSystem`, the `set...State` toggles, etc.) should normally be owner-only. Exposing them to ordinary users is a security risk.\n- Any registered, enabled system can modify component data for every entity in the world, so audit systems before registering them. The spec suggests registering third-party contributions in a disabled state until reviewed.\n- Components should check entity and system availability inside `set()` and expose no other write path.\n- The ECS split overlaps in spirit with modular upgrade patterns like the [ERC-2535](/eip-2535/) Diamond, but targets data modelling rather than function routing.\n"},"ja":{"lang":"ja","tldr":"Entity Component System パターンでオンチェーンのアプリやゲームを構築するための標準インターフェース。World レジストリ、データを保持する Component コントラクト、それらを操作する自由形式の System コントラクトで構成される。","tags":["gaming","architecture","ecs","composability"],"related":[2535,1155],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-7509/","markdown":"## 何を解決するのか\n\nEntity Component System（ECS）は、ゲームエンジンでよく使われるアーキテクチャです。深いクラス階層の代わりに、プログラムを 3 つに分けます。\n\n- **Entity**: 単なる ID（「プレイヤー #42」「剣 #7」）。\n- **Component**: Entity に付与される再利用可能なデータ（位置、HP、インベントリ）。\n- **System**: Component のデータを読み書きするロジック（移動、戦闘）。\n\n完全オンチェーンのゲームや複数コントラクトのアプリは、ECS が解決するのと同じ問題に直面します。データとロジックの絡み合い、面倒なアップグレード、プロジェクト間でほとんど再利用できないことです。ERC-7509 は、ECS スタイルのアプリが共通の語彙を持ち、あるチームが書いた Component を別のチームの World に差し込めるように、最小限のコントラクトインターフェースの集合を定義します。\n\n## 仕組み\n\n**World** コントラクト（`IWorld`）はコンテナ兼レジストリです。\n\n- `createEntity()` は新しい一意の `uint256` ID を返します。`setEntityState` は、それを利用可能・利用不可に切り替えます。\n- `registerComponent(addr)` / `registerSystem(addr)` は World にコントラクトを追加し、それぞれ独自のオン・オフ状態を持ちます。\n- `addComponent(entityId, componentAddr)` / `removeComponent` / `hasComponent` / `getEntityComponents` は、Entity がどの Component を持つかを管理します。\n\n**Component** コントラクト（`IComponent`）は Entity ごとにデータを保存します。\n\n- `world()` は、それが属する World を返します。\n- `types()` は、`bytes` データがどうエンコードされているかを示す型記述子（共有の `Types` ライブラリのもの）を返し、外部の呼び出し側がデコード方法を分かるようにします。\n- `set(entityId, data)` と `get(entityId)` は、エンコードされたデータを読み書きします。2 つ目の `get(entityId, params)` は、「この Entity のレベル N での HP」のようなパラメータ付きの取得を可能にします。\n\n**System** は、必須のインターフェースを持たない任意のコントラクトです。登録されて有効になれば、Component の `set` 関数を呼んで状態を変更できます。\n\n典型的な流れ: World をデプロイ → Entity を作成 → Component をデプロイして登録 → Component を Entity に付与 → System をデプロイして登録 → System を呼び出す。\n\n## サンプルコード\n\n単純な位置 Component と移動 System:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IWorld {\n    function entityExists(uint256) external view returns (bool);\n    function getEntityState(uint256) external view returns (bool);\n    function hasComponent(uint256, address) external view returns (bool);\n    function getSystemState(address) external view returns (bool);\n}\n\ncontract PositionComponent {\n    address public immutable world;\n    mapping(uint256 =\u003e bytes) private data;\n\n    constructor(address _world) { world = _world; }\n\n    function set(uint256 id, bytes memory d) external {\n        IWorld w = IWorld(world);\n        require(w.getSystemState(msg.sender), \"system not enabled\");\n        require(w.getEntityState(id) \u0026\u0026 w.hasComponent(id, address(this)), \"entity\");\n        data[id] = d;\n    }\n\n    function get(uint256 id) external view returns (bytes memory) { return data[id]; }\n    // types() and get(id, params) omitted for brevity\n}\n\ncontract MoveSystem {\n    PositionComponent public immutable pos;\n    constructor(PositionComponent p) { pos = p; }\n\n    function move(uint256 id, int32 dx, int32 dy) external {\n        (int32 x, int32 y) = abi.decode(pos.get(id), (int32, int32));\n        pos.set(id, abi.encode(x + dx, y + dy));\n    }\n}\n```\n\n## 知っておくべきこと\n\n- ステータスは **Draft** です。\n- 管理用の関数（`createEntity`、`addComponent`、`registerSystem`、`set...State` の切り替えなど）は、通常は所有者専用にすべきです。一般ユーザーに公開するとセキュリティリスクになります。\n- 登録され有効になった System は、その World 内のすべての Entity の Component データを変更できるため、登録前に System を監査してください。仕様は、第三者の貢献はレビューされるまで無効状態で登録することを提案しています。\n- Component は `set()` の内部で Entity と System の利用可否を確認し、それ以外の書き込み経路を公開してはいけません。\n- ECS の分割は、[ERC-2535](/eip-2535/) Diamond のようなモジュール式アップグレードパターンと趣旨が重なりますが、対象は関数のルーティングではなくデータモデリングです。\n"},"ko":{"lang":"ko","tldr":"Entity Component System 패턴으로 온체인 앱과 게임을 만들기 위한 표준 인터페이스. World 레지스트리, 데이터를 담는 Component 컨트랙트, 그리고 이를 다루는 자유 형식의 System 컨트랙트로 구성된다.","tags":["gaming","architecture","ecs","composability"],"related":[2535,1155],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-7509/","markdown":"## 어떤 문제를 해결하나요?\n\nEntity Component System(ECS)은 게임 엔진에서 흔히 쓰는 아키텍처입니다. 깊은 클래스 계층 대신 프로그램을 세 가지로 나눕니다.\n\n- **Entity**: 단순한 ID(\"플레이어 #42\", \"검 #7\").\n- **Component**: Entity에 붙는 재사용 가능한 데이터(위치, HP, 인벤토리).\n- **System**: Component 데이터를 읽고 쓰는 로직(이동, 전투).\n\n완전 온체인 게임이나 멀티 컨트랙트 앱도 ECS가 해결하는 것과 같은 문제를 겪습니다. 데이터와 로직이 얽혀 있고, 업그레이드가 고통스럽고, 프로젝트 간 재사용이 거의 없다는 점입니다. ERC-7509는 ECS 스타일 앱이 하나의 공통 어휘를 공유하고, 한 팀이 작성한 Component를 다른 팀의 World에 꽂아 쓸 수 있도록 최소한의 컨트랙트 인터페이스 집합을 정의합니다.\n\n## 어떻게 동작하나요?\n\n**World** 컨트랙트(`IWorld`)는 컨테이너이자 레지스트리입니다.\n\n- `createEntity()`는 새로운 고유 `uint256` ID를 반환하고, `setEntityState`는 이를 사용 가능/불가로 전환합니다.\n- `registerComponent(addr)` / `registerSystem(addr)`는 World에 컨트랙트를 추가하며, 각각 자체 켜짐/꺼짐 상태를 가집니다.\n- `addComponent(entityId, componentAddr)` / `removeComponent` / `hasComponent` / `getEntityComponents`는 Entity가 어떤 Component를 가졌는지 관리합니다.\n\n**Component** 컨트랙트(`IComponent`)는 Entity별로 데이터를 저장합니다.\n\n- `world()`는 자신이 속한 World를 반환합니다.\n- `types()`는 `bytes` 데이터가 어떻게 인코딩되어 있는지 알려 주는 타입 기술자(공유 `Types` 라이브러리의 것)를 반환하여 외부 호출자가 디코딩 방법을 알 수 있게 합니다.\n- `set(entityId, data)`와 `get(entityId)`는 인코딩된 데이터를 읽고 씁니다. 두 번째 `get(entityId, params)`는 \"이 Entity의 레벨 N에서의 HP\"처럼 매개변수가 있는 조회를 가능하게 합니다.\n\n**System**은 필수 인터페이스가 없는 임의의 컨트랙트입니다. 등록되고 활성화되면 Component의 `set` 함수를 호출해 상태를 바꿀 수 있습니다.\n\n일반적인 흐름: World 배포 → Entity 생성 → Component 배포 및 등록 → Component를 Entity에 연결 → System 배포 및 등록 → System 호출.\n\n## 샘플 코드\n\n간단한 위치 Component와 이동 System:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IWorld {\n    function entityExists(uint256) external view returns (bool);\n    function getEntityState(uint256) external view returns (bool);\n    function hasComponent(uint256, address) external view returns (bool);\n    function getSystemState(address) external view returns (bool);\n}\n\ncontract PositionComponent {\n    address public immutable world;\n    mapping(uint256 =\u003e bytes) private data;\n\n    constructor(address _world) { world = _world; }\n\n    function set(uint256 id, bytes memory d) external {\n        IWorld w = IWorld(world);\n        require(w.getSystemState(msg.sender), \"system not enabled\");\n        require(w.getEntityState(id) \u0026\u0026 w.hasComponent(id, address(this)), \"entity\");\n        data[id] = d;\n    }\n\n    function get(uint256 id) external view returns (bytes memory) { return data[id]; }\n    // types() and get(id, params) omitted for brevity\n}\n\ncontract MoveSystem {\n    PositionComponent public immutable pos;\n    constructor(PositionComponent p) { pos = p; }\n\n    function move(uint256 id, int32 dx, int32 dy) external {\n        (int32 x, int32 y) = abi.decode(pos.get(id), (int32, int32));\n        pos.set(id, abi.encode(x + dx, y + dy));\n    }\n}\n```\n\n## 알아둘 점\n\n- 상태는 **Draft**입니다.\n- 관리용 함수(`createEntity`, `addComponent`, `registerSystem`, `set...State` 전환 등)는 보통 소유자 전용이어야 합니다. 일반 사용자에게 노출하면 보안 위험이 됩니다.\n- 등록되고 활성화된 System은 World의 모든 Entity에 대한 Component 데이터를 수정할 수 있으므로 등록 전에 System을 감사하세요. 명세는 제3자의 기여는 검토될 때까지 비활성 상태로 등록하라고 제안합니다.\n- Component는 `set()` 안에서 Entity와 System의 사용 가능 여부를 확인해야 하며 다른 쓰기 경로를 노출해서는 안 됩니다.\n- ECS의 분리는 [ERC-2535](/eip-2535/) Diamond 같은 모듈식 업그레이드 패턴과 취지가 겹치지만, 함수 라우팅이 아니라 데이터 모델링을 겨냥합니다.\n"},"zh":{"lang":"zh","tldr":"用实体组件系统（Entity Component System）模式构建链上应用和游戏的标准接口：World 注册表、保存数据的 Component 合约，以及对其进行操作的自由形式 System 合约。","tags":["gaming","architecture","ecs","composability"],"related":[2535,1155],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-7509/","markdown":"## 它解决什么问题？\n\n实体组件系统（ECS）是游戏引擎中常见的架构。它不使用很深的类继承层次，而是把程序拆分为三部分：\n\n- **Entity（实体）**：纯粹的 ID（\"玩家 #42\"、\"剑 #7\"）。\n- **Component（组件）**：附加在实体上的可复用数据（位置、HP、背包）。\n- **System（系统）**：读写组件数据的逻辑（移动、战斗）。\n\n完全链上的游戏和多合约应用面临 ECS 所要解决的同样问题：数据和逻辑纠缠在一起、升级痛苦、项目之间很少复用。ERC-7509 定义了一组最小的合约接口，使 ECS 风格的应用共享同一套词汇，也使一个团队编写的组件可以接入另一个团队的 world。\n\n## 它如何运作\n\n**World** 合约（`IWorld`）是容器和注册表：\n\n- `createEntity()` 返回一个新的唯一 `uint256` ID；`setEntityState` 将其切换为可用或不可用。\n- `registerComponent(addr)` / `registerSystem(addr)` 向 world 添加合约，每个合约有各自的开关状态。\n- `addComponent(entityId, componentAddr)` / `removeComponent` / `hasComponent` / `getEntityComponents` 管理实体携带哪些组件。\n\n**Component** 合约（`IComponent`）按实体存储数据：\n\n- `world()` 返回它所属的 world。\n- `types()` 返回类型描述符（来自共享的 `Types` 库），说明其 `bytes` 数据的编码方式，让外部调用者知道如何解码。\n- `set(entityId, data)` 和 `get(entityId)` 读写编码后的数据。第二个 `get(entityId, params)` 支持带参数的查询，例如\"该实体在等级 N 时的 HP\"。\n\n**System** 是任何不要求实现特定接口的合约。一旦注册并启用，它就可以调用组件的 `set` 函数来改变状态。\n\n典型流程：部署 World → 创建实体 → 部署并注册组件 → 把组件附加到实体 → 部署并注册系统 → 调用系统。\n\n## 示例代码\n\n一个简单的位置组件和一个移动系统：\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IWorld {\n    function entityExists(uint256) external view returns (bool);\n    function getEntityState(uint256) external view returns (bool);\n    function hasComponent(uint256, address) external view returns (bool);\n    function getSystemState(address) external view returns (bool);\n}\n\ncontract PositionComponent {\n    address public immutable world;\n    mapping(uint256 =\u003e bytes) private data;\n\n    constructor(address _world) { world = _world; }\n\n    function set(uint256 id, bytes memory d) external {\n        IWorld w = IWorld(world);\n        require(w.getSystemState(msg.sender), \"system not enabled\");\n        require(w.getEntityState(id) \u0026\u0026 w.hasComponent(id, address(this)), \"entity\");\n        data[id] = d;\n    }\n\n    function get(uint256 id) external view returns (bytes memory) { return data[id]; }\n    // types() and get(id, params) omitted for brevity\n}\n\ncontract MoveSystem {\n    PositionComponent public immutable pos;\n    constructor(PositionComponent p) { pos = p; }\n\n    function move(uint256 id, int32 dx, int32 dy) external {\n        (int32 x, int32 y) = abi.decode(pos.get(id), (int32, int32));\n        pos.set(id, abi.encode(x + dx, y + dy));\n    }\n}\n```\n\n## 需要注意\n\n- 状态为 **Draft**。\n- 管理类函数（`createEntity`、`addComponent`、`registerSystem`、`set...State` 开关等）通常应仅限所有者调用。向普通用户开放它们是安全风险。\n- 任何已注册并启用的系统都可以修改 world 中每个实体的组件数据，因此在注册系统之前请先审计。规范建议，第三方贡献在审核通过之前以禁用状态注册。\n- 组件应在 `set()` 内部检查实体和系统的可用性，并且不暴露其他写入路径。\n- ECS 的拆分在精神上与 [ERC-2535](/eip-2535/) Diamond 等模块化升级模式有重叠，但它针对的是数据建模，而不是函数路由。\n"}}}
