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 ERC7758, a proposal for securely transferring ERC20 tokens through meta-transactions (the approve + transferFrom pattern).

The explanation below translates, summarizes, and expands on the following proposal.

Overview

ERC7758 proposes using EIP712 to enable meta-transactions for ERC20 tokens. This mechanism enables the following.

  • Let another party pay gas fees.
  • Pay gas fees in ERC20 tokens instead of ETH.
  • Batch multiple token transfers or operations in a single transaction.
  • Implement a mechanism in which the recipient submits the transaction when tokens are sent.
  • Process multiple transactions efficiently to improve computational efficiency and reduce fee overhead.
  • Improve nonce management to prevent transaction failures.

See the following article for more about ERC20.

https://chaldene.net/erc20

See the following article for more about ERC712.

EIP712: Hashing and Signing Typed Structured Data

Motivation

What is a meta-transaction?

Ordinarily, executing a transaction on an EVM-compatible blockchain requires the sender (the person who wants to execute the transaction) to pay gas fees in ETH. With meta-transactions, however, someone else, such as a relay service or the operator's EOA, can submit the transaction to the blockchain and pay the gas instead of the sender submitting it directly.

Example

Suppose Alice wants to send ERC20 tokens to Bob. Alice has no ETH, so she cannot submit a transaction. Alice creates a signed message compliant with EIP712 and sends it to Bob. Bob uses that message to submit a transaction on-chain and pays gas on Alice's behalf.

This allows users without ETH to exchange ERC20 tokens while another address pays the gas and executes the transaction.

Differences from ERC2612

ERC2612 also enables meta-transactions, but it differs from this proposal in the following respects.

See the following article for more about ERC2612.

ERC2612: Executing ERC20 approve and transferFrom in One Transaction

Nonce management

ERC2612 uses sequential nonce values, whereas this proposal uses random 32-byte nonce values.

When an EOA creates a transaction, the transaction includes a unique sequential value. This value is called a nonce and prevents the same transaction from being executed more than once.

ERC2612 assumes that transactions are processed in order. If a transaction remains unprocessed, the following transaction cannot execute until it has been processed. DApps may also inadvertently reuse the same nonce, or transactions may be processed in an unintended order because of transaction ordering. When gas prices rise and transactions become congested, this can make it difficult for users to process multiple transactions concurrently without failures.

By using random nonce values, ERC7758 avoids conflicts caused by issuing multiple transactions at the same time. It also enables parallel processing, allowing senders to submit multiple transactions safely.

Approval (approve) and transfer (transferFrom)

ERC2612 uses the ERC20 approve → transferFrom pattern, whereas this proposal does not. The reason is that the ERC20 approve → transferFrom pattern has security concerns.

Problems with the approve + transferFrom pattern

Multiple Withdrawal Attack

When ERC20 approve is used to authorize token transfers, a malicious account may be able to use that authorization for multiple transfers. For example, if an attacker calls transferFrom multiple times immediately after a DApp calls approve, tokens may be transferred in ways the user did not intend.

Infinite Allowance

Many DApps recommend an infinite allowance for convenience (a single approve grants unlimited token spending). However, if the DApp or smart contract is compromised, an attacker can continue stealing tokens without an allowance limit. To avoid these problems, the proposal recommends not using the approve → transferFrom mechanism.

Why was ERC777 not widely adopted?

ERC777 emerged as a token standard intended to address the ERC20 approve problem, but it did not gain widespread adoption. The reasons include the following.

ERC20 compatibility issues

Existing DApps and wallets did not support ERC777. ERC777 introduced a new concept called hooks, which older contracts could not accommodate.

Security concerns

Abusing hooks can disrupt certain transactions or cause unintended behavior. In particular, the risk of reentrancy attacks increases. Although ERC777 is theoretically a more capable token standard, adoption remained limited and it did not become a widely used replacement for ERC20.

Specification

Interface

js
event AuthorizationUsed(
    address indexed authorizer,
    bytes32 indexed nonce
);

// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;

// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;

AuthorizationUsed

js
event AuthorizationUsed(
    address indexed authorizer,
    bytes32 indexed nonce
);

Overview
An event emitted when tokens are transferred using an EIP712-compliant signature.

