How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Enabling meta transactions inside your contract is a powerful addition. Requiring users to hold ETH to pay for gas has always been and still is one of the biggest user onboarding challenges. Who knows how many more people would be using Ethereum right now if it was just a simple click?
But sometimes the solution can be added meta transaction capability inside your contracts. The implementation might be easier than you think.
Let's took at the high-level description first.

What are meta-transactions?
A meta transaction is a regular Ethereum transaction which contains another transaction, the actual transaction. The actual transaction is signed by a user and then sent to an operator or something similar, no gas and blockchain interaction required. The operator takes this signed transaction and submits it to the blockchain paying for the fees himself.
The contract ensures there's a valid signature on the actual transaction and then executes it.
High-level overview
If we want to support generalized meta-transactions in our contract, it can be done with a few simple steps. On a high-level, there are two steps to it.
Step 1: Verify the signature of the meta-transaction. We'll do this by creating a hash following the EIP-712 standard and ecrecover
.
bool isValidSignature = ecrecover(hash(transaction), v, r, s) == transaction.signerAddress
Step 2: Once verified, we can extract the actual transaction data. By using delegatecall
on our current contract address, we execute a function in our current contract without doing a new contract call. Remember that delegatecall basically calls the contract's code but with the current contract's state. So by doing address(this).delegatecall
we just execute the all in our current contract and we can pass the transaction data along.
(bool didSucceed, bytes memory returnData) = address(this).delegatecall(transaction.data);
That's it for the most part. But there are some critical things to verify and also alternatives for the signature.
Let's look into more details.
Transaction execution in detail
As we've seen the heart of the execution is the delegatecall
. This is where the actual transaction is executed. But to ensure proper execution, we have to make sure some things are correct.
Transaction Struct
First let's look at the data inside our Transaction struct on the right. It contains all the relevant requirements set by the user and the transaction itself which is to be executed as the bytes data
. This is what's passed from the user to the operator to the contract.
struct Transaction {
uint256 salt;
uint256 expirationTimeSeconds;
uint256 gasPrice;
address signerAddress;
bytes data;
}
Typed Transaction Hash
We'll further need to compute a hash over all this data. This is used for the signature scheme and to prevent double execution of the same transaction. For details about this look at the end in the signature explanation.
This is the transaction schema hash:
EIP712_TRANSACTION_SCHEMA_HASH = keccak256(
abi.encodePacked("Transaction(uint256 salt,uint256 expirationTimeSeconds,uint256 gasPrice,address signerAddress,bytes data)")
);
This is the EIP712 schema hash and can be computed once in the constructor of the contract.
function _getTransactionTypedHash(
Transaction memory transaction
) private view returns (bytes32) {
return keccak256(abi.encodePacked(
EIP712_TRANSACTION_SCHEMA_HASH,
transaction.salt,
transaction.expirationTimeSeconds,
transaction.gasPrice,
uint256(transaction.signerAddress),
keccak256(transaction.data)
));
}
We can use that to compute the full typed transaction hash using keccak256
and abi.encodePacked
.
By hashing all relevant values, we can ensure that only exactly what the original user signed would result in a successful transaction execution. If for example the operator was to change just 1 second inside expirationTimeSeconds
, it would not work anymore.
This is just the first part of the hash, for the full details including the requirements for a secure signature, read the part about signatures below.
Setting correct msg.sender
If we just execute delegatecall, the msg.sender of the transaction would still be the operator of the meta transaction, not the original signer.
We can solve this by setting a context variable:
function _setCurrentContextAddressIfRequired(address contextAddress) private {
currentContextAddress = contextAddress;
}
function _getCurrentContextAddress() private view returns (address) {
return currentContextAddress == address(0) ? msg.sender : currentContextAddress;
}
Everywhere you would use the msg.sender
in your contract, you would now instead call _getCurrentContextAddress()
.
Preventing multiple wrapped transactions

