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.
This article examines ERC7813, a proposal for organizing and managing blockchain data like a database to enable efficient, extensible on-chain data management.
The following material is translated, summarized, and supplemented with explanations.
I have also covered various EIPs, BIPs, SLIPs, CAIPs, ENSIPs, RFCs, and ACPs.
Overview
ERC7813 proposes an on-chain storage pattern for flexible blockchain data storage and management. Data is organized into structures called tables, each comprising a collection of records with key and value schemas defining their structure. This resembles tables in conventional databases.
The pattern defines the following components.
-
Unified contract interface A unified smart contract interface provides access to data. Different developers and services can therefore manipulate data using the same format.
-
Efficient binary encoding Both static (fixed-size) and dynamic (variable-size) data types are encoded compactly. This reduces gas costs for storage and event emission.
-
State management through standardized events Standardized events are emitted when smart contract state changes. Off-chain indexers can use these events to synchronize state automatically and replicate data according to its schema.
-
Dynamic table registration New tables can be registered dynamically at runtime. A special table stores schema metadata, allowing the system to be extended without breaking existing contracts or integrations.
This pattern provides greater flexibility in managing blockchain data structures and lets developers extend and update data safely and efficiently.
Motivation
Traditional smart contract development has lacked a unified standard for on-chain data management. This has led to several problems.
- Rigid data structures make extensions and changes difficult.
- Contract logic and off-chain services are tightly coupled, so updates can break compatibility.
- Changes to data structures can easily introduce problems in existing systems and integrations.
The storage pattern introduced by ERC7813 is designed to address these problems.
Benefits
| Benefit | Description |
|---|---|
| Automatic indexing | Off-chain services can automatically track and synchronize data through standard events emitted when state changes. This makes it easier to build schema-aware APIs. |
| No custom read functions | Individual contracts no longer need dedicated data retrieval functions. Data can be accessed through a unified interface, reducing coupling between contracts and external services and improving development efficiency. |
| Simpler upgrades | Unstructured storage enables logic to be upgraded without tying it to a fixed storage layout, avoiding risks associated with conventional fixed structures. |
| Flexible data extensions | New tables can be registered at runtime, allowing functionality to be extended while maintaining compatibility with existing systems and data consumers. |
| Lower gas costs | Efficient data packing reduces the cost of storage operations and event emission. |
Specification
Definitions
Store
// Store: A smart contract that implements the interface proposed by this ERC
// and organizes data in Tables. It emits events for each data operation.A Store is a smart contract implementing the interface defined by the ERC.
It organizes data into tables and emits events for data operations.
The Store centralizes operations such as reading, writing, and deleting data.
It exists on-chain and emits events for operations, enabling off-chain systems such as indexers to track and synchronize its state.
Table
// Table: A storage structure that holds Records sharing the same Schema.A Table is a storage structure containing multiple records with the same schema (data structure).
There are two types: on-chain tables and off-chain tables.
On-chain tables maintain state on the blockchain and also emit events.
Off-chain tables do not store the data itself on-chain and only emit events.
| Type | Description |
|---|---|
| On-chain table | Stores state on the blockchain and emits events for indexers. |
| Off-chain table | Emits events without maintaining state on-chain. |
Record
// Record: A piece of data stored in a Table, addressed by one or more keys.A Record is an individual unit of data stored in a table.
A record is uniquely identified by one or more keys.
Each record consists of keys (identifiers) and values (the data itself).
ResourceId
type ResourceId is bytes32;A ResourceId is a 32-byte value that uniquely identifies a table.
The first 2 bytes indicate the table type, and the remaining 30 bytes serve as a unique identifier.
0x7462 ("tb") denotes an on-chain table, and 0x6f74 ("ot") denotes an off-chain table.
| Byte range | Contents |
|---|---|
0-1 |
Identifier indicating the table type |
2-31 |
Unique table ID |
Schema
type Schema is bytes32;A Schema is a data type defining the structure of records in a table, including key and value types.
A table has two schemas: a key schema and a value schema.
The key schema consists only of fixed-length data types, whereas the value schema may contain both fixed-length and variable-length types.
| Byte range | Contents | Constraint |
|---|---|---|
0-1 |
Total byte length of static fields | - |
2 |
Number of static fields | At most (28 - number of dynamic fields) |
3 |
Number of dynamic fields | 0 for key schemas; at most 5 for value schemas |
4-31 |
One byte specifying each field type | Dynamic types must follow static types |
SchemaType
enum SchemaType {
// uint系: 0x00〜0x1F
// int系: 0x20〜0x3F
// bytes系: 0x40〜0x5F
// bool: 0x60
// address: 0x61
// 可変長配列やbytes/string型も含む
}A SchemaType represents each field type in a schema as a one-byte value.
Mapping data types to small integers enables an efficient binary representation.
| Value range | Data type |
|---|---|
0x00〜0x1F |
uint8〜uint256 |
0x20〜0x3F |
int8〜int256 |
0x40〜0x5F |
bytes1〜bytes32 |
0x60 |
bool |
0x61 |
address |
0x62〜0x81 |
uint8[]〜uint256[] |
0xC4 |
bytes |
0xC5 |
string |
FieldLayout
type FieldLayout is bytes32;A FieldLayout encodes the concrete layout of a schema, such as the byte length of each static field.
It stores precomputed field lengths to optimize on-chain processing.
| Byte range | Contents | Constraint |
|---|---|---|
0-1 |
Total length of static fields | - |
2 |
Number of static fields | At most (28 - number of dynamic fields) |
3 |
Number of dynamic fields | 0 for key schemas; at most 5 for value schemas |
4-31 |
Length of each static field | - |
EncodedLengths
type EncodedLengths is bytes32;EncodedLengths is a value encoding the lengths of all dynamic fields together.
It holds the information necessary to decode dynamic data.
This avoids storing the length of each dynamic field separately, improving efficiency.
| Byte range | Type | Contents |
|---|---|---|
0x00–0x06 |
uint56 | Total length of dynamic data |
0x07–0x0B |
uint40 | Length of the first dynamic field |
0x0C–0x10 |
uint40 | Length of the second dynamic field |
| ... | ... | Supports up to 5 fields |
Data Encoding
Record data returned by Store methods or emitted in events is encoded according to the following rules.
- Static fields are concatenated without padding (extra zero bytes).
- Dynamic fields are concatenated without their individual lengths, which are collected into one
EncodedLengthsvalue. - A record can contain up to 28 fields, of which at most 5 may be dynamic.
Encoding Example
(uint256 id, address owner, string description, uint8[] scores)The following is an example in pseudocode.
bytes memory staticData = abi.encodePacked(id, owner);
bytes memory packedScores = packElementsWithoutPadding(scores);
bytes memory dynamicData = abi.encodePacked(description, packedScores);
EncodedLengths encodedLengths = dynamicData.length;
encodedLengths |= (description.length << (56));
encodedLengths |= (encodedData.length << (56 + 8 * 5));
// Full record
(staticData, encodedLengths, dynamicData)The Store Interface
interface IStore {
function getRecord(ResourceId tableId, bytes32[] calldata keyTuple)
external view returns (bytes memory staticData, EncodedLengths encodedLengths, bytes memory dynamicData);
function getField(ResourceId tableId, bytes32[] calldata keyTuple, uint8 fieldIndex)
external view returns (bytes memory data);
function getFieldLength(ResourceId tableId, bytes32[] memory keyTuple, uint8 fieldIndex)
external view returns (uint256);
}getRecord
Retrieves the entire record corresponding to a specified table ID and key. Returns static data, dynamic data, and dynamic field length information.
Arguments
tableId- The target table's
ResourceId.
- The target table's
keyTuple- An array of keys identifying the record.
Return values
staticData- Static data in binary form.
encodedLengths- Dynamic field length information.
dynamicData- The dynamic data itself.
getField
Retrieves data from a single specified field. Returns the individual field's encoded data.
Arguments
tableId- The table's
ResourceId.
- The table's
keyTuple- The target record's keys.
fieldIndex- The index of the field to retrieve.
Return value
data- Encoded field data.
getFieldLength
Retrieves the byte length of the specified field. Returns the length of the data regardless of whether the field is static or dynamic.
Arguments
tableId- The table identifier.
keyTuple- The target record's keys.
fieldIndex- The target field index.
Return value
uint256- The byte length.
Store Operations and Events
Store_SetRecord
event Store_SetRecord(
ResourceId indexed tableId,
bytes32[] keyTuple,
bytes staticData,
EncodedLengths encodedLengths,
bytes dynamicData
);An event emitted when an entire record is set (overwritten). It is emitted whenever a record is written in full, whether the record is new or already exists.
Parameters
tableId- The target table ID.
keyTuple- The record's key array.
staticData- Encoded static data.
encodedLengths- Dynamic field length information.
dynamicData- Encoded dynamic data.
Store_SpliceStaticData
event Store_SpliceStaticData(
ResourceId indexed tableId,
bytes32[] keyTuple,
uint48 start,
bytes data
);An event emitted when part of the static data is overwritten. It is emitted when an operation overwrites static data at a specified position.
Parameters
tableId- The target table ID.
keyTuple- The record's keys.
start- The byte offset at which to start overwriting.
data- The replacement data.
Store_SpliceDynamicData
event Store_SpliceDynamicData(
ResourceId indexed tableId,
bytes32[] keyTuple,
uint8 dynamicFieldIndex,
uint48 start,
uint40 deleteCount,
EncodedLengths encodedLengths,
bytes data
);An event emitted when part of the dynamic data changes. It is emitted when dynamic data is inserted, deleted, or replaced.
Parameters
tableId- The target table ID.
keyTuple- The record's keys.
dynamicFieldIndex- The dynamic field index.
start- The starting offset of the operation.
deleteCount- The number of bytes to delete.
encodedLengths- Updated dynamic field length information.
data- The data to insert.
Store_DeleteRecord
event Store_DeleteRecord(ResourceId indexed tableId, bytes32[] keyTuple);An event emitted when a record is deleted. It is emitted when the record identified by the specified keys is removed from the table.
Parameters
tableId- The table ID.
keyTuple- The keys identifying the record to delete.
The Special Tables Table
This is a special on-chain table that manages information about all tables. It is used to register new tables dynamically.
| Key | Description |
|---|---|
tableId |
ResourceId of the target table. |
| Value | Description |
|---|---|
fieldLayout |
A FieldLayout encoding the byte length of each static data type. |
keySchema |
Schema specifying the key data types. |
valueSchema |
Schema specifying the value data types. |
abiEncodedKeyNames |
ABI-encoded key names. |
abiEncodedFieldNames |
ABI-encoded field names. |
Records stored in this table are immutable.
A Store_SetRecord event is emitted once at registration, and the record cannot be modified afterward.
The following is an example of a tableId used during registration.
ResourceId tableId = ResourceId.wrap(
0x746273746f72650000000000000000005461626c657300000000000000000000
);This mechanism lets off-chain indexers interpret the structure of every table and handle blockchain data like a structured database.
Additional Details
Splice Events
The Store defines the Store_SetRecord event for overwriting an entire record, but relying exclusively on that event is inefficient.
ERC7813 therefore introduces two splice events for partial updates: Store_SpliceStaticData and Store_SpliceDynamicData.
Why Partial Updates Are Needed
Emitting Store_SetRecord when only part of the data has changed requires reading and re-encoding the entire record before emitting it again.
This is inefficient in both gas costs and processing overhead.
The cost grows rapidly for records containing large variable-length data, such as long strings or arrays.
Splice events allow only the changed portion to be updated using minimal data. This provides the following benefits.
| Benefit | Effect |
|---|---|
| Lower update costs | Processing only the changed portion instead of reconstructing the entire record reduces gas costs. |
| Greater scalability | Costs grow more slowly even for large data structures, making the design easier to scale. |
| More efficient off-chain synchronization | Indexers need to process only changes, allowing faster state synchronization. |
Splice events enable efficient incremental updates to on-chain storage.
Prohibition of Arrays of Dynamic Types
The ERC explicitly prohibits defining arrays of dynamic types, such as string[] and bytes[], in schemas.
This is an intentional constraint that helps keep the system simple and efficient.
Rationale for the Constraint
Arrays of dynamic types create nested variable-length data structures, complicating storage implementations and encoding. This increases gas costs for storage operations and makes decoding more expensive.
To avoid this problem, the specification favors flat data structures. Records are represented as one-dimensional data structures, and complex array structures are managed using separate tables.
Alternative Data Model
To store a variable-length array such as string[], use a table structured as follows.
| Column name | Type | Description |
|---|---|---|
index |
uint256 |
Array element index |
data |
bytes |
Actual element data |
Storing one element per record allows array operations to be implemented safely as table operations. This simplifies the design and significantly improves gas efficiency.
FieldLayout Optimization
FieldLayout is a structure that stores precomputed byte lengths for the static (fixed-length) fields in a table.
Including this in the schema metadata (the Tables table) can significantly improve runtime efficiency.
How the Optimization Works
Smart contracts typically calculate field lengths and offsets dynamically. This requires computation and increases gas consumption, especially for complex schemas.
With FieldLayout, each field's byte length can be recorded in advance, eliminating the need to recalculate it at runtime.
This reduces storage operation costs and makes data reads and writes more efficient.
Main Benefits
| Benefit | Description |
|---|---|
| Lower execution costs | Gas usage decreases because lengths and offsets do not need to be recalculated each time. |
| Faster reads | Off-chain systems can also retrieve FieldLayout information from the Tables table and decode data quickly. |
| Implementation consistency | Schema information can be handled uniformly across all tables. |
FieldLayout acts as a cache of schema information, optimizing both on-chain and off-chain processing.
The Special Tables Table
Finally, ERC7813 defines a special on-chain table called the Tables table.
It serves as a metadata table for registering and managing the schema information of every table.
Purpose and Role
This table enables off-chain indexers to discover table structures (schemas) automatically. Instead of handling raw binary data without knowledge of its schema, indexers can process data with an understanding of its structure, enabling SQL-like queries and advanced data analysis.
Main Benefits
| Benefit | Description |
|---|---|
| Schema-aware indexers | APIs supporting advanced data queries can be built using the schema information of each table. |
| Simpler implementation | Table registration reuses existing Store events, so no new events need to be introduced. |
| Consistency and extensibility | All tables are managed through the same Store interface, maintaining consistency throughout the system. |
Illustration
Tables テーブル
┌─────────────────────┐
│ tableId │→ 各テーブルの識別子
│ fieldLayout │→ 静的フィールドの長さ情報
│ keySchema │→ キーの型情報
│ valueSchema │→ 値の型情報
│ abiEncodedKeyNames │→ キー名(文字列配列)
│ abiEncodedFieldNames│→ フィールド名(文字列配列)
└─────────────────────┘
↓ 登録イベント(Store_SetRecord)
他のすべてのテーブルがここで登録されるThe Tables table serves as the central schema registry on the blockchain, allowing off-chain services to understand data structures accurately.
Reference Implementation
Indexing Store Events
The following example shows how a simple in-memory indexer can use Store events to replicate Store state off-chain.
The indexer operates on raw encoded data.
The example uses TypeScript but can easily be reproduced in other languages.
type Hex = `0x${string}`;
type Record = {
staticData: Hex;
encodedLengths: Hex;
dynamicData: Hex;
};
const store = new Map<string, Record>();
// Create a key string from a table ID and key tuple to use in our store Map above
function storeKey(tableId: Hex, keyTuple: Hex[]): string {
return `${tableId}:${keyTuple.join(",")}`;
}
// Like `Array.splice`, but for strings of bytes
function bytesSplice(
data: Hex,
start: number,
deleteCount = 0,
newData: Hex = "0x"
): Hex {
const dataNibbles = data.replace(/^0x/, "").split("");
const newDataNibbles = newData.replace(/^0x/, "").split("");
return `0x${dataNibbles
.splice(start, deleteCount * 2)
.concat(newDataNibbles)
.join("")}`;
}
function bytesLength(data: Hex): number {
return data.replace(/^0x/, "").length / 2;
}
function processStoreEvent(log: StoreEvent) {
if (log.eventName === "Store_SetRecord") {
const key = storeKey(log.args.tableId, log.args.keyTuple);
// Overwrite all of the Record's fields
store.set(key, {
staticData: log.args.staticData,
encodedLengths: log.args.encodedLengths,
dynamicData: log.args.dynamicData,
});
} else if (log.eventName === "Store_SpliceStaticData") {
const key = storeKey(log.args.tableId, log.args.keyTuple);
const record = store.get(key) ?? {
staticData: "0x",
encodedLengths: "0x",
dynamicData: "0x",
};
// Splice the static field data of the Record
store.set(key, {
staticData: bytesSplice(
record.staticData,
log.args.start,
bytesLength(log.args.data),
log.args.data
),
encodedLengths: record.encodedLengths,
dynamicData: record.dynamicData,
});
} else if (log.eventName === "Store_SpliceDynamicData") {
const key = storeKey(log.args.tableId, log.args.keyTuple);
const record = store.get(key) ?? {
staticData: "0x",
encodedLengths: "0x",
dynamicData: "0x",
};
// Splice the dynamic field data of the Record
store.set(key, {
staticData: record.staticData,
encodedLengths: log.args.encodedLengths,
dynamicData: bytesSplice(
record.dynamicData,
log.args.start,
log.args.deleteCount,
log.args.data
),
});
} else if (log.eventName === "Store_DeleteRecord") {
const key = storeKey(log.args.tableId, log.args.keyTuple);
// Delete the whole Record
store.delete(key);
}
}Security
Access Control
ERC7813 defines only the functions for reading data from a Store.
Specifically, it defines these three functions.
| Function | Purpose |
|---|---|
getRecord |
Retrieves an entire record using the specified table ID and keys. |
getField |
Retrieves only the specified field. |
getFieldLength |
Retrieves the length of the specified field. |
These functions are read-only.
The standard does not define functions for writing, modifying, or deleting data.
Developers implementing a Store must therefore establish appropriate access control for their use cases.
Why Access Control Is Necessary
On a blockchain, contracts and accounts are public, and anyone can call a function declared public or external.
If data update methods can be called without restrictions, malicious third parties may be able to alter storage contents freely.
Example Implementation Measures
| Measure | Description |
|---|---|
| Role-based access control | Use Ownable or AccessControl to allow writes only by an administrator (owner) or addresses with a specified role. |
| Allowlist | Restrict write operations on the Store to approved contracts or accounts. |
| Authorized function calls | Verify signatures when transactions are submitted to determine whether the signer has legitimate authority. |
Developers must clearly define what data their applications manage and who can change that data and how, then design access controls accordingly.
Public Availability of On-chain Data
Another important security property is that data stored in a Store is fully public.
In conventional smart contracts, storage variables are treated as internal state and cannot be read directly by other contracts.
Developers must explicitly provide read functions if other contracts need access.
The Store defined by ERC7813 differs in this respect.
Any contract can access data in the Store through the following read functions.
| Function | Description |
|---|---|
getRecord |
Retrieves an entire record given a table ID and keys. |
getField |
Retrieves a particular field individually. |
getFieldLength |
Retrieves the byte length of a field. |
This mechanism allows other on-chain smart contracts to read data stored in a Store directly.
Although this improves transparency and interoperability, it introduces a clear constraint: confidential information must not be stored in plaintext.
Implications of Public Data
- Reads from other contracts
Other smart contracts can access data by calling functions such as
getRecord. This makes sharing data across applications easier. - Off-chain access
Anyone can scan the blockchain and reconstruct all data in the
Store. Personal information and confidential data should therefore not be stored there. - Cases requiring encryption If confidential data must be handled, the recommended design is to encrypt it before storage and perform decryption off-chain.
Summary of Precautions
| Precaution | Description |
|---|---|
| All data is public | Anyone can access data stored in a Store, whether on-chain or off-chain. |
| Do not store sensitive information | Personal information, private keys, passwords, and data about internal logic must not be stored directly. |
| Consider encrypted storage | If confidentiality is required, use a design that stores only encrypted data. |
Citation
alvarius (@alvrs), dk1a (@dk1a), frolic (@frolic), ludens (@ludns), vdrg (@vdrg), yonada yonada@proton.me, "ERC-7813: Store, Table-Based Introspectable Storage [DRAFT]," Ethereum Improvement Proposals, no. 7813, November 2024. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-7813.
Conclusion
This article covered ERC7813, a proposal for organizing and managing blockchain data like a database to enable efficient, extensible on-chain data management. I hope you found it useful.
If you have questions, feel free to contact me by direct message on Twitter.
I also share information on other platforms, so feel free to explore them.



