Crypto Training

Signatures in Solidity: EIP-712, Replay Attacks, and Permit Front-Run DoS

What an EIP-712 digest binds and what it leaves open: missing nonce, chain and contract fields, the permit front-run DoS, tokens whose permit call does nothing, ERC-1271 replay across smart accounts, and what Permit2 changes.

Crypto Training•2026-01-20•12 min read

EIP-712 domain separation illustration

A signature lets a user authorize an action without sending the transaction, since they sign a message off-chain and someone else submits it. permit, meta-transactions, off-chain orders and multisig approvals all work this way. The cryptographic check behind them is a single ecrecover call, described in ECDSA in Plain English, and it is rarely where things go wrong.

The losses come from two other places. One is the message, which may fail to pin down the chain, the contract, the action or the number of times it can be used. The other is the integrating contract, which often assumes that the call consuming the signature will behave in a way the standard never promised. This post goes through both, with the incident or audit finding behind each rule.

What an EIP-712 digest contains#

EIP-712 defines the value that gets signed as follows.

TEXT
digest      = keccak256("\x19\x01" || domainSeparator || hashStruct(message))
hashStruct  = keccak256(typeHash || encodeData(message))
typeHash    = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")

The type string is part of the hash, so a signature over one struct type cannot be reinterpreted as another. For the Permit type above the typehash is 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9, which you can reproduce with cast keccak.

The domain separator is the hashStruct of an EIP712Domain struct with up to five fields: name, version, chainId, verifyingContract and salt. The EIP lets designers include only "the fields that make sense for their signing domain", and that freedom is where replay bugs start, because chainId and verifyingContract are the two fields that stop a signature from being accepted on another chain or by another deployment of the same code.

A contract that verifies its own typed messages should build the digest itself from the function arguments. The example below compiles against OpenZeppelin Contracts v5.7.0 with Solidity 0.8.38.

SOLIDITY
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";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract SignedWithdrawals is EIP712, Nonces {
    using SafeERC20 for IERC20;

    bytes32 private constant WITHDRAW_TYPEHASH =
        keccak256("Withdraw(address owner,address to,uint256 amount,uint256 nonce,uint256 deadline)");

    IERC20 public immutable asset;
    mapping(address => uint256) public balanceOf;

    error Expired();
    error BadSignature();

    constructor(IERC20 asset_) EIP712("SignedWithdrawals", "1") {
        asset = asset_;
    }

    function deposit(uint256 amount) external {
        balanceOf[msg.sender] += amount;
        asset.safeTransferFrom(msg.sender, address(this), amount);
    }

    function withdrawBySig(address owner, address to, uint256 amount, uint256 deadline, bytes calldata signature)
        external
    {
        if (block.timestamp > deadline) revert Expired();

        // _useNonce returns the current nonce and increments it, so the signature is spent here.
        bytes32 structHash = keccak256(abi.encode(WITHDRAW_TYPEHASH, owner, to, amount, _useNonce(owner), deadline));
        bytes32 digest = _hashTypedDataV4(structHash);

        if (!SignatureChecker.isValidSignatureNow(owner, digest, signature)) revert BadSignature();

        balanceOf[owner] -= amount;
        asset.safeTransfer(to, amount);
    }
}

Three details in it carry weight. _hashTypedDataV4 prepends the domain separator, which OpenZeppelin's EIP712 rebuilds whenever block.chainid or address(this) differs from the values cached at construction, so the digest stays correct after a chain split and behind a proxy. EIP-2612 warns about the alternative, a DOMAIN_SEPARATOR fixed at deployment, which risks "replay attacks between chains in the event of a future chain split". _useNonce consumes the signer's nonce before any external call. SignatureChecker accepts contract accounts as well as EOAs, which comes up again below.

The encoding rules have traps of their own. Dynamic bytes and string members are replaced by the keccak256 of their contents, arrays by the hash of their concatenated encoded elements, and nested structs by their own hashStruct. A hand-written struct hash that skips one of these steps produces digests that no wallet will sign, which shows up as a dead feature and is easy to catch. The quieter mistake is to hash with abi.encodePacked, since the Solidity ABI specification says packed encoding "is ambiguous as soon as there are two dynamically-sized elements". Trail of Bits' review of Meson found a relative of this bug, where two message types shared one untyped 32-byte encoding and a swap request could be made to collide with a release (finding writeup).

