
Summary: Interacting with smart contracts traditionally required on-chain transactions for every administrative approval. The evolution from raw ECDSA hashing (
eth_sign) to structured EIP-712 domain hashing, and ultimately to ERC20Permit (EIP-2612), introduces gasless user approvals where signers produce off-chain cryptographic signatures verified in a single transaction on-chain. This guide details signature verification mechanics, analyzes replay prevention through chain IDs, contract addresses, and account nonces, and walks through a Foundry test suite implementing EIP-2612 permits.
1. The Three Tiers of Off-Chain Signatures
Gas economy of permits: replacing sequential on-chain approve transactions with off-chain signatures bundled directly into execution calls.
Smart contract authentication off-chain has evolved across three standards:
1. Raw ECDSA (eth_sign):
User signs a 32-byte hex hash.
* Blind signing: the user cannot see what they are approving in their wallet.
* High phishing and replay risk.
2. Structured Data (EIP-712):
User signs a structured schema containing named fields.
* Readable wallet prompt: displays token, recipient, amount, deadline.
* Domain separator prevents cross-chain and cross-contract replays.
3. Application Standard (EIP-2612 ERC20Permit):
Standardized EIP-712 struct applied directly to ERC20 token approvals.
* Replaces the separate approve() transaction with permit().
* Combines approval and business execution (transferFrom/deposit) into a single transaction.
2. Low-Level Verification: ECDSA and ecrecover
An Ethereum signature consists of three parameters derived from an elliptic curve (secp256k1) operation: (v, r, s).
From the open-source repository imminer668/Solidity-Guide (foundry_projects/08_offchain_auth/35_Signature/src/raw/SignatureNFT.sol):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract SignatureVerifier {
// Computes Ethereum Signed Message hash: \x19Ethereum Signed Message:\n32 ++ hash
function getMessageHash(address to, uint256 amount) public pure returns (bytes32) {
return keccak256(abi.encodePacked(to, amount));
}
function getEthSignedMessageHash(bytes32 _messageHash) public pure returns (bytes32) {
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)
);
}
// Native ecrecover call
function recoverSigner(bytes32 _ethSignedMessageHash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
address signer = ecrecover(_ethSignedMessageHash, v, r, s);
require(signer != address(0), "Invalid signature");
return signer;
}
}
2.1 The ecrecover Zero-Address Gotcha
If (v, r, s) are invalid or malformed, the EVM ecrecover precompile does not revert; it returns address(0).
If a contract checks:
// Vulnerable if owner variable is uninitialized (address(0))
require(ecrecover(hash, v, r, s) == owner, "Unauthorized");
An attacker passing all zeroes will match an uninitialized owner = address(0). Always explicitly assert require(signer != address(0)) or use OpenZeppelin’s ECDSA.recover().
3. EIP-712: Structured Data and Domain Separation
EIP-712 provides domain isolation and prevents cross-protocol signature replaying.
From foundry_projects/08_offchain_auth/36_EIP712/src/raw/EIP712Storage.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract EIP712Demo {
bytes32 public immutable DOMAIN_SEPARATOR;
bytes32 public constant DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 public constant PERMIT_TYPEHASH = keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
constructor(string memory name, string memory version) {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(version)),
block.chainid, // Bound to current chain ID
address(this) // Bound to current contract deployment
)
);
}
function hashStruct(address owner, address spender, uint256 value, uint256 nonce, uint256 deadline)
public
pure
returns (bytes32)
{
return keccak256(
abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonce, deadline)
);
}
function toTypedDataHash(bytes32 structHash) public view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
}
}
By including block.chainid and address(this), a signature signed for this contract on Ethereum mainnet cannot be replayed on Polygon or against a clone contract on the same chain.
4. ERC20Permit (EIP-2612): Gasless Approvals
EIP-2612 standardizes EIP-712 for ERC20 allowances, allowing a spender to submit an owner’s signature directly to the permit() function.
From foundry_projects/08_offchain_auth/37_ERC20Permit/src/raw/ERC20Permit.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract ERC20Permit {
mapping(address => uint256) public nonces;
mapping(address => mapping(address => uint256)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
// 1. Validate deadline
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
// 2. Hash payload according to EIP-712
bytes32 structHash = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner],
deadline
)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash)
);
// 3. Recover signer
address signer = ecrecover(digest, v, r, s);
require(signer != address(0) && signer == owner, "ERC20Permit: invalid signature");
// 4. Increment nonce to prevent replay
nonces[owner]++;
// 5. Update allowance
allowance[owner][spender] = value;
}
}Traditional 2-Tx Flow:
1. User broadcasts approve(router, 100) -> Pays gas, waits for block
2. User broadcasts deposit(100) -> Pays gas, waits for block
ERC20Permit 1-Tx Flow:
1. User signs EIP-712 permit payload off-chain (0 Gas)
2. Relayer or Router submits permit() + deposit() in a single on-chain transaction
5. Testing Permits with Foundry Cheatcodes
Foundry provides vm.sign(privateKey, digest) to sign typed data directly inside Solidity tests.
From foundry_projects/08_offchain_auth/37_ERC20Permit/test/raw/ERC20Permit.t.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {Test} from "forge-std/Test.sol";
import {ERC20Permit} from "../../src/raw/ERC20Permit.sol";
contract ERC20PermitTest is Test {
ERC20Permit public token;
uint256 internal ownerPrivateKey = 0xA11CE;
address internal owner;
address internal spender = address(0x2);
function setUp() public {
token = new ERC20Permit();
owner = vm.addr(ownerPrivateKey);
}
function testPermitFlow() public {
uint256 value = 1000 ether;
uint256 nonce = token.nonces(owner);
uint256 deadline = block.timestamp + 1 hours;
// Construct EIP-712 digest
bytes32 structHash = keccak256(
abi.encode(
token.PERMIT_TYPEHASH(),
owner,
spender,
value,
nonce,
deadline
)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", token.DOMAIN_SEPARATOR(), structHash)
);
// Sign off-chain using owner's private key
(uint8 v, bytes32 r, bytes32 s) = vm.sign(ownerPrivateKey, digest);
// Submit on-chain via spender
vm.prank(spender);
token.permit(owner, spender, value, deadline, v, r, s);
assertEq(token.allowance(owner, spender), value);
assertEq(token.nonces(owner), nonce + 1);
}
}
Run tests with forge test -vv.
6. Signature Security Checklist
- Check for
address(0)onecrecover: Never allow a recovered zero address to match uninitialized state variables. - Include Chain ID and Contract Address: Always bind the
DOMAIN_SEPARATORtoblock.chainidandaddress(this). - Strict Nonce Tracking: Increment nonces monotonically (
nonces[owner]++) upon successful execution to invalidate replayed signatures. - Enforce Reasonable Deadlines: Do not accept
deadline = type(uint256).maxin user-facing applications. Use bounded windows (e.g. 15 to 30 minutes). - Verify S-Value Upper Bound: Reject signatures where
s > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0to prevent transaction malleability attacks.
7. Production Systems Context
In production Web3 products: – Agent Wallet Guard (中文版): Uses EIP-712 envelopes to validate AI agent transaction intents off-chain. Operators can revoke session authorizations instantly on-chain, causing any pending or in-flight signed UserOperations to revert (see Testing Agent Wallet Revocation with Signed Operations). – Passage Bridge (中文版): Binds cross-chain release messages to explicit execution contexts (sourceChain, destChain, nonce), preventing relayer replay attacks across different testnets or mainnet environments (see Binding Cross-Chain Messages to Their Execution Context).
Review full systems on the Fone Products Center (中文版) or read technical notes on Fone Insights.
Off-Chain Signature Standards Comparison Matrix
| Signature Standard | Specification | Wallet UI Display | Built-in Replay Defense | Primary Production Use Case |
|---|---|---|---|---|
EIP-191 (personal_sign) |
\x19Ethereum Signed Message: + length + raw bytes |
Opaque hex string or raw UTF-8 text | None (Developer must embed custom nonce/chainId) | Simple off-chain login challenges (SIWE) and basic whitelists |
| EIP-712 Typed Data | \x19\x01 + domainSeparator + hashStruct(message) |
Structured JSON fields (amount, recipient, deadline) |
chainId + verifyingContract bound in Domain |
Orderbook DEX intents, AI session key envelopes, DAO votes |
EIP-2612 (ERC20Permit) |
Standardized EIP-712 Permit(owner,spender,value,nonce,deadline) |
Native token allowance approval card | Sequential per-address nonces(owner) + deadline |
Single-transaction gasless token checkout and vault deposits |
Verify It Locally with Foundry
Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/08_offchain_auth/37_ERC20Permit):
# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide
# 2. Run the verified Foundry test suite for this module
cd foundry_projects/08_offchain_auth/37_ERC20Permit && forge test -vvv
Expected local verification output:
[PASS] test_PermitAndTransferFromInSingleTx() (gas: 72450)
[PASS] test_RevertWhen_PermitExpired() (gas: 21340)
Suite result: ok. 2 passed; 0 failed; 0 skipped
Frequently Asked Questions (Technical FAQ)
Why does EIP-712 prefix every digest with 0x1901?
Defined in EIP-191, the initial 0x19 byte guarantees that the signed payload can never be a valid RLP-encoded Ethereum transaction (preventing transaction-signing confusion), and 0x01 designates version 1 structured typed data (domainSeparator || hashStruct).
How does ERC20Permit eliminate the two-transaction approve + transferFrom UX bottleneck?
Instead of the user broadcasting an on-chain approve() transaction first, the user signs an off-chain EIP-712 Permit struct for free. The dApp or relayer passes (v, r, s) into a single transaction that calls token.permit(...) followed immediately by token.transferFrom(...).
What happens if ecrecover is called with an invalid v value (neither 27 nor 28)?
The ecrecover precompile silently returns address(0) rather than reverting. Always validate recovered != address(0) and restrict v to {27, 28} and s to the lower half of the secp256k1 curve order.
Series & Related Engineering Guides
- Previous Lesson (S09): NFT Asset Modeling in Solidity: ERC721 vs. ERC1155 Raw & OpenZeppelin Implementations
- Next Lesson (S11): Web3 Growth & Batching in Solidity: Cooldown Faucets, Merkle Tree Airdrops, and Atomic MultiCall
- Companion Security & Architecture Deep-Dive (T05): 6 Hidden Vulnerabilities in EIP-712 and ecrecover: Zero-Address Bypass, Cross-Chain Replay, and Malleability
- Production Engineering Case Study: Testing Agent Wallet Revocation with Signed Operations
- Open-Source Codebase: imminer668/Solidity-Guide (
foundry_projects/08_offchain_auth/37_ERC20Permit) - Commercial Platforms & Advisory: Fone Products Center (中文版) | Fone Services | Contact Engineering