Another thing we want to prevent is executing a meta-meta-transaction. (unless you want to be cool for no reason)
It serves no purpose and just wastes additional gas. So we can add the check before any transaction execution:
require(currentContextAddress == address(0), "META_TX: Transaction has context set already");
Ensuring transaction requirements are met
We'll further make sure that all defined requirements are met:
- An expiration time is useful, so the user knows a transaction is not executed months later when he doesn't expect it anymore.
- A
transactionsExecuted
mapping to ensure a meta transaction is only executed once. Note: Make sure to settransactionsExecuted[transactionHash] = true
after a successful execution. - A defined gas price by the user. This might not be required in your system. Since the gas is paid by the operator, the only reason for enforcing some gas price would be if the value has some further effect inside the transaction. For example in 0x the gas price will affect the fee prices.
require(block.timestamp < transaction.expirationTimeSeconds, "META_TX: Meta transaction is expired");
require(!transactionsExecuted[transactionHash], "META_TX: Transaction already executed");
require(tx.gasprice == requiredGasPrice, "META_TX: Gas price not matching required gas price");
Verifying the signature
Of course we only want to execute transactions with a valid signature. A naive solution may only take the transaction.data and sign that.
But...
- how do we ensure all additional transaction parameters are set correctly (expiration, salt, signer...) ?
- how do we prevent a signed transaction from being used multiple times?
The first part is easy, we create a hash over all those values as shown above with the _getTransactionTypedHash
function. The second part is what EIP-712 is solving for us. You can see how we create a hash from the transaction data and additional EIP-712 data below:
function _getFullTransactionTypedHash(Transaction memory transaction) private view returns (bytes32) {
bytes32 transactionStructHash = _getTransactionTypedHash(transaction);
bytes32 EIP191_HEADER = 0x1901000000000000000000000000000000000000000000000000000000000000;
bytes32 schemaHash = keccak256(abi.encodePacked("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"));
uint256 chainId = 1; // mainnet
address verifyingContract = address(this);
bytes32 domainHash = keccak256(abi.encodePacked(
schemaHash,
keccak256(bytes("My Protocol Name")),
keccak256(bytes("1.0.0")),
chainId,
verifyingContract
));
return keccak256(abi.encodePacked(EIP191_HEADER, domainHash, hashStruct));
}
We put additional information into our hash, so that a signed transaction may only be used for exactly this contract with the given chainId. For all the details, check out the EIP or my previous post on ERC20-Permit.
Okay now we have the full transaction hash and the signature from the user. We can obtain the three values r and s which are the elliptic curve signature values inside our signature by extracting the bytes32 values with a helper. The uint8 v value requires only a simple conversion.
Using ecrecover
with our given signature and the transaction hash, we compute a signer address. If this address matches the set transaction.signerAddress
, the signature is indeed valid.
function _isValidTransactionWithHashSignature(
Transaction memory transaction,
bytes32 txHash,
bytes memory signature
) private pure returns (bool) {
require(
signature.length == 66,
"META_TX: Invalid signature length"
);
uint8 v = uint8(signature[0]);
bytes32 r = _readBytes32(signature, 1);
bytes32 s = _readBytes32(signature, 33);
address recovered = ecrecover(txHash, v, r, s);
return transaction.signerAddress == recovered;
}
function _readBytes32(
bytes memory b, uint256 index
) private pure returns (bytes32 result) {
require(
b.length >= index + 32,
"META_TX: Invalid index for given bytes"
);
// Arrays are prefixed by
// a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
This is the regular signature scheme. It works perfectly if you have a user signing his own transaction.
But what if you want to allow smart contracts to create valid signatures?
Advanced signature schemes
An arguably more advanced use case is having smart contracts sign meta transactions, but imagine a user has his funds inside a multi signature smart contract. This is already quite common for certain wallets. This user cannot sign a transaction with the EIP-712 scheme to create a valid v, r, s signature.
function isValidSignature(
bytes32 hash,
bytes memory signature
) public view returns (bytes4);
where the return value is 0x1626ba7e
for a valid signature. It is up to the smart contract developer to decide on how to implement the signature logic.
So how can we verify such a signature?
You can see an example implementation on the right. Using staticcall
, we can ensure no further state modifications happen in the call. If the result succeeds and has a valid returnData length (this is very critical, see the previous 0x bug), we can check if the return value matches 0x1626ba7e
.
function _staticCallEIP1271Wallet(
address verifyingContractAddress,
bytes memory data,
bytes memory signature
) private view returns (bool) {
bytes memory callData = abi.encodeWithSelector(
IEIP1271Wallet.isValidSignature.selector,
data,
signature
);
(bool didSucceed, bytes memory returnData)
= verifyingContractAddress.staticcall(callData);
require(
didSucceed && returnData.length == 32,
"META_TX: EIP1271 call failed"
);
bytes4 returnedValue = _readBytes4(returnData, 0);
return returnedValue == 0x1626ba7e;
}
You may want to allow further methods for signatures like pre-signing or having operators that can sign on behalf of a user. See the existing types in 0x here for some inspiration.
Implementing it yourself
So far we've seen the critical parts for all the implementation. This should give you a good idea on how to implement this. I would further recommend looking at
- the 0x meta transaction implementation here
- the Openzeppelin EIP-712 support here
- the npm
eip-712
lib to implement the signing part here
The Openzeppelin EIP-712 library is still a draft, but has additional support for the case of forks where the chain id could change. Also take a look at the 0x code where a lot of the implementation in this blog post comes from.
Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
SushiSwap Explained!
Looking at the implementation details of SushiSwap
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Using the new Uniswap v2 in your contracts
What's new in Uniswap v2 and how to integrate Uniswap v2
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?