Details
This event is emitted when tokens are transferred through transferWithAuthorization or receiveWithAuthorization, indicating that the transaction signature has been used. This helps prevent the same signature from being reused.

Parameters

  • authorizer
    • The address that signed the authorization (the token sender).
  • nonce
    • A unique identifier associated with the signature (a random 32-byte value).

TRANSFER_WITH_AUTHORIZATION_TYPEHASH

js
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;

Overview
A constant representing the EIP712 type hash for transferWithAuthorization.

Details
EIP712 explicitly defines the structure of a message and uses a hash for signing. This constant is the keccak256 hash of the transferWithAuthorization data structure. It is used to check transaction integrity when verifying signatures.


RECEIVE_WITH_AUTHORIZATION_TYPEHASH

js
bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;

Overview
A constant representing the EIP712 type hash for receiveWithAuthorization.

Details
EIP712 defines message types and uses their hashes for signing. This constant is the keccak256 hash of the receiveWithAuthorization data structure. It is used to verify that a receiveWithAuthorization request is legitimate.


authorizationState

js
function authorizationState(
    address authorizer,
    bytes32 nonce
) external view returns (bool);

Overview
A function that checks whether a specified nonce has already been used.

Details
This function checks whether a nonce used by transferWithAuthorization or receiveWithAuthorization has already been consumed.
A nonce cannot be reused once consumed, which helps prevent replay attacks.

Arguments

  • authorizer
    • The address that signed the authorization (the token sender).
  • nonce
    • A unique identifier (a random 32-byte value).

Return value

  • bool
    • If true, the nonce has already been used.
    • If false, the nonce is unused and the transaction can be executed.

transferWithAuthorization

js
function transferWithAuthorization(
    address from,
    address to,
    uint256 value,
    uint256 validAfter,
    uint256 validBefore,
    bytes32 nonce,
    uint8 v,
    bytes32 r,
    bytes32 s
) external;

Overview
A function that transfers tokens using an EIP712 signature.

Details
The recipient (to) or a third party can submit data signed off-chain in advance by the sender (from) to transfer tokens on-chain.
This enables token transfers even without ETH and allows another party to pay the gas.
The nonce also prevents reuse of the signature.

Arguments

  • from
    • The sender (the token owner who signed the authorization).
  • to
    • The recipient address (the address receiving the tokens).
  • value
    • The amount of tokens to transfer.
  • validAfter
    • The time at which the signature becomes valid (Unix timestamp).
  • validBefore
    • The time at which the signature expires (Unix timestamp).
  • nonce
    • A unique identifier (a random 32-byte value).
  • v
    • The v component of the signature (an EIP712 signature component).
  • r
    • The r component of the signature (an EIP712 signature component).
  • s
    • The s component of the signature (an EIP712 signature component).

receiveWithAuthorization

js
function receiveWithAuthorization(
    address from,
    address to,
    uint256 value,
    uint256 validAfter,
    uint256 validBefore,
    bytes32 nonce,
    uint8 v,
    bytes32 r,
    bytes32 s
) external;

Overview
A function that transfers tokens using an EIP712 signature while ensuring that the recipient itself executes the transaction.

Details
Unlike transferWithAuthorization, this function requires the recipient address (to) to match msg.sender.
This prevents third parties from front-running the transaction.
As with the other functions, the nonce prevents signature reuse.

Arguments

  • from
    • The sender (the token owner who signed the authorization).
  • to
    • The recipient address (the address receiving the tokens).
  • value
    • The amount of tokens to transfer.
  • validAfter
    • The time at which the signature becomes valid (Unix timestamp).
  • validBefore
    • The time at which the signature expires (Unix timestamp).
  • nonce
    • A unique identifier (a random 32-byte value).
  • v
    • The v component of the signature (an EIP712 signature component).
  • r
    • The r component of the signature (an EIP712 signature component).
  • s
    • The s component of the signature (an EIP712 signature component).

Optional functionality

AuthorizationCanceled

js
event AuthorizationCanceled(
    address indexed authorizer,
    bytes32 indexed nonce
);

Overview
An event emitted when an EIP712-compliant signature is canceled through cancelAuthorization.

Details
This event is emitted when an unused signature is canceled, recording the cancellation of its nonce.
This helps prevent signatures that are no longer needed from being misused.

