
Building a Safe ERC20 Airdrop Claim Contract with Merkle Proofs in Solidity
Why use a Merkle airdrop?
Airdrops often need to support hundreds or thousands of recipients. A naive design that stores every allocation on-chain is expensive and operationally rigid. A Merkle tree solves this by compressing the full distribution into one root hash.
Each claimant submits:
- their address
- their allocation amount
- a Merkle proof
The contract verifies that the leaf is part of the published tree and transfers tokens only once.
Benefits
| Approach | On-chain storage | Gas cost per claim | Operational flexibility |
|---|---|---|---|
| Store all recipients | High | Low to medium | Low |
| Push transfers from owner | Low | High for owner | Medium |
| Merkle claim contract | Very low | Low | High |
Merkle claims are especially useful for:
- community rewards
- retroactive contributor distributions
- testnet incentive programs
- token launch campaigns
- partner or referral payouts
Contract design goals
A production-ready airdrop contract should enforce a few rules:
- Only valid proofs can claim
- Each allocation can be claimed once
- The contract must hold enough tokens before claims begin
- The distribution root should be configurable by an authorized account
- Claims should emit events for indexing and analytics
To keep the example focused, we will implement a single-round airdrop where each address has one fixed allocation.
How the Merkle tree works
Each recipient is encoded as a leaf, typically using the recipient address and allocation amount. For example:
leaf = keccak256(abi.encodePacked(account, amount))
Leaves are paired and hashed repeatedly until only one hash remains: the Merkle root. Off-chain tooling generates:
- the root
- each recipient’s proof
- the allocation list used to build the tree
On-chain, the contract recomputes the leaf and verifies the proof against the stored root.
Important hashing note
Use the exact same encoding and hashing scheme off-chain and on-chain. A mismatch in field order, type encoding, or sorting will invalidate proofs.
Example contract
The following contract uses OpenZeppelin libraries for ERC20 interaction, access control, Merkle proof verification, and reentrancy protection.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract MerkleAirdrop is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
IERC20 public immutable token;
bytes32 public merkleRoot;
mapping(address => bool) public hasClaimed;
event MerkleRootUpdated(bytes32 indexed oldRoot, bytes32 indexed newRoot);
event Claimed(address indexed account, uint256 amount);
constructor(address tokenAddress, bytes32 initialRoot, address initialOwner) Ownable(initialOwner) {
require(tokenAddress != address(0), "token is zero address");
token = IERC20(tokenAddress);
merkleRoot = initialRoot;
}
function setMerkleRoot(bytes32 newRoot) external onlyOwner {
bytes32 oldRoot = merkleRoot;
merkleRoot = newRoot;
emit MerkleRootUpdated(oldRoot, newRoot);
}
function claim(
uint256 amount,
bytes32[] calldata proof
) external nonReentrant {
require(!hasClaimed[msg.sender], "already claimed");
require(amount > 0, "amount is zero");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender, amount));
require(MerkleProof.verifyCalldata(proof, merkleRoot, leaf), "invalid proof");
hasClaimed[msg.sender] = true;
token.safeTransfer(msg.sender, amount);
emit Claimed(msg.sender, amount);
}
function withdrawUnclaimed(address to, uint256 amount) external onlyOwner {
require(to != address(0), "to is zero address");
token.safeTransfer(to, amount);
}
}
Contract walkthrough
State variables
token: the ERC20 token being distributedmerkleRoot: the current distribution roothasClaimed: tracks whether an address has already claimed
This simple boolean mapping is enough for one-time claims. If you need multiple distribution rounds, you should track claims by round ID instead of by address alone.
Constructor
The constructor sets:
- the token contract address
- the initial Merkle root
- the owner
Using Ownable(initialOwner) makes deployment more flexible, especially when a multisig is responsible for administration.
setMerkleRoot
This function lets the owner update the distribution root. That is useful if you want to publish a corrected tree or run a new campaign.
Be careful: changing the root after claims have started can create confusion. In production, you should define a clear policy, such as:
- root changes allowed only before the claim window opens, or
- root changes only for a new campaign contract
claim
The claim function performs the critical checks:
- the caller has not claimed before
- the amount is valid
- the Merkle proof matches the stored root
- the claim is recorded
- tokens are transferred
The order matters. The contract marks the claim before transferring tokens, which helps prevent reentrancy-based double claims. The nonReentrant modifier adds another layer of defense.
withdrawUnclaimed
This function lets the owner recover leftover tokens after the campaign ends. In a real deployment, you may want to restrict this to a post-expiration period or require a timelock.
Building the Merkle tree off-chain
The contract only verifies proofs; it does not generate them. You typically build the tree in a script using a library such as merkletreejs or a custom hashing pipeline.
A common off-chain leaf format is:
keccak256(abi.encodePacked(address, amount))
If your distribution uses sorted pairs, the tree builder must sort sibling hashes consistently. OpenZeppelin’s MerkleProof verification assumes the proof was generated using the same tree construction rules.
Example data flow
- Prepare a CSV or JSON file of recipients and amounts
- Hash each
(address, amount)pair into a leaf - Build the Merkle tree
- Export:
- the root
- each recipient’s proof
- the allocation list
- Deploy the contract with the root
- Fund the contract with enough tokens
- Publish proof data to users
Practical claim flow
A typical user experience looks like this:
- The user connects a wallet
- The frontend looks up their allocation
- The frontend fetches their proof from an API or static JSON file
- The user calls
claim(amount, proof) - The contract verifies and transfers tokens
For a better UX, the frontend should also check:
- whether the connected address is eligible
- whether the user already claimed
- whether the contract has enough token balance
- whether the root matches the published campaign metadata
Security considerations
1. Use SafeERC20
Not all ERC20 tokens behave identically. SafeERC20 handles tokens that return false or do not return a value consistently. This avoids silent transfer failures.
2. Prevent double claims
A simple mapping(address => bool) is enough for one allocation per address. If your distribution allows multiple claims or partial claims, use a more granular accounting model.
3. Protect against reentrancy
Although standard ERC20 transfers are usually safe, external token contracts can be nonstandard. nonReentrant is a sensible defense-in-depth measure.
4. Keep the leaf format stable
The most common source of failed claims is a mismatch between the off-chain and on-chain leaf encoding. Document the exact schema and never change it mid-campaign.
5. Fund the contract before opening claims
If the contract does not hold enough tokens, claims will revert. A good operational practice is to:
- deploy the contract
- verify the root
- transfer the full distribution amount
- test one claim on a small allocation
- then announce the campaign publicly
Common variations
| Variation | When to use it | Key change |
|---|---|---|
| Multi-round airdrop | Several campaigns over time | Track claims by roundId |
| Partial claims | Users can claim in installments | Store claimed amount per user |
| Deadline-based claims | Campaign expires after a date | Add claimDeadline |
| Delegated claims | Another address can claim on behalf of a user | Add signature or authorization logic |
Multi-round pattern
If you plan multiple distributions, replace mapping(address => bool) with something like:
mapping(uint256 => mapping(address => bool)) public hasClaimedRound;
That way, a user can claim once per round without interfering with other campaigns.
Testing recommendations
A Merkle airdrop contract should be tested with both positive and negative cases.
Test cases to include
- valid proof succeeds
- invalid proof reverts
- wrong amount reverts
- repeated claim reverts
- zero amount reverts
- owner can update the root
- non-owner cannot update the root
- token transfer failure reverts cleanly
Example test scenarios
| Scenario | Expected result |
|---|---|
| Correct proof and amount | Claim succeeds |
| Same address claims twice | Revert |
| Proof for another user | Revert |
| Amount does not match leaf | Revert |
| Contract lacks balance | Revert |
In Hardhat or Foundry, it is worth generating a small tree with three or four recipients and asserting that each proof is unique and valid only for its matching leaf.
Deployment checklist
Before mainnet deployment, verify the following:
- the token address is correct
- the Merkle root matches the published recipient set
- the contract owner is a secure multisig
- the contract balance covers all claims
- the frontend proof data matches the deployed root
- the claim function has been tested on a fork or testnet
If the distribution is large, consider publishing the full recipient list and root generation script for transparency. That makes it easier for users and auditors to reproduce the tree independently.
When this pattern is the right choice
Use a Merkle claim contract when you want:
- low on-chain storage costs
- a transparent and auditable distribution
- user-driven claims instead of manual payouts
- a single published allocation snapshot
Avoid it when recipients must change frequently, when claims depend on dynamic business logic, or when each user’s entitlement is computed from live state. In those cases, a more interactive accounting model may be more appropriate.