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 covers EIP-712, a standard for hashing and signing typed structured data.
The following explanation translates, summarizes, and expands on the original proposal.
I have also written about other ERC standards.
Overview
This standard defines how to process, hash, and sign data according to structured types. It aims to handle data securely by taking its type and structure into account, rather than treating it solely as a raw byte string. It has the following features.
- A theoretical framework for correct encoding functions
- It provides a theoretical foundation for ensuring that encoding functions are correct.
- A structured data specification similar to and compatible with Solidity structs
- It defines structured data similar to Solidity
structsand makes it possible to process that data securely.
- It defines structured data similar to Solidity
- A secure hashing algorithm
- It provides an algorithm for securely hashing instances of these structures.
- A mechanism for safely including instances in the set of signable messages
- Instances of these structures can safely be treated as signable messages.
- An extensible domain separation mechanism
- It includes extensions for distinguishing data across domains.
- A new RPC call,
eth_signTypedData- This RPC call can be used to sign structured data.
- An optimized implementation of the hashing algorithm for the EVM
- The hashing algorithm has an optimized implementation that runs efficiently in the EVM.
Reentrancy protection is not included, so the standard does not provide a mechanism for preventing repeated execution of operations between contracts.
Motivation
When signing data consisting only of byte strings, established techniques already address the problem. In practice, however, messages with complex semantics matter. Hashing structured data is not straightforward, and doing so incorrectly can undermine the security properties of a system.
This is where the principle of not rolling your own cryptography applies. Use audited, trustworthy, standardized techniques instead. This EIP aims to provide such a standard.
The EIP also aims to improve the usability of off-chain message signing for on-chain applications. Off-chain message signing is increasingly adopted because it saves gas and reduces the number of on-chain transactions. Signed messages have traditionally been displayed to users as opaque hexadecimal strings with little context about the structure of the message. This EIP aims to improve that experience.

The proposal introduces a way to encode data together with its structure, allowing users to inspect the data when signing.
The scheme helps users understand what data a message contains before signing it. Users can therefore more easily verify the data they intend to sign, improving security.

