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 ERC-5202, a standard that defines a bytecode format for blueprint contracts, making it easier to deploy multiple instances of a contract.
This article translates, summarizes, and expands on the proposal below, as discussed in the original article published on January 6, 2024. Historical statements reflect the context of that article.
I have also written about various other ERCs.
Some sections require familiarity with EVM opcodes. The following resource provides further background.
Overview
A blueprint contract is a contract that stores initialization code (initcode) on-chain in a standardized format. This initialization code defines how a contract is created and determines the code and initial state of the resulting contract. It acts as a blueprint for deployment.
With blueprint contracts, developers can deploy the code once and then reuse the blueprint to create similar contracts. This makes the creation and deployment of new contracts more efficient.
The approach is particularly useful for standardized contracts such as ERC-20 and ERC-721. Instead of writing a contract with specific functions or roles from scratch, developers can use an existing blueprint to create instances with the required functionality. For example, when creating a new token, they can use an ERC-20 or ERC-721 blueprint to deploy a contract with functions such as mint and transfer, using custom initialization logic or parameters supported by that blueprint.
Blueprint contracts can also simplify interactions between contracts. A standardized blueprint format enables compatible tooling and deployment contracts to interpret the stored code consistently, reducing the risk of unexpected behavior caused by format differences.
Motivation
One useful pattern for reducing the size of deploying contracts is to store initialization code (initcode) on-chain as a blueprint contract. A deployer can then use EXTCODECOPY to copy the initcode into memory before invoking CREATE or CREATE2.
However, this approach presents several problems.
External tools and indexers have difficulty determining whether a given contract is a regular runtime contract or a blueprint contract. Heuristically searching for patterns in bytecode to identify initcode raises maintenance and accuracy concerns.
Storing raw initcode on-chain also creates correctness and security concerns. The EVM does not have a native way to distinguish executable code from other types of code. Unless the initcode explicitly implements access control list (ACL) rules, anyone can call such a blueprint contract and directly execute the initcode as normal runtime code.
This is particularly problematic when the stored initcode has side effects, such as writing to storage or calling external contracts. Under the EVM semantics discussed in the proposal, executing the SELFDESTRUCT opcode in the stored initcode could delete the blueprint contract itself and disrupt downstream deployment contracts that rely on it.
A special preamble that prevents execution is therefore desirable.
A preamble (preamble) is a sequence of code or text placed at the beginning of a contract or document.
In programming and blockchain contexts, a preamble typically contains identifiers or sequences that encode information about the remaining code.
For blueprint contracts, the preamble indicates that the contract contains initcode rather than ordinary executable runtime code.
It prevents accidental execution of the contract and improves security. A specific pattern or sequence serves as a marker identifying the intended purpose and type of the contract.
Specification
Blueprint contracts must use the preamble 0xFE71<version bits><length encoding bits>.
The version occupies 6 bits, and the length encoding occupies 2 bits. The initial version is 0 (0b000000), with subsequent versions incremented by one.
The value 0b11 for the length encoding bits is reserved. When the length bits are 0b11, the third byte is treated as a continuation byte, meaning that more than one byte is required to encode the version. The exact encoding of multibyte versions is left to future ERCs.
The following examples illustrate the version bits and length encoding bits used in a blueprint contract's preamble.
-
Version bits
- Six bits in the preamble are allocated to the version number.
- The version starts at
0(0b000000) and increments by one. - This provides
64possible bit patterns, from version0to version63(0b111111). - For example, version
5is represented in binary as0b000101.
-
Length encoding bits
- The length encoding is allocated
2bits, allowing three ordinary values (0b00,0b01, and0b10), with a fourth value,0b11, reserved for a special purpose. - For example, a value of
0b01indicates that the next byte specifies the length of the data.
- The length encoding is allocated
-
Reserved value (
0b11)- When the length encoding bits are
0b11, they indicate a continuation byte. - More than one byte is required to encode the version number.
- This provides room for expansion if additional versions are needed in the future.
- The exact encoding of multibyte versions will be defined in a future ERC.
- When the length encoding bits are
Example
- Suppose we create a version 2 (
0b000010) blueprint contract. - The length encoding specifies one byte (
0b01). - In this case, the preamble begins as follows.
0xFE71 000010 01- This indicates version 2 and specifies that the following byte encodes the data length.
The version and length encoding identify the blueprint contract's version and data structure while providing room for future extensions.
A blueprint contract must contain at least one byte of initcode.
Blueprint contracts may include arbitrary bytes (data or code) between the version byte and the initcode. When variable-length data is included, the preamble must take the form 0xFE71<version bits><length encoding bits><length bytes><data>.
The length encoding bits represent a number from 0 to 2, inclusive, specifying how many bytes the length field occupies. The length field encodes the number of data bytes as a big-endian integer.
A blueprint contract's preamble follows a specific format so that tooling can correctly identify and use the contract.
Suppose we create a version 1 (0b000001) blueprint contract and want to insert 10 bytes of arbitrary data or code before the initcode. We choose 2 bytes (16 bits) to encode the data length.
-
Beginning of the preamble
- Every blueprint contract preamble begins with
0xFE71.
- Every blueprint contract preamble begins with
-
Version bits
- The contract uses version
1, so the version bits are0b000001.
- The contract uses version
-
Length encoding bits
- We choose
2bytes (16bits) to encode the length. - The value
2is encoded as0b10.
- We choose
-
Length bytes
- Since the data occupies
10bytes, we encode this length in big-endian form. - In binary,
10is0b0000000000001010. - As
2bytes, this becomes0x000A.
- Since the data occupies
-
Data
- The
10bytes of data follow. - For example, suppose the data is
0x1234567890ABCDEFFFED.
- The
The complete preamble is therefore as follows.
0xFE71 000001 10 000A 1234567890ABCDEFFFEDThis format allows a parser to identify the blueprint version, determine how much data precedes the initcode, and extract that data accurately.
Blueprint contracts can consequently accommodate initcode of different sizes and contents, along with optional data.
Big-endian encoding
Big-endian encoding places the most significant byte first when representing data as a sequence of bytes.
It is a common way to store multibyte data, such as numbers and addresses. Its counterpart, little-endian encoding, places the least significant byte first.
For example, consider encoding the number 0x12345678 in big-endian form.
Its individual hexadecimal bytes are:
0x12(most significant byte)0x340x560x78(least significant byte)
Big-endian encoding places the most significant byte first, yielding the following byte sequence:
0x12 0x34 0x56 0x78
Little-endian encoding places the least significant byte first, yielding:
0x78 0x56 0x34 0x12
Big-endian encoding is often intuitive for humans to read and write. It is also widely used for network communication, where it is known as network byte order.
Additional considerations
Blueprint contracts provide a mechanism for storing and reusing contract initialization code (initcode) on-chain.
This pattern can reduce gas and storage requirements in certain deployment architectures. Achieving those efficiencies requires several design decisions in the structure of the blueprint contract.
First, the blueprint contract preamble begins with 0xfe. This is the INVALID opcode, which causes execution to halt exceptionally if the contract is called directly. This ensures that the blueprint contract is not executed as an ordinary runtime contract.
Other contracts might also begin with 0xfe, so the magic byte 0x71 follows it to distinguish blueprint contracts. The value 0x71 is taken from the last byte of the keccak256 hash of the string blueprint and serves as an identifying marker in the preamble.
Magic bytes
A magic byte is a specific byte in a blueprint contract's preamble that helps identify the contract as a blueprint.
Such a byte is chosen to identify a particular type or format and distinguish it from unrelated data or ordinary contracts.
In this case, the magic byte 0x71 was chosen as the last byte of the keccak256 hash of the string blueprint.
keccak256 is a widely used cryptographic hash function that produces a fixed-length hash for arbitrary input. Hashing the string blueprint produces a hash whose final byte is 0x71.
For example, the following Python code demonstrates the operation.
import hashlib
# 'blueprint'文字列のkeccak256ハッシュ値を計算します。
hash_value = hashlib.sha3_256(b'blueprint').digest()
# ハッシュ値の最後のバイトを取得します。
magic_byte = hash_value[-1]
print(f"魔法のバイト: {magic_byte:02x}")The expected magic byte is 0x71. This value identifies the blueprint contract when used in its preamble. The original article uses a Python example to illustrate the derivation; Ethereum uses Keccak-256, which is distinct from standardized SHA3-256.
The likelihood of an unrelated contract or random data beginning with 0xFE71 by coincidence is low. This marker helps tooling reliably identify blueprint contracts.
Blueprint contracts require at least 1 byte of initcode; empty initcode is not allowed. This prevents the common mistake of accidentally providing empty initialization code.
If users want to include arbitrary data or code in the preamble, variable-length encoding is available. When the data length is less than 256 bytes, zero or one length bytes suffice. The third byte of the preamble reserves 2 bits to specify the length encoding.
Version bits accommodate possible future changes to the blueprint format. A continuation sequence is also reserved in case the available version bits are exhausted. The original proposal considers the compact two-byte identifying prefix sufficient for ordinary use and reserves the special continuation marker (0b11) for expansion.
Finally, the Ethereum Object Format (EOF), if introduced into the EVM in the future, could provide another way to specify blueprint contracts more explicitly. In the meantime, this ERC provides a standardized blueprint contract format that can support more efficient blockchain applications.
Ethereum Object Format (EOF)
Ethereum Object Format (EOF) is a proposed format intended to make Ethereum smart contracts and their execution environment safer, more efficient, and more transparent.
Under the EVM code format discussed in the original article, code is stored as a single sequence of bytes without explicit information about the contract's structure or contents. This complicates contract analysis and validation and can create security and efficiency concerns.
EOF aims to address these issues by distinguishing code from data and storing them in separate sections. Its proposed features include:
Sectioned format
Contract code, data, and other elements are divided into separate sections. This makes the structure of a contract clearer and facilitates analysis and validation.
Explicit versioning
EOF includes a version number, allowing different format versions and execution environments to be distinguished. This makes future upgrades and changes easier to manage.
Improved security
Separating code from data can reduce the risks associated with unintended code execution and the handling of data.
Efficient execution
A clearer contract structure allows the EVM to analyze and execute code more efficiently. Such improvements may also enable reductions in gas consumption.
EOF was proposed as part of future Ethereum upgrades and discussed through Ethereum Improvement Proposals (EIPs). Its anticipated benefits include improved smart contract security and execution efficiency.
Compatibility
There are no particular backward compatibility concerns identified by the proposal.
Tests
Blueprint contracts provide a mechanism for storing reusable initialization code (initcode) on Ethereum.
0xFE7100000xFE71is the magic header identifying the code as a blueprint contract.0x00indicates version0and that the length field occupies0bytes.- In other words, this contract has no data section.
- The final
0x00is theSTOPinstruction, which terminates execution of the initialization code.
0xFE710107FFFFFFFFFFFFFF000xFE71is again the magic header.0x01indicates version0and a length field of1byte.0x07indicates that the data section contains7bytes.- In this case, the data is
FFFFFFFFFFFFFF, or seven repetitions of0xFF.
- In this case, the data is
- The final
0x00is theSTOPinstruction. 0xFE71|01|07|FFFFFFFFFFFFFF|00
0xFE71020100FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00- Here too,
0xFE71is the magic header. 0x02indicates version0and a length field of2bytes.0100indicates that the data section contains256bytes.- The length is encoded in big-endian format, so
0100represents256.
- The length is encoded in big-endian format, so
- This is followed by
256bytes ofFF.- The data section consists of 256 repetitions of
0xFF.
- The data section consists of 256 repetitions of
- Finally, the
0x00STOPinstruction follows. 0xFE71|02|0100|FF...FF|00
These examples illustrate the basic structure of a blueprint contract. They begin with the magic header (0xFE71), followed by version and data length information, an optional data section, and, in these examples, a STOP instruction as the initialization code.
The data section can contain arbitrary data intended for specific purposes. This flexibility allows blueprint contracts to support a range of use cases.
Implementation
from typing import Optional, Tuple
def parse_blueprint_preamble(bytecode: bytes) -> Tuple[int, Optional[bytes], bytes]:
"""
Given bytecode as a sequence of bytes, parse the blueprint preamble and
deconstruct the bytecode into:
the ERC version, preamble data and initcode.
Raises an exception if the bytecode is not a valid blueprint contract
according to this ERC.
arguments:
bytecode: a `bytes` object representing the bytecode
returns:
(version,
None if <length encoding bits> is 0, otherwise the bytes of the data section,
the bytes of the initcode,
)
"""
if bytecode[:2] != b"\xFE\x71":
raise Exception("Not a blueprint!")
erc_version = (bytecode[2] & 0b11111100) >> 2
n_length_bytes = bytecode[2] & 0b11
if n_length_bytes == 0b11:
raise Exception("Reserved bits are set")
data_length = int.from_bytes(bytecode[3:3 + n_length_bytes], byteorder="big")
if n_length_bytes == 0:
preamble_data = None
else:
data_start = 3 + n_length_bytes
preamble_data = bytecode[data_start:data_start + data_length]
initcode = bytecode[3 + n_length_bytes + data_length:]
if len(initcode) == 0:
raise Exception("Empty initcode!")
return erc_version, preamble_data, initcodeThe Python function parse_blueprint_preamble parses the bytecode of a blueprint contract and returns its constituent parts: the ERC version, the preamble data, and the initcode (initialization code).
Here, bytecode is the binary representation of the blueprint contract.
-
Validating the bytecode
- First, the function checks whether the bytecode begins with
\xFE\x71. - This is the blueprint contract's magic header.
- If the header is absent, it raises an exception with the message Not a blueprint!
- First, the function checks whether the bytecode begins with
-
Parsing the ERC version
- The function extracts the ERC version from the
3rd byte of the bytecode. - The version is a
6-bit value stored in the upper6bits of the byte. - It is obtained by shifting the byte right by
2bits, discarding the lower2bits.
- The function extracts the ERC version from the
-
Parsing the length bits
- The function uses the lower
2bits of the3rd byte to obtain the number of bytes used to encode the data section length (n_length_bytes). - If this value is the reserved value
0b11, it raises an exception.
- The function uses the lower
-
Calculating the data section length
- The function reads the next
n_length_bytesbytes, interprets them as a big-endian integer, and calculates the data section length (data_length).
- The function reads the next
-
Extracting the preamble data
- If
n_length_bytesis0, there is no preamble data (None). - Otherwise, the function extracts
data_lengthbytes from the bytecode and stores them aspreamble_data.
- If
-
Extracting the initcode
- All bytes following the data section constitute the
initcode. - They are stored in the
initcodevariable. - If the
initcodeis empty (its length is0), the function raises an exception. - This is because blueprint contracts must contain at least
1byte ofinitcode.
- All bytes following the data section constitute the
Finally, the function returns this information as a tuple in the form (erc_version, preamble_data, initcode).
The caller can access the important components of the blueprint contract and process them further as needed.
This function provides a way to parse blueprint contract bytecode and validate its format against the ERC specification.
The following reference function takes the initcode required for a blueprint as a parameter and returns EVM code that deploys the corresponding blueprint contract without a data section.
def blueprint_deployer_bytecode(initcode: bytes) -> bytes:
blueprint_preamble = b"\xFE\x71\x00" # ERC5202 preamble
blueprint_bytecode = blueprint_preamble + initcode
# the length of the deployed code in bytes
len_bytes = len(blueprint_bytecode).to_bytes(2, "big")
# copy <blueprint_bytecode> to memory and `RETURN` it per EVM creation semantics
# PUSH2 <len> RETURNDATASIZE DUP2 PUSH1 10 RETURNDATASIZE CODECOPY RETURN
deploy_bytecode = b"\x61" + len_bytes + b"\x3d\x81\x60\x0a\x3d\x39\xf3"
return deploy_bytecode + blueprint_bytecodeSecurity
This ERC proposes the distinctive preamble 0xFE71 to identify blueprint contracts.
In theory, an existing on-chain contract could coincidentally have the same prefix. Its bytecode might begin with 0xFE71 even though it was not designed as a blueprint contract. However, such a collision is not considered a significant risk.
Indexers that identify blueprint contracts under this ERC can do more than inspect the bytecode prefix. Where source code is available, they can compile it and verify the preamble to determine whether the contract was intentionally designed as a blueprint. This verification helps distinguish accidental matches from intended blueprint contracts.
Furthermore, a survey of Ethereum mainnet as of July 8, 2022 found no contracts with bytecode beginning with 0xFE71. This indicated that the proposed preamble was unique at the time and that the likelihood of collisions with existing contracts was very low.
The proposal therefore considers the risks of adopting this preamble limited.
Citation
Charles Cooper (@charles-cooper), Edward Amor (@skellet0r), "ERC-5202: Blueprint contract format," Ethereum Improvement Proposals, no. 5202, June 2022. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-5202.
Final thoughts
This article covered ERC-5202, which defines a bytecode format for blueprint contracts that facilitate the replication and deployment of contracts.
If you have questions, feel free to send me a direct message on Twitter.
I also publish content on other platforms.



