
Building a Safe ERC20 Pull Payment Distributor in Solidity
Airdrops, affiliate payouts, revenue shares, and rewards programs often need to distribute ERC20 tokens to many recipients. The simplest implementation is usually a loop that transfers tokens to each address, but that approach becomes fragile as recipient counts grow and can fail because of gas limits, partial execution, or unexpected token behavior.
A pull payment distributor avoids those problems by letting recipients claim their own tokens. This tutorial shows how to build a practical ERC20 distributor in Solidity that records allocations, supports one-time claims, and keeps the contract easy to audit and operate.
Why use a pull-based distributor?
In a push model, the contract sends tokens to every recipient in one transaction. That sounds convenient, but it creates several operational risks:
- Gas exhaustion when the recipient list is large
- Partial completion if one transfer fails mid-loop
- Operational complexity when distributions must be retried
- Higher attack surface if token transfers trigger unexpected behavior
A pull-based design changes the flow:
- The owner loads the contract with tokens.
- The contract records how much each recipient can claim.
- Each recipient calls
claim()when ready. - The contract transfers only that recipient’s allocation.
This pattern is especially useful for:
- Employee bonus distributions
- Community rewards
- Referral payouts
- Vesting-style token drops without time-based schedules
- Any scenario where recipients may claim at different times
Design goals
A good distributor should:
- Track allocations per recipient
- Prevent double claims
- Support batch setup for efficiency
- Use safe ERC20 transfer handling
- Emit events for off-chain indexing
- Keep the claim path simple and predictable
For this tutorial, we will build a contract with these features:
setAllocations()to register recipient balancesfund()to deposit tokens into the distributorclaim()to withdraw an individual allocationclaimable()view function for frontendsownerWithdrawUnclaimed()for recovering leftover tokens after the distribution period
Contract overview
The contract stores each recipient’s entitlement in a mapping. Once a recipient claims, the contract marks that allocation as claimed and transfers the tokens.
The implementation uses OpenZeppelin-style safety patterns:
Ownablefor administrative controlReentrancyGuardto protect state-changing claimsSafeERC20to handle non-standard ERC20 return values
Core data model
| State variable | Purpose |
|---|---|
token | ERC20 token being distributed |
allocations | Amount each recipient can claim |
claimed | Tracks whether a recipient already claimed |
totalAllocated | Sum of all registered allocations |
totalClaimed | Sum of all claimed amounts |
Implementation
Below is a complete example of a safe pull payment distributor.
// 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 {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract ERC20PullDistributor is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
IERC20 public immutable token;
mapping(address => uint256) private allocations;
mapping(address => bool) public claimed;
uint256 public totalAllocated;
uint256 public totalClaimed;
event AllocationSet(address indexed recipient, uint256 amount);
event Claimed(address indexed recipient, uint256 amount);
event Funded(address indexed from, uint256 amount);
event UnclaimedWithdrawn(address indexed to, uint256 amount);
constructor(IERC20 tokenAddress, address initialOwner) Ownable(initialOwner) {
token = tokenAddress;
}
function setAllocations(address[] calldata recipients, uint256[] calldata amounts)
external
onlyOwner
{
require(recipients.length == amounts.length, "Length mismatch");
for (uint256 i = 0; i < recipients.length; i++) {
address recipient = recipients[i];
uint256 amount = amounts[i];
require(recipient != address(0), "Zero recipient");
require(amount > 0, "Zero amount");
require(!claimed[recipient], "Already claimed");
require(allocations[recipient] == 0, "Allocation exists");
allocations[recipient] = amount;
totalAllocated += amount;
emit AllocationSet(recipient, amount);
}
}
function fund(uint256 amount) external {
require(amount > 0, "Zero amount");
token.safeTransferFrom(msg.sender, address(this), amount);
emit Funded(msg.sender, amount);
}
function claimable(address recipient) public view returns (uint256) {
if (claimed[recipient]) {
return 0;
}
return allocations[recipient];
}
function claim() external nonReentrant {
address recipient = msg.sender;
uint256 amount = claimable(recipient);
require(amount > 0, "Nothing to claim");
claimed[recipient] = true;
totalClaimed += amount;
token.safeTransfer(recipient, amount);
emit Claimed(recipient, amount);
}
function ownerWithdrawUnclaimed(address to, uint256 amount) external onlyOwner {
require(to != address(0), "Zero address");
uint256 available = token.balanceOf(address(this));
uint256 reserved = totalAllocated - totalClaimed;
require(available > reserved, "No excess tokens");
uint256 excess = available - reserved;
require(amount <= excess, "Amount exceeds excess");
token.safeTransfer(to, amount);
emit UnclaimedWithdrawn(to, amount);
}
}
How the contract works
1. Allocation setup
The owner calls setAllocations() with parallel arrays of recipients and amounts. Each recipient can only be assigned once, which keeps the accounting simple and avoids accidental overwrites.
This is a deliberate tradeoff. If you need editable allocations, you can add a separate update function, but that increases complexity and should be paired with careful event logging and governance controls.
2. Funding the distributor
The contract does not assume that allocations and funding happen in the same transaction. Instead, anyone can fund it by transferring tokens into the contract using fund().
This is useful when:
- Treasury operations are handled by a separate wallet
- Funding is staged over time
- A multisig wants to deposit tokens after allocations are finalized
3. Claiming tokens
A recipient calls claim(). The contract checks the recipient’s allocation, marks it as claimed, updates totals, and transfers the tokens.
The order matters:
- Read the claimable amount
- Update state
- Transfer tokens
- Emit the event
Updating state before the transfer helps protect against reentrancy and ensures a failed transfer does not leave the contract in an inconsistent state.
4. Recovering excess tokens
Sometimes the contract may hold more tokens than the reserved amount. This can happen if:
- The owner overfunds the distributor
- Tokens are accidentally sent to the contract
- A distribution is canceled and the remaining balance should be reclaimed
The ownerWithdrawUnclaimed() function only allows withdrawing tokens above the reserved amount. This preserves recipient entitlements while still allowing operational cleanup.
Best practices for production use
Use a Merkle tree for large recipient sets
If you need to support thousands of recipients, storing every allocation on-chain may become expensive. A Merkle-based claim system can reduce storage costs by storing only a root hash and verifying proofs at claim time.
Use the mapping-based version when:
- The recipient set is moderate
- Simplicity and auditability matter more than gas optimization
- You want easy on-chain introspection
Use a Merkle-based version when:
- The recipient list is large
- You need lower deployment cost
- Off-chain generation of proofs is acceptable
| Approach | Pros | Cons |
|---|---|---|
| Mapping-based allocations | Simple, transparent, easy to audit | Higher storage cost |
| Merkle claims | Scales well for large lists | More complex off-chain tooling |
| Push distribution | Immediate payout | Gas-heavy and failure-prone |
Protect against duplicate claims
The claimed mapping prevents double withdrawals. In some designs, you can instead zero out the allocation after a claim. Either approach works, but a separate claimed flag makes the intent explicit and helps preserve historical allocation data.
Validate inputs carefully
Always check:
- Recipient addresses are non-zero
- Amounts are non-zero
- Array lengths match
- Allocation entries are not duplicated
These checks reduce accidental misconfiguration and make failures easier to diagnose.
Emit events for every important action
Events are critical for:
- Frontend claim tracking
- Indexing by analytics tools
- Auditing distribution history
- Reconstructing state off-chain
At minimum, emit events for allocation setup, claims, and withdrawals.
Keep claim logic minimal
The claim path should do as little as possible:
- No external calls before state updates
- No loops over other recipients
- No optional business logic that can fail unexpectedly
A minimal claim path is easier to test and less likely to break under edge cases.
Example workflow
A typical deployment and usage flow looks like this:
- Deploy the ERC20 token.
- Deploy the distributor with the token address.
- Call
setAllocations()to register recipients. - Transfer enough tokens to the distributor, or call
fund(). - Recipients call
claim()individually. - After the distribution ends, the owner withdraws any excess tokens.
This workflow is practical for a treasury or operations team because it separates setup, funding, and claiming into distinct steps.
Testing scenarios you should cover
When writing tests, focus on the following cases:
- A recipient can claim exactly once
- A second claim reverts
- Claims fail when the contract is underfunded
- The owner cannot overwrite an existing allocation
ownerWithdrawUnclaimed()cannot drain reserved funds- Zero-address recipients are rejected
- Mismatched input array lengths revert
If your token is non-standard, also test that SafeERC20 handles it correctly.
When to extend this pattern
You may want to extend the distributor with:
- Claim deadlines to enforce a distribution window
- Admin cancellation for revoked allocations
- Per-recipient metadata for notes or categories
- Upgradeable storage layout if the contract must evolve over time
- Merkle proof verification for very large distributions
Be cautious with feature creep. Every new rule adds more edge cases and more audit surface.
Common mistakes to avoid
- Using a push loop for large distributions
This can fail when gas limits are exceeded.
- Forgetting to reserve tokens before withdrawal
Always compare contract balance against unclaimed obligations.
- Allowing allocation overwrites without controls
This can create accounting errors or disputes.
- Putting too much logic inside
claim()
Keep the claim path deterministic and small.
- Ignoring token transfer quirks
Use SafeERC20 rather than raw transfer calls.
Conclusion
A pull-based ERC20 distributor is a reliable pattern for token rewards and payouts. It scales better than push-based loops, reduces operational risk, and gives recipients control over when they claim. With careful accounting, safe token transfers, and minimal claim logic, you can build a distributor that is both practical and easy to audit.