Arguments

  • authorizer
    • The address that signed the authorization (the token owner).
  • nonce
    • A unique identifier (the canceled random 32-byte value).

CANCEL_AUTHORIZATION_TYPEHASH

js
bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;

Overview

A constant representing the EIP712 data type for cancelAuthorization.

Details
EIP712 defines message types and uses their hashes for signing.
This constant is the keccak256 hash of the cancelAuthorization data structure. It is used to verify that a cancelAuthorization request is legitimate.


cancelAuthorization

js
function cancelAuthorization(
    address authorizer,
    bytes32 nonce,
    uint8 v,
    bytes32 r,
    bytes32 s
) external;

Overview

A function that cancels (invalidates) an unused signature.

Details
The signature can be canceled before the transaction executes.
This can prevent unauthorized use if the signature is leaked.
Once a nonce is canceled, it cannot be used again.

Arguments

  • authorizer
    • The address that signed the authorization (the token owner).
  • nonce
    • The unique identifier to cancel (a random 32-byte value).
  • v
    • The v component of the signature (an EIP712 signature component).
  • r
    • The r component of the signature (an EIP712 signature component).
  • s
    • The s component of the signature (an EIP712 signature component).

Examples

Generating the domain separator (DomainSeparator)
js
DomainSeparator := Keccak256(ABIEncode(
  Keccak256(
    "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
  ),
  Keccak256("USD Coin"),                      // name
  Keccak256("2"),                             // version
  1,                                          // chainId
  0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48  // verifyingContract
))

EIP712 signing defines a structure called EIP712Domain (DomainSeparator) to ensure signature uniqueness. The DomainSeparator generates a different hash for each target contract or token, preventing signatures from being confused across contracts and preventing replay attacks across blockchains.

  • name (e.g., "USD Coin")
    • The token name.
  • version (e.g., "2")
    • The smart contract version.
  • chainId (e.g., 1)
    • The chain ID of the blockchain where the transaction executes (Ethereum mainnet = 1).
  • verifyingContract (e.g., 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48)
    • The contract address that processes the transaction.

Calculating the type hash (TypeHash)
js
// Transfer With Authorization
TypeHash := Keccak256(
  "TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"
)
Params := { From, To, Value, ValidAfter, ValidBefore, Nonce }

// ReceiveWithAuthorization
TypeHash := Keccak256(
  "ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"
)
Params := { From, To, Value, ValidAfter, ValidBefore, Nonce }

// CancelAuthorization
TypeHash := Keccak256(
  "CancelAuthorization(address authorizer,bytes32 nonce)"
)
Params := { Authorizer, Nonce }

A type hash (TypeHash) is created for each transaction type to identify the type of transaction.
This is an important mechanism for processing EIP712 typed messages.

What is a type hash (TypeHash)?

A fixed data type is defined for each function (TransferWithAuthorization, ReceiveWithAuthorization, and CancelAuthorization), and its hash is calculated in advance.
This makes it possible to distinguish the types of data being signed.


Hashing and signing transaction data
js
// "‖" denotes concatenation.
Digest := Keccak256(
  0x1901 ‖ DomainSeparator ‖ Keccak256(ABIEncode(TypeHash, Params...))
)

{ v, r, s } := Sign(Digest, PrivateKey)

The following transaction data is hashed with keccak256, and the resulting hash is signed with the user's private key.

  • 0x1901 (fixed prefix)
  • DomainSeparator (domain separator)
  • Keccak256(ABIEncode(TypeHash, Params...)) (encoding the type hash and data)

The resulting signature components, v, r, s, can be verified by the contract to ensure that the off-chain signature has not been tampered with.


A contract that wraps receiveWithAuthorization
js
function deposit(address token, bytes calldata receiveAuthorization)
    external
    nonReentrant
{
    (address from, address to, uint256 amount) = abi.decode(
        receiveAuthorization[0:96],
        (address, address, uint256)
    );
    require(to == address(this), "Recipient is not this contract");

    (bool success, ) = token.call(
        abi.encodePacked(
            _RECEIVE_WITH_AUTHORIZATION_SELECTOR,
            receiveAuthorization
        )
    );
    require(success, "Failed to transfer tokens");

    ...
}

