How do I sign and verify messages with EIP-191 and EIP-712?
EIP-191 personal_sign hashes text behind an "Ethereum Signed Message" prefix; EIP-712 hashes typed structs bound to an app, chain and contract. Sign with signMessage or signTypedData; verify with ECDSA or ERC-1271.
EIP-191 and EIP-712 both define how to hash data before an Ethereum key signs it, so a signature for your app can never be mistaken for a transaction or reused somewhere else. EIP-191 personal_sign signs keccak256("\x19Ethereum Signed Message:\n" + length + message), which suits human-readable text such as a login message. EIP-712 signs typed structured data: keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message)), where the domain binds the signature to one app, chain and contract, and the wallet can show each field. Sign with signMessage or signTypedData (viem or ethers v6), verify off-chain by recovering the address, and verify on-chain with OpenZeppelin's ECDSA, EIP712 and SignatureChecker, which also handles smart-contract wallets through ERC-1271.
Why not just sign a hash?
An Ethereum signature is an ECDSA signature over a 32-byte digest. If an app asked the wallet to sign an arbitrary 32-byte value (the old eth_sign), that value could be the hash of a valid transaction, and the signature would let an attacker broadcast it. Wallets now warn heavily about eth_sign or disable it.
EIP-191 fixes this with a prefix byte. Every signed payload starts with 0x19, which can't begin a valid RLP-encoded legacy transaction, and the next byte says which format follows:
Version byte
Format
Used for
0x45 (E)
"\x19Ethereum Signed Message:\n" + len(message) + message
personal_sign is simple and readable, but it carries no structure. The contract verifying it has to parse text or trust that the bytes mean what the frontend said. That is the gap EIP-712 fills.
delegatecall runs another contract's code on your storage by slot number, so mismatched layouts overwrite data. Delegate only to trusted code, use ERC-1967 and ERC-7201 slots, check the target has code, and diff layouts.
EIP-712 defines a deterministic hash for a struct, plus a domain separator that scopes it.
Encode the type.Order(address maker,address token,uint256 amount,uint256 nonce,uint256 deadline). Nested struct types are appended in alphabetical order after the primary type.
Type hash.typeHash = keccak256(encodedType).
hashStruct.keccak256(abi.encode(typeHash, field1, field2, ...)), where atomic values are ABI-encoded to 32 bytes, string and bytes are replaced by their keccak256, arrays by the hash of their concatenated encoded elements, and nested structs by their own hashStruct.
Domain separator.hashStruct of an EIP712Domain with any of name, version, chainId, verifyingContract and salt.
The domain is what prevents replay across apps and chains. A permit signed for USDC on Ethereum mainnet has a different digest from the same permit on Base or for another token, because chainId and verifyingContract differ. ERC-2612 permit is the best-known EIP-712 message, and Permit2, order books, gasless meta-transactions and governance votes by signature all use the same scheme.
How do I sign messages in TypeScript?
With viem, the wallet client builds the payload and the public client verifies it:
viem's publicClient.verifyMessage and verifyTypedData call the chain, so they also accept signatures from smart-contract wallets (ERC-1271) and from smart accounts that are not yet deployed (ERC-6492). The standalone verifyMessage exported from viem only does ECDSA recovery.
With ethers v6, which the ethers.js v6 guide covers in more depth, the equivalents return the recovered address for you to compare:
import { ethers } from"ethers";
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!);
// domain, types and order as in the viem exampleconst sig = await wallet.signMessage("Sign in to example.com\nNonce: 7f3c9a21");
const signer = ethers.verifyMessage("Sign in to example.com\nNonce: 7f3c9a21", sig);
// Do not include EIP712Domain in `types`; ethers derives it from `domain`.const typedSig = await wallet.signTypedData(domain, types, order);
const typedSigner = ethers.verifyTypedData(domain, types, order, typedSig);
const digest = ethers.TypedDataEncoder.hash(domain, types, order); // the 32-byte digest a contract seesconsole.log(signer === wallet.address, typedSigner === wallet.address);
How do I verify a signature in Solidity?
OpenZeppelin's EIP712 base contract, the same one behind ERC20Permit in a secure OpenZeppelin ERC-20, builds and caches the domain separator (recomputing it if block.chainid changes after a fork), and _hashTypedDataV4 produces the final digest. Pair it with a nonce and a deadline:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {Nonces} from "@openzeppelin/contracts/utils/Nonces.sol";
contract ExampleOrders is EIP712, Nonces {
bytes32 private constant ORDER_TYPEHASH =
keccak256("Order(address maker,address token,uint256 amount,uint256 nonce,uint256 deadline)");
error Expired();
error InvalidSignature();
constructor() EIP712("Example Orders", "1") {}
function fill(address maker, address token, uint256 amount, uint256 deadline, bytes calldata signature)
external
{
if (block.timestamp > deadline) revert Expired();
bytes32 structHash =
keccak256(abi.encode(ORDER_TYPEHASH, maker, token, amount, _useNonce(maker), deadline));
bytes32 digest = _hashTypedDataV4(structHash);
// ECDSA for EOAs, ERC-1271 isValidSignature for contract wallets
if (!SignatureChecker.isValidSignatureNow(maker, digest, signature)) revert InvalidSignature();
// ... execute the order
}
}
_useNonce returns the current nonce and increments it, so each signature works once. For an EIP-191 message, hash with MessageHashUtils.toEthSignedMessageHash(bytes(message)) and recover with ECDSA.recover(digest, signature). OpenZeppelin's ECDSA rejects high-s (malleable) signatures and reverts on invalid ones instead of returning address(0) the way raw ecrecover does.
Smart accounts, ERC-1271 and EIP-7702
A contract wallet has no private key, so there is nothing to recover. Instead, ERC-1271 defines isValidSignature(bytes32 hash, bytes signature), which returns the magic value 0x1626ba7e if the account approves. SignatureChecker calls it whenever the signer has code. That covers multisigs and ERC-4337 smart accounts.
One newer edge case: an EOA delegated with EIP-7702 has code, so current OpenZeppelin SignatureChecker routes it to the ERC-1271 path. If the delegate contract doesn't implement isValidSignature correctly, a perfectly valid ECDSA signature from that EOA fails. Test with delegated accounts if your users might have them, and check how your verification library orders the two checks.
What usually goes wrong?
Signing the hex string instead of the bytes.signMessage("0xabc...") signs the 66-character text. To sign a 32-byte hash with personal_sign, pass bytes: ethers.getBytes(hash) or viem's { message: { raw: hash } }.
Type string mismatch. One different field name, order or type (uint vs uint256) between frontend and contract changes the type hash, and every signature fails with no clue why. Compare TypedDataEncoder.hash off-chain with your contract's digest in a test.
No nonce or deadline. Without them a signature can be replayed until the end of time.
Wrong domain. A hard-coded chainId, or a verifyingContract that points at a proxy's implementation instead of the proxy, breaks verification or weakens replay protection. Expose eip712Domain() (ERC-5267, built into OpenZeppelin's EIP712) so clients can read the real values.
Hand-rolled encoding. Using abi.encodePacked with dynamic types in a struct hash allows collisions. Follow the EIP-712 rules: hash strings and bytes, use abi.encode.
Treating a signature as authorisation for anything. Users sign what the wallet shows them. Keep messages specific and readable, because signature phishing relies on vague prompts, and the same risks as permit apply to any typed data that moves value.
In Foundry, vm.sign(privateKey, digest) returns (v, r, s); pack it as abi.encodePacked(r, s, v) to test your verifier with known keys, and use fuzz tests in Foundry to cover random amounts and expired deadlines.
Checklist
Use EIP-712 for anything a contract will act on; reserve personal_sign for human-readable messages such as logins.
Include a nonce and a deadline in every signed struct, and consume the nonce on use.
Bind the domain to the real chainId and the address users interact with (the proxy).
Verify with SignatureChecker (or viem's public client) so contract wallets and smart accounts work.
Use OpenZeppelin's ECDSA, never bare ecrecover.
Assert in tests that the off-chain digest equals the on-chain digest.
Test with an EOA, a multisig, an undeployed smart account and an EIP-7702 delegated account. The EIP-712 specification is the reference when encodings disagree.
Pair an execution client such as Geth with a consensus client such as Lighthouse, linked by the Engine API on port 8551 and a shared JWT secret. Use checkpoint sync, 4 TB of NVMe and open P2P ports, then confirm both are synced.
ERC-721 maps each token id to one owner, ideal for unique items. ERC-1155 tracks quantities per id with batch transfers and mandatory receiver hooks, suiting editions and game items. Pick by data model, not hype.