{"eip":7813,"title":"Store, Table-Based Introspectable Storage","description":"On-chain tables for automatic indexing and introspectable state","authors":["alvarius (@alvrs)","dk1a (@dk1a)","frolic (@frolic)","ludens (@ludns)","vdrg (@vdrg)","yonada \u003cyonada@proton.me\u003e"],"status":"Final","type":"Standards Track","category":"ERC","created":"2024-11-08","discussionsTo":"https://ethereum-magicians.org/t/erc-7813-store-table-based-introspectable-storage/21628","repo":"ERCs","label":"ERC-7813","officialUrl":"https://eips.ethereum.org/EIPS/eip-7813","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-7813.md","url":"https://eips.huatuo.xyz/eip-7813/","tldr":{"en":"A storage standard that organizes contract data into typed tables with schemas registered on-chain and standard events for every write, so indexers can replicate any contract's state automatically without custom getters.","ja":"コントラクトのデータを、スキーマがオンチェーンに登録された型付きテーブルに整理し、すべての書き込みで標準イベントを emit するストレージ標準。インデクサーは、独自の getter なしに、あらゆるコントラクトの状態を自動的に複製できる。","ko":"컨트랙트 데이터를, 스키마가 온체인에 등록된 타입 있는 테이블로 정리하고 모든 쓰기마다 표준 이벤트를 발생시키는 스토리지 표준. 인덱서가 커스텀 getter 없이도 어떤 컨트랙트의 상태든 자동으로 복제할 수 있다.","zh":"一种存储标准：把合约数据组织成带类型的表，表的 schema 在链上注册，每次写入都触发标准事件，这样索引器无需自定义 getter 就能自动复制任何合约的状态。"},"tags":["storage","indexing","tables","events","mud"],"explainers":{"en":{"lang":"en","tldr":"A storage standard that organizes contract data into typed tables with schemas registered on-chain and standard events for every write, so indexers can replicate any contract's state automatically without custom getters.","tags":["storage","indexing","tables","events","mud"],"related":[7208],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-7813/","markdown":"## What problem does it solve?\n\nIn a typical contract, data lives in Solidity variables and mappings. To read it, others need a getter written specifically for it. To index it, someone writes a custom subgraph or indexer that knows that contract's events. Changing the data layout breaks those integrations, and upgrades must carefully preserve the storage layout.\n\nERC-7813 defines a **Store**: data is kept in tables whose key and value schemas are themselves stored on-chain, and every write emits one of four standard events. Any generic indexer can then rebuild every table of every Store, and any contract can read any record through a single interface. It standardizes the Store model used by the MUD framework.\n\n## How it works\n\n- **Tables** are identified by a 32-byte `ResourceId`: two bytes for the type (`\"tb\"` on-chain, `\"ot\"` off-chain, which only emits events), then a 30-byte name.\n- **Records** are addressed by a key tuple (`bytes32[]`).\n- Each table has a **key schema** (static types only) and a **value schema** (up to 28 fields, at most 5 of them dynamic). A `Schema` packs field types into one `bytes32`, one byte per field (`0x00`–`0x1F` for `uint8`…`uint256`, `0x61` `address`, `0xC4` `bytes`, `0xC5` `string`, and so on). Arrays of dynamic types such as `string[]` are not allowed.\n- **Encoding**: static fields are tightly packed; dynamic fields are concatenated without lengths, and their lengths go into a single `EncodedLengths` word. A record is `(staticData, encodedLengths, dynamicData)`.\n- **Read interface**: `getRecord`, `getField`, `getFieldLength`. Writes are implementation-specific.\n- **Events**: `Store_SetRecord` (full overwrite), `Store_SpliceStaticData` and `Store_SpliceDynamicData` (partial updates, cheaper than re-emitting the whole record), `Store_DeleteRecord`. On-chain table contents MUST always equal what replaying these events gives.\n- A special **`Tables`** table stores each table's field layout, schemas and key/field names. It registers itself first, so an indexer that knows only this one table ID can decode everything else.\n\n## Sample code\n\nThe read interface:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity \u003e=0.8.24;\n\ntype ResourceId is bytes32;\ntype EncodedLengths is bytes32;\n\ninterface IStore {\n    function getRecord(ResourceId tableId, bytes32[] calldata keyTuple)\n        external view\n        returns (bytes memory staticData, EncodedLengths encodedLengths, bytes memory dynamicData);\n\n    function getField(ResourceId tableId, bytes32[] calldata keyTuple, uint8 fieldIndex)\n        external view returns (bytes memory data);\n\n    function getFieldLength(ResourceId tableId, bytes32[] memory keyTuple, uint8 fieldIndex)\n        external view returns (uint256);\n}\n```\n\nFollowing a Store from TypeScript (ethers v6):\n\n```ts\nconst store = new Contract(STORE, [\n  \"event Store_SetRecord(bytes32 indexed tableId, bytes32[] keyTuple, bytes staticData, bytes32 encodedLengths, bytes dynamicData)\",\n  \"event Store_DeleteRecord(bytes32 indexed tableId, bytes32[] keyTuple)\",\n], provider);\n\nstore.on(\"Store_SetRecord\", (tableId, keyTuple, staticData, encodedLengths, dynamicData) =\u003e {\n  db.upsert(tableId, keyTuple, { staticData, encodedLengths, dynamicData });\n});\n```\n\n## Things to know\n\n- **Status: Final.**\n- The standard only defines reads. Each implementation must add its own access control for writes.\n- Everything in a Store is readable by any other contract through `getRecord`/`getField`, unlike ordinary contract storage, which other contracts cannot read without a getter. Do not treat any table as private.\n- Off-chain tables (`\"ot\"`) are a cheap way to publish data via events only; their content cannot be read on-chain.\n- The `Tables` table ID is fixed: `0x746273746f72650000000000000000005461626c657300000000000000000000` (`\"tb\"` + `\"store\"` + `\"Tables\"`).\n"},"ja":{"lang":"ja","tldr":"コントラクトのデータを、スキーマがオンチェーンに登録された型付きテーブルに整理し、すべての書き込みで標準イベントを emit するストレージ標準。インデクサーは、独自の getter なしに、あらゆるコントラクトの状態を自動的に複製できる。","tags":["storage","indexing","tables","events","mud"],"related":[7208],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-7813/","markdown":"## 何を解決するのか\n\n典型的なコントラクトでは、データは Solidity の変数やマッピングに保存されます。それを読むには、そのデータ専用に書かれた getter が必要です。インデックスを作るには、そのコントラクトのイベントを理解したカスタムのサブグラフやインデクサーを誰かが書くことになります。データレイアウトを変更するとそれらの連携が壊れ、アップグレードではストレージレイアウトを慎重に維持しなければなりません。\n\nERC-7813 は **Store** を定義します。データは、キーと値のスキーマ自体がオンチェーンに保存されたテーブルに保持され、すべての書き込みで 4 つの標準イベントのいずれかが emit されます。これにより、汎用のインデクサーならどの Store のどのテーブルも再構築でき、どのコントラクトも単一のインターフェースを通じて任意のレコードを読めます。これは MUD フレームワークが使う Store モデルを標準化するものです。\n\n## 仕組み\n\n- **テーブル**は 32 バイトの `ResourceId` で識別されます。先頭 2 バイトが種別（オンチェーンなら `\"tb\"`、イベントのみを emit するオフチェーンなら `\"ot\"`）で、続く 30 バイトが名前です。\n- **レコード**はキータプル（`bytes32[]`）でアドレス指定されます。\n- 各テーブルには**キースキーマ**（静的型のみ）と**値スキーマ**（最大 28 フィールドで、動的なものは最大 5 つ）があります。`Schema` は各フィールドの型を 1 フィールド 1 バイトで 1 つの `bytes32` にパックします（`uint8`〜`uint256` は `0x00`〜`0x1F`、`address` は `0x61`、`bytes` は `0xC4`、`string` は `0xC5`、など）。`string[]` のような動的型の配列は使えません。\n- **エンコーディング**: 静的フィールドは隙間なく詰められます。動的フィールドは長さなしで連結され、それらの長さは 1 つの `EncodedLengths` ワードにまとめられます。レコードは `(staticData, encodedLengths, dynamicData)` です。\n- **読み取りインターフェース**: `getRecord`、`getField`、`getFieldLength`。書き込みは実装依存です。\n- **イベント**: `Store_SetRecord`（全体の上書き）、`Store_SpliceStaticData` と `Store_SpliceDynamicData`（部分更新で、レコード全体を再 emit するより安価）、`Store_DeleteRecord`。オンチェーンのテーブル内容は、これらのイベントをリプレイして得られる内容と常に一致しなければなりません（MUST）。\n- 特別な **`Tables`** テーブルが、各テーブルのフィールドレイアウト、スキーマ、キー名・フィールド名を保存します。これは最初に自分自身を登録するため、このテーブル ID だけを知っているインデクサーが、それ以外のすべてをデコードできます。\n\n## サンプルコード\n\n読み取りインターフェース:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity \u003e=0.8.24;\n\ntype ResourceId is bytes32;\ntype EncodedLengths is bytes32;\n\ninterface IStore {\n    function getRecord(ResourceId tableId, bytes32[] calldata keyTuple)\n        external view\n        returns (bytes memory staticData, EncodedLengths encodedLengths, bytes memory dynamicData);\n\n    function getField(ResourceId tableId, bytes32[] calldata keyTuple, uint8 fieldIndex)\n        external view returns (bytes memory data);\n\n    function getFieldLength(ResourceId tableId, bytes32[] memory keyTuple, uint8 fieldIndex)\n        external view returns (uint256);\n}\n```\n\nTypeScript（ethers v6）で Store を追跡する例:\n\n```ts\nconst store = new Contract(STORE, [\n  \"event Store_SetRecord(bytes32 indexed tableId, bytes32[] keyTuple, bytes staticData, bytes32 encodedLengths, bytes dynamicData)\",\n  \"event Store_DeleteRecord(bytes32 indexed tableId, bytes32[] keyTuple)\",\n], provider);\n\nstore.on(\"Store_SetRecord\", (tableId, keyTuple, staticData, encodedLengths, dynamicData) =\u003e {\n  db.upsert(tableId, keyTuple, { staticData, encodedLengths, dynamicData });\n});\n```\n\n## 知っておくべきこと\n\n- **ステータス: Final。**\n- この標準が定義するのは読み取りだけです。書き込みのアクセス制御は、各実装が独自に追加する必要があります。\n- Store 内のすべてのデータは、`getRecord` / `getField` を通じて他のどのコントラクトからも読めます。getter なしでは他のコントラクトから読めない通常のコントラクトストレージとは異なります。どのテーブルもプライベートだと考えてはいけません。\n- オフチェーンテーブル（`\"ot\"`）は、イベントだけでデータを公開する安価な方法です。その内容はオンチェーンでは読めません。\n- `Tables` テーブルの ID は固定です: `0x746273746f72650000000000000000005461626c657300000000000000000000`（`\"tb\"` + `\"store\"` + `\"Tables\"`）。\n"},"ko":{"lang":"ko","tldr":"컨트랙트 데이터를, 스키마가 온체인에 등록된 타입 있는 테이블로 정리하고 모든 쓰기마다 표준 이벤트를 발생시키는 스토리지 표준. 인덱서가 커스텀 getter 없이도 어떤 컨트랙트의 상태든 자동으로 복제할 수 있다.","tags":["storage","indexing","tables","events","mud"],"related":[7208],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-7813/","markdown":"## 어떤 문제를 해결하나요?\n\n일반적인 컨트랙트에서 데이터는 Solidity 변수와 매핑에 저장됩니다. 이를 읽으려면 그 데이터를 위해 따로 작성한 getter가 필요합니다. 인덱싱하려면 누군가 그 컨트랙트의 이벤트를 아는 커스텀 서브그래프나 인덱서를 작성해야 합니다. 데이터 레이아웃을 바꾸면 이런 연동이 깨지고, 업그레이드할 때는 스토리지 레이아웃을 신중하게 유지해야 합니다.\n\nERC-7813은 **Store**를 정의합니다. 데이터는 키와 값의 스키마 자체가 온체인에 저장된 테이블에 보관되고, 모든 쓰기는 네 가지 표준 이벤트 중 하나를 emit합니다. 그러면 범용 인덱서가 어떤 Store의 모든 테이블이든 재구성할 수 있고, 어떤 컨트랙트든 단일 인터페이스로 어떤 레코드든 읽을 수 있습니다. 이는 MUD 프레임워크가 사용하는 Store 모델을 표준화한 것입니다.\n\n## 어떻게 동작하나요?\n\n- **테이블**은 32바이트 `ResourceId`로 식별됩니다. 앞 두 바이트가 타입(온체인은 `\"tb\"`, 이벤트만 emit하는 오프체인은 `\"ot\"`)이고 그 뒤 30바이트가 이름입니다.\n- **레코드**는 키 튜플(`bytes32[]`)로 주소를 지정합니다.\n- 각 테이블에는 **키 스키마**(정적 타입만)와 **값 스키마**(최대 28개 필드, 그중 동적 필드는 최대 5개)가 있습니다. `Schema`는 필드 타입을 필드당 한 바이트씩 하나의 `bytes32`에 담습니다(`uint8`…`uint256`은 `0x00`–`0x1F`, `address`는 `0x61`, `bytes`는 `0xC4`, `string`은 `0xC5` 등). `string[]` 같은 동적 타입의 배열은 허용되지 않습니다.\n- **인코딩**: 정적 필드는 빈틈없이 패킹됩니다. 동적 필드는 길이 없이 이어 붙이고, 그 길이들은 하나의 `EncodedLengths` 워드에 담습니다. 레코드는 `(staticData, encodedLengths, dynamicData)`입니다.\n- **읽기 인터페이스**: `getRecord`, `getField`, `getFieldLength`. 쓰기는 구현에 따라 다릅니다.\n- **이벤트**: `Store_SetRecord`(전체 덮어쓰기), `Store_SpliceStaticData`와 `Store_SpliceDynamicData`(부분 업데이트로, 레코드 전체를 다시 emit하는 것보다 저렴함), `Store_DeleteRecord`. 온체인 테이블의 내용은 이 이벤트들을 재생해서 얻은 결과와 항상 같아야 합니다(MUST).\n- 특별한 **`Tables`** 테이블은 각 테이블의 필드 레이아웃, 스키마, 키 이름/필드 이름을 저장합니다. 이 테이블이 가장 먼저 자기 자신을 등록하므로, 이 테이블 ID 하나만 아는 인덱서도 나머지 전부를 디코딩할 수 있습니다.\n\n## 샘플 코드\n\n읽기 인터페이스:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity \u003e=0.8.24;\n\ntype ResourceId is bytes32;\ntype EncodedLengths is bytes32;\n\ninterface IStore {\n    function getRecord(ResourceId tableId, bytes32[] calldata keyTuple)\n        external view\n        returns (bytes memory staticData, EncodedLengths encodedLengths, bytes memory dynamicData);\n\n    function getField(ResourceId tableId, bytes32[] calldata keyTuple, uint8 fieldIndex)\n        external view returns (bytes memory data);\n\n    function getFieldLength(ResourceId tableId, bytes32[] memory keyTuple, uint8 fieldIndex)\n        external view returns (uint256);\n}\n```\n\nTypeScript(ethers v6)로 Store 따라가기:\n\n```ts\nconst store = new Contract(STORE, [\n  \"event Store_SetRecord(bytes32 indexed tableId, bytes32[] keyTuple, bytes staticData, bytes32 encodedLengths, bytes dynamicData)\",\n  \"event Store_DeleteRecord(bytes32 indexed tableId, bytes32[] keyTuple)\",\n], provider);\n\nstore.on(\"Store_SetRecord\", (tableId, keyTuple, staticData, encodedLengths, dynamicData) =\u003e {\n  db.upsert(tableId, keyTuple, { staticData, encodedLengths, dynamicData });\n});\n```\n\n## 알아둘 점\n\n- **상태: Final.**\n- 이 표준은 읽기만 정의합니다. 쓰기에 대한 접근 제어는 각 구현이 직접 추가해야 합니다.\n- Store의 모든 데이터는 `getRecord`/`getField`를 통해 다른 어떤 컨트랙트에서도 읽을 수 있습니다. getter 없이는 다른 컨트랙트가 읽을 수 없는 일반 컨트랙트 스토리지와 다릅니다. 어떤 테이블도 비공개라고 생각하지 마세요.\n- 오프체인 테이블(`\"ot\"`)은 이벤트만으로 데이터를 게시하는 저렴한 방법입니다. 그 내용은 온체인에서 읽을 수 없습니다.\n- `Tables` 테이블의 ID는 고정되어 있습니다. `0x746273746f72650000000000000000005461626c657300000000000000000000`(`\"tb\"` + `\"store\"` + `\"Tables\"`).\n"},"zh":{"lang":"zh","tldr":"一种存储标准：把合约数据组织成带类型的表，表的 schema 在链上注册，每次写入都触发标准事件，这样索引器无需自定义 getter 就能自动复制任何合约的状态。","tags":["storage","indexing","tables","events","mud"],"related":[7208],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-7813/","markdown":"## 它解决什么问题？\n\n在典型的合约中，数据保存在 Solidity 变量和 mapping 里。要读取它，别人需要一个专门为此编写的 getter。要为它建立索引，就得有人编写了解该合约事件的自定义 subgraph 或索引器。一旦数据布局改变，这些集成就会失效，而升级时也必须小心地保持存储布局不变。\n\nERC-7813 定义了一个 **Store**：数据保存在表中，表的键和值 schema 本身也存储在链上，每次写入都会触发四种标准事件之一。这样，任何通用索引器都能重建任何 Store 的所有表，任何合约也能通过同一个接口读取任何记录。它标准化了 MUD 框架所使用的 Store 模型。\n\n## 它如何运作\n\n- **表**由一个 32 字节的 `ResourceId` 标识：前两个字节表示类型（链上为 `\"tb\"`，链下为 `\"ot\"`，后者只触发事件），其后是 30 字节的名称。\n- **记录**由键元组（`bytes32[]`）寻址。\n- 每个表都有一个**键 schema**（只能是静态类型）和一个**值 schema**（最多 28 个字段，其中动态字段最多 5 个）。`Schema` 把字段类型打包进一个 `bytes32`，每个字段一个字节（`uint8`…`uint256` 用 `0x00`–`0x1F`，`address` 用 `0x61`，`bytes` 用 `0xC4`，`string` 用 `0xC5`，等等）。不允许使用 `string[]` 这类动态类型的数组。\n- **编码**：静态字段紧凑打包；动态字段不带长度地拼接在一起，它们的长度放进同一个 `EncodedLengths` 字中。一条记录是 `(staticData, encodedLengths, dynamicData)`。\n- **读取接口**：`getRecord`、`getField`、`getFieldLength`。写入方式由实现自行决定。\n- **事件**：`Store_SetRecord`（整条覆盖）、`Store_SpliceStaticData` 和 `Store_SpliceDynamicData`（部分更新，比重新触发整条记录更便宜）、`Store_DeleteRecord`。链上表的内容必须（MUST）始终等于重放这些事件所得到的结果。\n- 一个特殊的 **`Tables`** 表存储每个表的字段布局、schema 以及键名/字段名。它最先注册自己，所以只知道这一个表 ID 的索引器就能解码其他所有内容。\n\n## 示例代码\n\n读取接口：\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity \u003e=0.8.24;\n\ntype ResourceId is bytes32;\ntype EncodedLengths is bytes32;\n\ninterface IStore {\n    function getRecord(ResourceId tableId, bytes32[] calldata keyTuple)\n        external view\n        returns (bytes memory staticData, EncodedLengths encodedLengths, bytes memory dynamicData);\n\n    function getField(ResourceId tableId, bytes32[] calldata keyTuple, uint8 fieldIndex)\n        external view returns (bytes memory data);\n\n    function getFieldLength(ResourceId tableId, bytes32[] memory keyTuple, uint8 fieldIndex)\n        external view returns (uint256);\n}\n```\n\n用 TypeScript（ethers v6）跟踪一个 Store：\n\n```ts\nconst store = new Contract(STORE, [\n  \"event Store_SetRecord(bytes32 indexed tableId, bytes32[] keyTuple, bytes staticData, bytes32 encodedLengths, bytes dynamicData)\",\n  \"event Store_DeleteRecord(bytes32 indexed tableId, bytes32[] keyTuple)\",\n], provider);\n\nstore.on(\"Store_SetRecord\", (tableId, keyTuple, staticData, encodedLengths, dynamicData) =\u003e {\n  db.upsert(tableId, keyTuple, { staticData, encodedLengths, dynamicData });\n});\n```\n\n## 需要注意\n\n- **状态：Final。**\n- 该标准只定义读取。每个实现都必须为写入添加自己的访问控制。\n- Store 中的所有数据都可以被任何其他合约通过 `getRecord`/`getField` 读取，这与普通合约存储不同（其他合约没有 getter 就无法读取）。不要把任何表当作私有的。\n- 链下表（`\"ot\"`）是仅通过事件发布数据的廉价方式；其内容无法在链上读取。\n- `Tables` 表的 ID 是固定的：`0x746273746f72650000000000000000005461626c657300000000000000000000`（`\"tb\"` + `\"store\"` + `\"Tables\"`）。\n"}}}