This function wraps receiveWithAuthorization to simplify processing signed transactions.

  1. Decode the receiveAuthorization data to obtain from, to, and amount.
  2. Check whether to (the recipient address) is the contract itself.
  3. Call receiveWithAuthorization to transfer the tokens.
  4. Return an error if the operation fails.

Passing the signed data as a single bytes value simplifies transaction execution.

Web3 providers

The proposal also provides sample code for obtaining EIP712 signatures using a Web3 provider such as MetaMask.


Defining the EIP712 message structure

javascript
const data = {
  types: {
    EIP712Domain: [
      { name: "name", type: "string" },
      { name: "version", type: "string" },
      { name: "chainId", type: "uint256" },
      { name: "verifyingContract", type: "address" },
    ],
    TransferWithAuthorization: [
      { name: "from", type: "address" },
      { name: "to", type: "address" },
      { name: "value", type: "uint256" },
      { name: "validAfter", type: "uint256" },
      { name: "validBefore", type: "uint256" },
      { name: "nonce", type: "bytes32" },
    ],
  },
  domain: {
    name: tokenName,
    version: tokenVersion,
    chainId: selectedChainId,
    verifyingContract: tokenAddress,
  },
  primaryType: "TransferWithAuthorization",
  message: {
    from: userAddress,
    to: recipientAddress,
    value: amountBN.toString(10),
    validAfter: 0,
    validBefore: Math.floor(Date.now() / 1000) + 3600, // 有効期限を1時間後に設定
    nonce: Web3.utils.randomHex(32),
  },
};

This code defines an EIP712 typed message and constructs the data to sign for the transaction.

Details

  • Define the EIP712 message structure

    • types
      • Type definitions
    • domain
      • Domain information that ensures signature uniqueness
    • primaryType
      • The primary type of this message
    • message
      • The data to sign
  • Domain information (domain)

    • name
      • Token name (e.g., "USD Coin")
    • version
      • Token version (e.g., "2")
    • chainId
      • Target blockchain ID (e.g., 1 = Ethereum mainnet)
    • verifyingContract
      • Address of the contract performing the operation
  • Message data (message)

    • from
      • Sender address
    • to
      • Recipient address
    • value
      • Amount of tokens to transfer (converted from BigNumber format to a string)
    • validAfter
      • Time at which the signature becomes valid (0 means immediately valid)
    • validBefore
      • Expiration time (current time +1 hour)
    • nonce
      • Random 32-byte value (prevents signature reuse)

Obtaining a signature with eth_signTypedData_v4

javascript
const signature = await ethereum.request({
  method: "eth_signTypedData_v4",
  params: [userAddress, JSON.stringify(data)],
});

Overview

eth_signTypedData_v4 is used to obtain an EIP712-formatted signature.

eth_signTypedData_v4 is an Ethereum method for obtaining EIP712 signatures. It can be called through a Web3 provider such as MetaMask. Once the user approves the signature in their wallet, the signature data is returned.

Arguments

  • userAddress
    • The address of the user signing the message.
  • JSON.stringify(data)
    • The EIP712 message data to sign.

Return value

  • signature
    • Signature data containing v, r, s (130 hexadecimal characters, prefixed with 0x).

Splitting the signature into v, r, s

javascript
const v = "0x" + signature.slice(130, 132);
const r = signature.slice(0, 66);
const s = "0x" + signature.slice(66, 130);

The signature returned by eth_signTypedData_v4 is split into v, r, s for use in the contract.

An Ethereum signature (65 bytes = 130 hexadecimal characters) has the following format.

Component Bytes Extraction
r 32 bytes signature.slice(0, 66)
s 32 bytes signature.slice(66, 130)
v 1 byte signature.slice(130, 132)
  • r
    • The first 32 bytes of signature (characters 0–65, including the prefix).
  • s
    • The next 32 bytes of signature (characters 66–129).
  • v
    • The last byte of signature (characters 130–131).
    • v is either 0x1b (27) or 0x1c (28).

Using the signature in a contract

These signature components (v, r, s) are passed as arguments to the contract's transferWithAuthorization or receiveWithAuthorization function.

Additional notes

Problems with sequential nonce values and the use of random nonces