Replay is a missing field#

A signature is replayable whenever some context in which it should be invalid was left out of the digest, or its use was never recorded. The table lists the fields we check for, with a case where each one was absent.

FieldWhat it limitsWhat happened without it
Nonce or used-flag, written before the effectnumber of usesAzukiDAO's claim kept a signatureClaimed map and never checked it, so one signed claim was redeemed 200 times in July 2023, for about $69k (writeup)
chainId, read from block.chainid when verifyingchainPhi's signatureClaim decoded a chain id from the signed payload and discarded it (finding). Another audited contract accepted the whole domain separator from the caller (finding)
verifyingContractdeploymentHYBUX hashed only (sender, tokenIds, weights), so a signature issued for one staking contract was valid on a second one that shared the signer (finding)
Caller, recipient and amountactionSofamon's mint signature left out msg.sender, so any fresh address at nonce 0 could present it (finding)
deadlinetime windowA leaked or forgotten signature stays usable until the nonce moves

The nonce row deserves a second look in any review, because nonces come in two shapes. A sequential per-signer counter, as in EIP-2612, forces signatures to be used in order, which suits approvals. Orders and intents that must be usable in any order need unordered nonces, usually a bitmap in which each signature names the bit it will set. The signature bytes themselves must never stand in for a nonce, since one authorization has more than one valid byte encoding (the malleability section of the ECDSA post has an exploit of that pattern).

Signers that are contracts#

ecrecover can only speak for a private key. A Safe or an ERC-4337 account has none, so ERC-1271 gives contracts a method, isValidSignature(bytes32 hash, bytes signature), that returns 0x1626ba7e (its own selector) when the account accepts the signature. SignatureChecker.isValidSignatureNow in the example above uses ECDSA recovery when the signer has no code and makes this call when it has, which includes an EOA that carries an EIP-7702 delegation, since EXTCODESIZE reports 23 bytes for it. A protocol that only calls ecrecover locks those users out, and EIP-2612 permit has that limitation built in, which is why OpenZeppelin's IERC20Permit documentation tells integrators to keep an entry point that works without a permit.

ERC-1271 moves one replay boundary into the account, and many accounts got it wrong. If an account validates the incoming hash directly against its owner's key, then two accounts owned by the same key accept the same signature, even when the application's digest is correct in all other respects. Alchemy found this in October 2023 in its own LightAccount and in several other account implementations, and published the details in March 2024. Most of the affected accounts adopted an EIP-712 wrapper, in which the account re-hashes the incoming digest under its own domain before checking the owner's signature, and ERC-7739 (a draft at the time of writing) standardises that wrapping.

The mistake still turns up in audits, for example in an ERC-1271 handler of zkSync SSO (finding) and in a session module that implemented the wrapper with its own address in the domain in place of the account's (finding).

Permit in an integration#

EIP-2612 permit(owner, spender, value, deadline, v, r, s) sets an allowance from a signature. Compared with approve, it changes two things for the contract that integrates it, and both have been exploited.

Anyone can submit the signature first#

A permit signature names the owner, the spender, the value, the nonce and the deadline. It leaves out who may submit it, so anyone who sees it in the mempool can call permit on the token directly. The EIP says as much and adds that "the end result is the same for the Permit signer". That holds for the signer and fails for a contract that calls permit and then continues, because once the nonce is used the second permit call reverts and takes the user's whole transaction with it.

sequenceDiagram autonumber participant U as User (wallet) participant A as Attacker (mempool watcher) participant T as ERC-20 (permit) participant D as dApp contract U->>U: sign Permit(owner, spender = D, value, nonce, deadline) U->>D: pending tx: depositWithPermit(amount, sig) A->>T: permit(sig), copied from the pending tx and mined first T-->>A: allowance set, nonce consumed D->>T: permit(sig), inside the user's tx T-->>D: revert, nonce already used note over U,D: the deposit never runs although the allowance it needed is in place

No tokens move, yet a deposit or a repayment can be blocked for as long as someone is willing to pay for the front-run, which hurts most when the action is time-sensitive, such as topping up collateral. The mitigation OpenZeppelin documents in IERC20Permit is to let the permit fail and rely on the allowance check that follows.