Specification
The set of signable messages is extended to include structured data (𝕊), in addition to transactions (𝕋) and byte strings (𝔹⁸ⁿ).
The resulting set is 𝕋 ∪ 𝔹⁸ⁿ ∪ 𝕊.
𝕋 ∪ 𝔹⁸ⁿ ∪ 𝕊
Transactions (𝕋) These represent transactions involving contracts on the blockchain. For example, a user might submit a transaction requesting a token transfer through a particular contract. Transactions are RLP-encoded and represented as byte strings.
Byte strings (𝔹⁸ⁿ)
A byte string is a sequence of binary data, which may be represented as a hexadecimal string.
It is a simple form of data commonly associated with operations such as signing.
An example is the hexadecimal string 0xabcdef123456.
Structured data (𝕊) Structured data includes both the data and its structure. It can contain more complex data than a transaction or a byte string. For example, it can represent configuration settings or a set of rules for a particular contract. The data is encoded in a specified way and used for signing.
For example, when a user signs a transaction (𝕋) to transfer a particular ERC-20 token, the transaction may include detailed information represented as structured data (𝕊). Messages in this set cover transactions, byte strings, and structured data, each of which may be encoded differently for signing.
These messages are encoded as byte strings suitable for hashing and signing. The encoding rules are as follows.
Transactions
encode(transaction : 𝕋) = RLP_encode(transaction). The transaction is RLP-encoded.
Byte strings
encode(message : 𝔹⁸ⁿ) = "\x19Ethereum Signed Message:\n" ‖ len(message) ‖ message
The byte string encoding contains \x19Ethereum Signed Message:\n and data representing the length of the byte string.
Domain separator and message
encode(domainSeparator : 𝔹²⁵⁶, message : 𝕊) = "\x19\x01" ‖ domainSeparator ‖ hashStruct(message)
The domain separator and message are encoded in a specified manner, and their hashes are combined.
The encoding is deterministic in each case.
It is also injective.
The three cases are distinguished by their prefixes (RLP_encode(transaction) does not begin with \x19).
Deterministic
Deterministic means that following a particular rule always produces the same result.
For example, adding 2 and 2 always gives 4.
Similarly, a given piece of data (a transaction, byte string, or structured data) is always encoded in the same way.
Injective Injective means that distinct inputs are not mapped to the same output. For example, even if you order two of the same dish, you receive two separate dishes. Similarly, distinct inputs (transactions, byte strings, or structured data) have distinct encodings rather than mapping to the same output.
Distinguished by the initial bytes
The encoding relies on differences in the initial bytes of the encoded data.
For example, the original article states that the transaction encoding begins with \x19, while the byte string encoding begins with \x19Ethereum Signed Message:\n.
The different prefixes allow the encodings of distinct message categories to be distinguished.
The encoding consistently transforms data, maps distinct inputs to distinct encodings, and distinguishes message categories by their prefixes.
The encoding conforms to EIP-191.
The version byte is fixed at 0x01, the version-specific data is the 32-byte domain separator domainSeparator, and the data to sign is the 32-byte hashStruct(message).
Structured data 𝕊
To define the set of structured data, we first define the supported types. These types are closely related to ABI v2, and Solidity notation is used to describe their definitions. Although the standard is specific to the Ethereum Virtual Machine (EVM), it is designed to apply to high-level programming languages as well. Consider the following example.
struct Mail {
address from;
address to;
string contents;
}- Definition of a struct type
- A structure (
struct) is a named type containing zero or more member variables. - Each member variable has a member type and a name.
- A structure (
A member type is the data type of an individual element or field in structured data. Structured data generally consists of multiple members (fields) of different types. A member type indicates what information the data represents.
Consider the following struct.
struct Person {
string name;
uint age;
}Here, name has a string (string) member type, while age has an unsigned integer (uint) member type.
In other words, name represents text, and age represents integer data.
Member types define the kind of data each element can store and how that data is handled.
- Member types
- A member type is either atomic, dynamic, or a reference type.
- Atomic types
- Atomic types are basic types, such as integers, strings, booleans, and addresses.
- They resemble Solidity types and include integer widths and address formats.
- Dynamic types
- The special types
bytesandstringrepresent variable-length data. - Their types are specified in a similar manner to atomic types, but their encoding differs.
- The special types
- Reference types
- Reference types include arrays (
arrays) and structs (structs). - Arrays may be fixed-length or variable-length and are expressed by their type and element count.
- Structs can reference other structs, and recursive struct types are supported.
- Reference types include arrays (
- Structured data 𝕊
- The set of structured data 𝕊 contains every instance of a struct type.
- In other words, it includes actual instances of the data defined by structs.
These definitions describe the basic types and rules for handling structured data, including structs, atomic types, dynamic types, and reference types. Instances of these types form the set of structured data 𝕊.
Definition of hashStruct
The hashStruct function hashes structured data (𝕊).
It concatenates typeHash and encodeData(s) and applies the keccak256 hash function to the result.
The typeHash is constant for a particular struct type and does not need to be computed at runtime.
Definition of encodeType
A struct type is encoded as a string representing its name and its members (fields).
Each member is expressed as a combination of type and name.
For example, the Mail struct is encoded as Mail(address from,address to,string contents).
If the struct type references other struct types, including transitive references, the referenced types are sorted by name and appended to the encoding.
Definition of encodeData
The encoding of a struct instance is the concatenation of the encoded values of its members. Member values are represented as 32-byte strings in the order specified by the type.
Atomic values are encoded according to specified rules.
For example, booleans are encoded as uint256 values of 0 or 1, and addresses are encoded as uint160.
Integer values are sign-extended to 256 bits and encoded in big-endian order.
Values from bytes1 to bytes31 are treated as arrays, in order from index 0 to length - 1, and zero-padded to bytes32.
This corresponds to the ABI v1 and v2 encodings.
Dynamic values of type bytes and string are encoded as the keccak256 hash of their contents.
Array values are encoded as the keccak256 hash of the concatenated encodeData of their contents.
That is, encoding SomeType[5] is equivalent to encoding a struct containing five members of SomeType.
Struct values are encoded recursively as hashStruct(value).
The behavior is undefined for circular references.
These definitions make it possible to encode and hash structured data (𝕊).
Definition of domainSeparator
domainSeparator = hashStruct(eip712Domain)- The
domainSeparatoris the hash of a struct called EIP712Domain. - The struct type
EIP712Domainmay contain any of the following fields.- Protocol designers include the fields appropriate to their signing domain.
- Unused fields are omitted from the struct type.
string name- The human-readable name of the signing domain, such as the name of a DApp or protocol.
string version- The current major version of the signing domain.
- Signatures from different versions are incompatible; the user agent should refuse to sign if the chain does not match the currently active chain.
uint256 chainId- The EIP-155 chain ID. The user agent should refuse signing if this does not match the currently active chain.
address verifyingContract- The address of the contract that verifies the signature.
- The user agent may implement contract-specific phishing prevention.
bytes32 salt- A salt used to distinguish protocols.
- It can be used as a last-resort domain separator.
Future extensions to this standard may add new fields and corresponding constraints on user-agent behavior.
A user agent may use the supplied information to inform or warn the user, or refuse to sign.
DApp implementers should not add private fields.
New fields must be proposed through the EIP process.
The fields of EIP712Domain appear in the order listed above, with absent fields skipped.
Future fields are appended after these fields in alphabetical order.
User agents should accept fields in the order specified by the EIPT712Domain type.
This ensures that the domain separator uniquely identifies the signing domain and is used to verify signatures.
eth_signTypedData JSON-RPC specification
The eth_signTypedData method is an addition to Ethereum's JSON-RPC, providing functionality similar to eth_sign.
Specification of eth_signTypedData
This method computes a particular Ethereum signature. Specifically, it computes the following signature.
sign(keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message))).
Here, domainSeparator and message are defined as above.
Note
The signing account must be unlocked.
Parameters
Address- 20 bytes.
- The address of the account signing the message.
TypedData(typed structured data)- The structured data to be signed.
TypedData is a JSON object containing type information, domain separator parameters, and the message object.
The following is the JSON schema definition for the TypedData parameter.
Explain
{
type: 'object',
properties: {
types: {
type: 'object',
properties: {
EIP712Domain: {type: 'array'},
},
additionalProperties: {
type: 'array',
items: {
type: 'object',
properties: {
name: {type: 'string'},
type: {type: 'string'}
},
required: ['name', 'type']
}
},
required: ['EIP712Domain']
},
primaryType: {type: 'string'},
domain: {type: 'object'},
message: {type: 'object'}
},
required: ['types', 'primaryType', 'domain', 'message']
}This method lets a specified account generate a signature for the supplied structured data.
Return value
DATA
A signature (Signature).
Like eth_sign, it is a 129-byte array represented in hexadecimal with a 0x prefix, as described in the original explanation.
This array encodes the r, s, and v parameters defined in Appendix F of the Yellow Paper in big-endian format.
The original description assigns bytes 0 through 64 to r, bytes 64 through 128 to s, and the final byte to v.
The v parameter also includes the chain ID specified by EIP-155, according to the original description.
Example
Request
curl -X POST --data '{"jsonrpc":"2.0","method":"eth_signTypedData","params":["0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", {"types":{"EIP712Domain":[{"name":"name","type":"string"},{"name":"version","type":"string"},{"name":"chainId","type":"uint256"},{"name":"verifyingContract","type":"address"}],"Person":[{"name":"name","type":"string"},{"name":"wallet","type":"address"}],"Mail":[{"name":"from","type":"Person"},{"name":"to","type":"Person"},{"name":"contents","type":"string"}]},"primaryType":"Mail","domain":{"name":"Ether Mail","version":"1","chainId":1,"verifyingContract":"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"},"message":{"from":{"name":"Cow","wallet":"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"},"to":{"name":"Bob","wallet":"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"},"contents":"Hello, Bob!"}}],"id":1}'Result
{
"id":1,
"jsonrpc": "2.0",
"result": "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c"
}In the example above, the specified account (address 0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826) signs the supplied structured data.
The resulting signature is returned in hexadecimal format.
personal_signTypedData
The following steps explain how to use Solidity's ecrecover to verify a signature computed by eth_signTypedData.
A concrete example appears in the Example.js file, using contracts deployed to the Ropsten and Rinkeby test networks.
Steps:
- The user obtains signed data with
eth_signTypedData.- Typically this is a signature over a message or typed data supplied by the user.
- Send the user-supplied data and signature to a Solidity smart contract.
- The smart contract verifies the signature.
- Use the
ecrecoverfunction in the smart contract to recover the public key information from the signature.- The original explanation describes recovery using the signature (
r,s,v), the message hash, and the signing address.
- The original explanation describes recovery using the signature (
- Use the recovered information in the smart contract to establish that the message is authentic.
- Specifically, recompute the message hash and verify the signer's address using the signature and the recovered information.
- If the message hash is authentic and the signer's address matches the signature, the signature is considered valid.
- This establishes the authenticity of the data signed with
eth_signTypedData.
- This establishes the authenticity of the data signed with
This process verifies data signed with eth_signTypedData within the smart contract, establishing its authenticity.
Web3 API specification
This section describes the Web3 API introduced in Web3.js version 1.
web3.eth.signTypedData
web3.eth.signTypedData(typedData, address [, callback])- The
web3.eth.signTypedDatamethod signs typed data using a specified account. - The account must be unlocked.
Parameters
Object(object)- The domain separator and typed data to sign.
- It is structured according to the JSON schema specified in the eth_signTypedData JSON-RPC call.
StringorNumber(string or number)- The address used to sign the data.
- Alternatively, an address or index of a local wallet in web3.eth.accounts.wallet.
Function(optional)- An optional callback function.
- It returns an error object as the first parameter and the result as the second.
Return value
- A Promise resolving to a
Stringis returned. - This is the signature returned by
eth_signTypedData.
Example
web3.eth.signTypedData(typedData, "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826")
.then(console.log);
> "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c"web3.eth.personal.signTypedData
- The
web3.eth.personal.signTypedDatamethod works similarly toweb3.eth.signTypedDatabut accepts an additional password parameter. - It is analogous to
web3.eth.personal.sign.
These methods allow a specified account to sign typed data and retrieve the resulting signature.
Additional notes
Extending the encoding function
- New cases were added to the encoding function to support new data types.
- The initial bytes of the encoding distinguish these cases.
- It is therefore not safe to use the domain separator or
typeHashdirectly. - A
typeHashcould inadvertently be constructed as the prefix of an encoded transaction.
Role of the domain separator
- The domain separator prevents collisions between otherwise identical structures.
- Even if two DApps propose the same structure but are incompatible, introducing a domain separator avoids signature collisions.
Supporting different signature use cases
- A domain separator allows different signature use cases within the same structure.
- For example, if signatures from both
fromandtoare required, different domain separators can distinguish those signatures.
Alternative 1: Use the target contract address as the domain separator
- This alternative uses the target contract address as the domain separator to prevent collisions between contracts using the same type.
- However, it is not suitable for supporting multiple different signature use cases.
- The standard suggests that implementers use the target contract address where appropriate.
Role of hashStruct
- The
hashStructfunction starts withtypeHashto distinguish different data types. - By assigning different prefixes to different data types,
encodeDataonly needs to be injective within a particular data type. - In other words,
encodeData(a)may equalencodeData(b)only when the types ofaandbdiffer (typeOf(a)is nottypeOf(b)).
typeHash
The typeHash is designed to become a compile-time constant in Solidity.
For example, it can be defined as follows.
bytes32 constant MAIL_TYPEHASH = keccak256(
"Mail(address from,address to,string contents)");Several alternatives to typeHash were considered but rejected for specific reasons.
Alternative 2: Use the ABI v2 function signature
bytes4has insufficient collision resistance.- Unlike function signatures, using a longer hash incurs almost no runtime cost.
Alternative 3: Use a 256-bit ABI v2 function signature
- This includes type information but not semantics beyond the function.
- In practice, it can cause collisions such as
transfer(address,uint256)in EIP-20 andtransfer(address,uint256)in EIP-721. - In the former,
uint256refers to an amount; in the latter, it refers to a unique ID. - In general, ABI v2 favors compatibility, while the hashing standard does not.
Alternative 4: Add parameter and struct names to the 256-bit ABI v2 signature
- This is longer than the proposed solution.
- The string length may also grow exponentially relative to the input length.
- It does not allow recursive
structtypes.
Alternative 5: Include NatSpec documentation
- This includes more semantic information in the schema hash, reducing the possibility of collisions further.
- However, extending or correcting documentation becomes a breaking change, contrary to the usual expectation.
- It also makes the schema hashing mechanism very verbose.
After considering these alternatives, typeHash was selected.
It serves as a type identifier and can be used securely and efficiently as a compile-time constant in Solidity.
Additional notes on encodeData
The encodeData function is designed to make hashStruct straightforward to implement in Solidity.
The reasons are as follows.
Implementing hashStruct
First, encodeData is used to implement hashStruct in Solidity.
The hashStruct function computes a hash from the in-memory data of a Mail struct.
The code is as follows.
function hashStruct(Mail memory mail) pure returns (bytes32 hash) {
return keccak256(abi.encode(
MAIL_TYPEHASH,
mail.from,
mail.to,
keccak256(mail.contents)
));
}This code uses encodeData to encode MAIL_TYPEHASH and the in-memory data, then hashes the result with keccak256.
This produces a unique hash from the contents of the struct.
Efficient implementation in the EVM
The encodeData function also allows efficient in-place implementations in the EVM.
The following code implements hashStruct using assembly.
It allows the hash to be computed without altering the in-memory data.
function hashStruct(Mail memory mail) pure returns (bytes32 hash) {
// Compute sub-hashes
bytes32 typeHash = MAIL_TYPEHASH;
bytes32 contentsHash = keccak256(mail.contents);
assembly {
// Back up select memory
let temp1 := mload(sub(mail, 32))
let temp2 := mload(add(mail, 128))
// Write typeHash and sub-hashes
mstore(sub(mail, 32), typeHash)
mstore(add(mail, 64), contentsHash)
// Compute hash
hash := keccak256(sub(mail, 32), 128)
// Restore memory
mstore(sub(mail, 32), temp1)
mstore(add(mail, 64), temp2)
}
}This implementation makes specific assumptions about the memory layout: in particular, data is not placed at addresses below 32, members are stored in order, and all values are aligned to 32-byte boundaries.
It also assumes that dynamic and reference types are stored as 32-byte pointers.
Alternative 6: Tight packing
This alternative uses tight packing, described as the default behavior when calling keccak256 with multiple arguments.
It minimizes the number of bytes to hash but requires complex packing instructions in the EVM and does not allow in-place computation.
Tight packing saves bytes but complicates processing within the EVM.
Alternative 7: ABI v2 encoding
In particular, the anticipated combination with abi.encode makes it easy to use abi.encode as the encodeData function.
However, ABI v2 itself does not meet the deterministic security requirement because multiple valid ABI v2 encodings can exist for the same data.
ABI v2 does not allow in-place computation.
In-place computation In-place computation is a technique in which a computer program or algorithm performs calculations within existing memory without using additional memory regions. The data structures and variables used for computation are updated in their existing memory locations, so processing does not require allocation of new memory regions.
In-place computation is used to minimize memory usage and improve execution efficiency. It is particularly useful for large datasets and memory-constrained environments. However, it requires careful management because memory contents may be corrupted or computation results may be unexpected.
It is also used for many algorithms and data operations, including sorting, list operations, and matrix operations. Examples include in-place sorting (quicksort and heapsort), in-place list reversal, and in-place matrix transformations.
Alternative 8: Omit typeHash from hashStruct and combine it with the domain separator instead
This alternative omits typeHash from hashStruct and combines it with the domain separator instead.
This improves efficiency but makes the semantics of Solidity's keccak256 hashing function non-injective.
In other words, different hashes could be generated for the same data, as described in the original explanation.
Alternative 9: Support circular data structures
The current standard is optimized for tree-shaped data and leaves circular data structures undefined. Supporting circular data requires maintaining a stack containing the path to the current node and substituting a stack offset when a cycle is detected. This is complex and difficult to implement, and breaks composability when constructing a struct hash from hashes of member values because it depends on the hashing path. It is possible to extend the standard compatibly to define hashing for circular data.
Optimization for acyclic graphs
A naive implementation for acyclic graphs is not optimal. Recursively visiting members may visit the same node twice. Memoization can optimize this process.
These alternatives offer different approaches to hash computation in Solidity, each with particular limitations and challenges. The alternatives must be considered when choosing an appropriate approach.
Additional notes on the domain separator (domainSeparator)
A flexible approach is used because different domains may require different security requirements and verification methods. This allows each DApp (decentralized application) to customize the mechanism according to its security needs.
A DApp defines the EIP712Domain struct type and a concrete instance (eip712Domain) and provides them to the user agent.
Based on the fields in the received EIP712Domain, the user agent can apply different verification techniques and security measures.
The benefit is that DApps with different security requirements can still use the EIP-712 scheme.
Each DApp can define its own EIP712Domain and include the necessary security information and configuration.
Based on the received EIP712Domain, the user agent can perform verification appropriate to the particular DApp.
This flexibility helps meet different security needs across domains and lets each DApp strengthen security according to its requirements. Customized security measures can improve overall system security while retaining the same EIP-712 scheme.
Backward compatibility
At the time of the proposal, the RPC call, Web3 methods, and SomeStruct.typeHash parameter had not yet been concretely defined.
Defining them should not affect the behavior of existing decentralized applications (DApps).
The Solidity expression keccak256(someInstance) was also valid syntax for an instance someInstance of type SomeStruct.
At the time, this expression evaluated to the keccak256 hash of the memory address of someInstance.
However, this behavior should be considered potentially unsafe.
It may appear to work correctly in some situations but can cause determinism or injectivity problems in others.
DApps relying on this behavior should be aware of the risks.
These undefined elements and the new behavior in Solidity should be specified without affecting existing DApps. DApps relying on the unsafe behavior are also warned that corrections are necessary.
Tests
A sample contract is available in Example.sol, and a JavaScript signing implementation is available in Example.js.
https://eips.ethereum.org/assets/eip-712/Example.sol
https://eips.ethereum.org/assets/eip-712/Example.js
Security considerations
Replay attacks
This standard concerns message signing and signature verification. In actual applications, signed messages are used to authorize actions. Token transfers are one example. Implementers must ensure that their applications behave appropriately if the same signed message is submitted twice. The specific measures vary by application and are outside the scope of the standard. Possible measures include rejecting repeated messages or making the authorized action idempotent.
Frontrunning attacks
The mechanism for broadcasting signatures to the blockchain varies by application and is outside the scope of this standard. When a signature is used in a contract, the application must implement measures to protect against frontrunning. In this attack, an attacker intercepts a signature and submits it to the contract before its intended use. The application should behave correctly if an attacker submits the signature first. This can be achieved by rejecting the attack or reproducing the effect intended by the signer.
These security considerations are outside the scope of the standard for signing and verifying messages and indicate the need for application-specific security measures.
References
Remco Bloemen (@Recmo), Leonid Logvinov (@LogvinovLeon), Jacob Evans (@dekz), "EIP-712: Typed structured data hashing and signing," Ethereum Improvement Proposals, no. 712, September 2017. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-712.
Conclusion
This article covered ERC-712, the standard proposing a mechanism for hashing and signing typed structured data. I hope the explanation was helpful.
If you have questions, feel free to contact me via Twitter DM.
I also publish content on the following platforms.