Ethereum transactions ordinarily use sequential nonce values, but this mechanism does not work well for meta-transactions, motivating the use of random nonces.

For example, if a transaction with nonce = 4 is submitted before the transaction with nonce = 3 is processed, the former remains pending until the latter is confirmed.

However, this mechanism does not work for meta-transactions. In a meta-transaction, a relayer (a third party) submits the transaction instead of the user, so ordering is not guaranteed across different relayers.

This leads to the following problems.

Transactions are not processed in order

Even if a user issues transactions with nonce = 3, 4, 5, the order in which relayers submit them or transactions are included in blocks may produce an order such as 4 → 5 → 3. As a result, a valid nonce such as 3 may not be processed.

  • Transactions with excessively high nonce values fail immediately.

In ordinary Ethereum transactions, an excessively high nonce causes a transaction to remain pending, whereas in meta-transactions it can fail immediately and waste gas.

Conflicts across applications

When multiple applications are used, each may manage nonce values differently, creating the potential for duplicate nonces from outstanding authorizations.

Problems when gas prices are high

If high gas prices congest transactions, meta-transactions may remain pending for a long time, and the same nonce may inadvertently be reused in another transaction.

Solution

One solution is to use random nonce values.

Using a random 32-byte nonce removes the dependence on transaction ordering. Relayers can then process transactions in different orders without this conflict, avoiding wasted gas and transaction failures caused by nonce ordering.

Why validAfter and validBefore are needed

With meta-transactions, relayers submit transactions instead of users, so users do not directly control submission timing. The validAfter and validBefore fields specify the validity period to avoid the following problems.

Submission at an unintended time

For example, even if a user creates a signature intending to send tokens on payday (the 30th), the relayer might submit it on the 29th.

Submission too late

If a transaction is meant to become invalid unless payment occurs within 30 minutes, submission by the relayer 31 minutes later could otherwise result in an unwanted transaction.

Solution

Define validAfter as the start of the transaction's validity period and validBefore as the end of that period.

Signature security with EIP712

EIP712 improves signature security by including the contract address and chain ID in Ethereum signing data.

Basic Ethereum eth_sign signatures can be reused across contracts or networks, introducing replay risk.

EIP712 provides the following measures.

Using a domain separator

Including verifyingContract and chainId makes the signature invalid outside the specified contract and chain.

Using structured JSON data

With eth_signTypedData_v4, users can see what they are signing.

Compatibility

Existing ERC20 tokens rely on approve + transferFrom and do not directly support EIP712 meta-transactions. A forwarder contract is therefore needed to maintain compatibility with existing contracts.

Introducing a forwarder contract called DepositForwarder enables interaction with existing ERC20 contracts using EIP712 meta-transactions.

DepositForwarder is a wrapper contract that enables token deposits using meta-transactions.

Execution flow

  1. Receive signed receiveAuthorization data.
  2. Execute receiveWithAuthorization to transfer tokens from the sender (from) to the forwarder contract.
  3. Use approve on the transferred tokens so that the parent contract can receive them.
  4. Call the parent contract's deposit method to deposit the tokens (for example, for staking).
  5. Return tokens minted by the parent contract to the original sender (from).
  6. Refund any remaining excess tokens to the original sender (from).

Reference implementation