SOLIDITY
function depositWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
    // A front-runner may already have used this signature. The allowance it set is still there.
    try IERC20Permit(address(token)).permit(msg.sender, address(this), amount, deadline, v, r, s) {} catch {}
    deposit(amount);
}

function deposit(uint256 amount) public {
    shares[msg.sender] += amount;
    token.safeTransferFrom(msg.sender, address(this), amount);
}

We ran both variants in a local Foundry test. With a bare permit call the front-run makes the deposit revert, and with the try/catch form the same deposit goes through on the allowance the front-runner's call created. The owner passed to permit is msg.sender. Taking owner as a parameter turns the function into a way to move someone else's tokens, as the next case shows.

A permit call that returns proves nothing#

Multichain's router had a function anySwapOutUnderlyingWithPermit that took a from address, a token address and a signature. It read underlying() from token, called permit(from, router, ...) on that underlying, and then pulled the tokens with safeTransferFrom(underlying, from, token, amount). An attacker could pass a contract of their own as token and have it report WETH as the underlying. WETH has no permit function, but it has a fallback that accepts any calldata, so the call returned normally and the router went on to spend the allowance that from had granted it earlier for ordinary use.

Dedaub reported this class of bug to Multichain on 10 January 2022 and named it a phantom function (their writeup). The router was exploited later that month (writeup), and the same path drained an account that still had a standing approval on 29 July 2025 (writeup).

Dedaub's general rule is that "callers should not rely on permit reverting for arbitrary tokens". A contract that accepts permits for tokens it does not control should therefore act only on msg.sender's tokens and depend on the effect it needs, which is the allowance. A helper that calls permit for a caller-chosen owner deserves the same scrutiny as any function that spends third-party approvals, as a finding on a router's pullTokensWithPermit illustrates (finding).

DAI needs separate handling, because its permit predates the standard and takes (holder, spender, nonce, expiry, allowed), a difference the EIP-2612 text records.

Permit2#

Uniswap's Permit2 moves signature approvals out of the token. The user approves the Permit2 contract once per token and from then on signs Permit2 messages. It has two modes with different replay properties.

AllowanceTransfer.permit behaves like EIP-2612 with an expiry. It uses a sequential nonce per owner, token and spender, and anyone may submit the signature, so the front-run consideration above applies unchanged. SignatureTransfer.permitTransferFrom is a one-shot transfer. Its nonces are unordered bits in a per-owner bitmap, and the signed hash includes msg.sender as the spender, which makes a copied signature useless to any other caller.

Neither mode signs, by default, what the spender will do with the tokens. In an audit of Sablier, a PermitSingle naming a proxy as spender could be replayed through any plugin that the proxy would run, which sent the tokens to a recipient the user never chose (finding). permitWitnessTransferFrom exists for this case. The integrator supplies a witness hash and its type string, and the user's signature then covers the order, the recipient or any other data the protocol needs bound.

What the wallet shows the user#

A typed message protects users only if they can read it, and with Permit2 a single off-chain signature can move any token the user has approved to it. Patrick Collins' video decodes an EIP-712 request field by field on a hardware wallet, which is a useful exercise for anyone who designs the structs users will be asked to sign. The pipeline around the wallet is the subject of Signing Infrastructure Threat Model.

Review checklist#

These are the questions we ask of any function that accepts a signature, roughly in the order in which they find bugs.

  1. What does the signed message say in plain words, and does the digest contain each part of that sentence (who, what, how much, to whom, on which contract and chain, until when)?
  2. Is the digest built on-chain from the arguments, with a domain separator derived from block.chainid and address(this)?
  3. What marks the signature as used, and is that written before any external call?
  4. What happens if a stranger submits the signature first, on its own, in a different transaction?
  5. If the signer can be a contract, is ERC-1271 supported, and does the account bind the hash to itself?
  6. For permits on arbitrary tokens, is the owner always msg.sender, and does the code survive both a reverting permit and one that silently does nothing?

To debug a concrete signature, the Signature Lab on this site rebuilds the domain separator and digest for a typed message or a permit and shows which address the signature recovers to.

Sources#