EIP7758.sol
abstract contract EIP7758 is IERC20Transfer, EIP712Domain {
    // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
    bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;

    // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
    bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;

    mapping(address => mapping(bytes32 => bool)) internal _authorizationStates;

    event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);

    string internal constant _INVALID_SIGNATURE_ERROR = "EIP7758: invalid signature";

    function authorizationState(address authorizer, bytes32 nonce)
        external
        view
        returns (bool)
    {
        return _authorizationStates[authorizer][nonce];
    }

    function transferWithAuthorization(
        address from,
        address to,
        uint256 value,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external {
        require(now > validAfter, "EIP7758: authorization is not yet valid");
        require(now < validBefore, "EIP7758: authorization is expired");
        require(
            !_authorizationStates[from][nonce],
            "EIP7758: authorization is used"
        );

        bytes memory data = abi.encode(
            TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
            from,
            to,
            value,
            validAfter,
            validBefore,
            nonce
        );
        require(
            EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from,
            "EIP7758: invalid signature"
        );

        _authorizationStates[from][nonce] = true;
        emit AuthorizationUsed(from, nonce);

        _transfer(from, to, value);
    }
}
IERC20Transfer.sol
abstract contract IERC20Transfer {
    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual;
}
EIP712Domain.sol
abstract contract EIP712Domain {
    bytes32 public DOMAIN_SEPARATOR;
}
EIP712.sol
library EIP712 {
    // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
    bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;

    function makeDomainSeparator(string memory name, string memory version)
        internal
        view
        returns (bytes32)
    {
        uint256 chainId;
        assembly {
            chainId := chainid()
        }

        return
            keccak256(
                abi.encode(
                    EIP712_DOMAIN_TYPEHASH,
                    keccak256(bytes(name)),
                    keccak256(bytes(version)),
                    bytes32(chainId),
                    address(this)
                )
            );
    }

    function recover(
        bytes32 domainSeparator,
        uint8 v,
        bytes32 r,
        bytes32 s,
        bytes memory typeHashAndData
    ) internal pure returns (address) {
        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                domainSeparator,
                keccak256(typeHashAndData)
            )
        );
        address recovered = ecrecover(digest, v, r, s);
        require(recovered != address(0), "EIP712: invalid signature");
        return recovered;
    }
}

Security

Why use receiveWithAuthorization instead of transferWithAuthorization?

To prevent front-running attacks.

What is front-running?

An attack in which another party (the attacker) detects a pending transaction (transaction A) and has another transaction (transaction B) processed first. On Ethereum, transactions are temporarily held in a waiting area called the mempool. An attacker can monitor the mempool and execute a particular transaction (such as transferWithAuthorization) first, potentially causing unintended outcomes.

Attack scenario

  1. Alice creates signed data for calling transferWithAuthorization and attempts to execute it through a relayer.
  2. An attacker monitors the mempool and obtains Alice's transferWithAuthorization data.
  3. The attacker changes to to their own account and executes transferWithAuthorization before Alice.
  4. As a result, Alice's intended wrapper function (the forwarder contract) may not run, and the funds may not be processed correctly.

Solution

Use receiveWithAuthorization. receiveWithAuthorization requires the recipient (to), rather than the sender (from), to execute the transaction, preventing an attacker from intercepting the transaction at will. It prevents front-running by checking that msg.sender matches to.

Additional measures

  • Use the first byte of the nonce as an identifier.
    • For example, define different nonce prefixes for different purposes.
  • This prevents misuse of receiveWithAuthorization across different intended purposes.

Considerations when submitting multiple transactions concurrently

In ordinary Ethereum transactions, the nonce determines execution order, but meta-transactions use random nonce values and cannot guarantee ordering. Different relayers may also submit transactions in different orders, so submitting interdependent transactions concurrently risks failure.

Solution

Submit dependent transactions one at a time

For example, if A → B → C is the required order, do not submit B until A is confirmed.

Manage ordering off-chain

Include ordering information in the signed data and implement sequential processing on the relayer side.

Manage nonce values carefully across applications

If a transaction with an outstanding nonce exists, another application might reuse that nonce. Each application can address this by managing nonce values off-chain.


Why ecrecover must check for the zero address (0x0)

When using ecrecover, reject the zero address (0x0).

ecrecover is Ethereum's public-key recovery function and is used to recover the original signer's address from signature data (v, r, s). However, invalid signature data can cause it to return the zero address (0x0000000000000000000000000000000000000000).

If the result of ecrecover is used directly for transfer or approve, the zero-address account might improperly obtain tokens.

Solution

Check for the zero address as shown below.

js
address recovered = ecrecover(digest, v, r, s);
require(recovered != address(0), "Invalid signature");

References

Peter Jihoon Kim (@petejkim), Kevin Britz (@kbrizzle), David Knott (@DavidLKnott), Dongri Jin (@dongri), "ERC-7758: Transfer With Authorization [DRAFT]," Ethereum Improvement Proposals, no. 7758, September 2020. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-7758.

Conclusion

This article covered ERC7758, which proposes a mechanism for securely transferring ERC20 tokens through meta-transactions (the approve + transferFrom pattern).