
Summary: Scaling user acquisition and operational throughput in Web3 requires managing both gas costs and RPC latency. Rate-limiting token distribution through time-locked faucets protects initial testnet or launch supplies against sybil draining. For mass airdrops, replacing on-chain storage arrays with Merkle Trees reduces contract deployment overhead from storage slots to a single 32-byte root hash, offloading proof generation to the client. On the interaction layer, MultiCall aggregates dozens of independent read or write operations into a single execution frame, turning high-latency sequential RPC calls into atomic batch transactions. This guide walks through time-locked faucets, Merkle proof verification, and MultiCall routers using Foundry.
1. Rate-Limiting Asset Distribution: The Cooldown Faucet
Gas economy of scale: Merkle trees offload storage overhead off-chain while maintaining cryptographic proof on-chain.
Faucets provide controlled token allotments for testnets, onboarding incentives, or game loops. Without access gating or rate limiting, automated bots can drain reserves in a single block.
From the open-source repository imminer668/Solidity-Guide (foundry_projects/07_distribution/28_Faucet/src/raw/Faucet.sol):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {IERC20} from "./IERC20.sol";
error CooldownNotElapsed(uint256 nextAvailableTimestamp);
error FaucetEmpty();
error TransferFailed();
contract Faucet {
IERC20 public immutable token;
uint256 public constant DRIP_AMOUNT = 100 * 10**18; // 100 tokens
uint256 public constant COOLDOWN_PERIOD = 1 days;
mapping(address => uint256) public lastDripTime;
event Dripped(address indexed recipient, uint256 amount);
constructor(address _tokenAddress) {
token = IERC20(_tokenAddress);
}
function requestTokens() external {
uint256 nextAvailable = lastDripTime[msg.sender] + COOLDOWN_PERIOD;
if (block.timestamp < nextAvailable) {
revert CooldownNotElapsed(nextAvailable);
}
if (token.balanceOf(address(this)) < DRIP_AMOUNT) {
revert FaucetEmpty();
}
// 1. Effects: Record timestamp before calling external token transfer
lastDripTime[msg.sender] = block.timestamp;
// 2. Interactions: Execute transfer
bool success = token.transfer(msg.sender, DRIP_AMOUNT);
if (!success) revert TransferFailed();
emit Dripped(msg.sender, DRIP_AMOUNT);
}
}
1.1 Testing Time-Lock Logic with vm.warp
In foundry_projects/07_distribution/28_Faucet/test/raw/Faucet.t.sol, testing cooldown windows relies on the vm.warp cheatcode:
function testCannotDripBeforeCooldown() public {
// 1. First claim succeeds
vm.prank(alice);
faucet.requestTokens();
// 2. Second claim in same block reverts
vm.prank(alice);
vm.expectRevert();
faucet.requestTokens();
// 3. Fast-forward time by 24 hours + 1 second
vm.warp(block.timestamp + 1 days + 1);
// 4. Claim succeeds again
vm.prank(alice);
faucet.requestTokens();
}
2. Scaling Whitelists: The Merkle Tree Airdrop
When distributing tokens or whitelist mint entitlements to 50,000 addresses, storing eligible recipients directly in on-chain storage is economically prohibitive: – Storing 50,000 addresses in a mapping consumes . This far exceeds the Ethereum block gas limit (30,000,000), requiring dozens of sequential administrative transactions.
A Merkle Tree solves this by storing only the 32-byte Merkle root on-chain.
[ MERKLE ROOT ] (32 Bytes stored on-chain)
/ \
H(0,1) H(2,3)
/ \ / \
H(0) H(1) H(2) H(3)
| | | |
L(0) L(1) L(2) L(3) <- User address/amount leaves
To claim, the user supplies their leaf data alongside sibling hashes (the Merkle proof). For 50,000 users, a proof requires only 16 hashes ( bytes of calldata).
2.1 Implementing Proof Verification
From foundry_projects/08_offchain_auth/34_MerkleTree/src/raw/MerkleProof.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
library MerkleProof {
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf)
internal
pure
returns (bool)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash == root;
}
// Sort pair before hashing to prevent second-preimage collision attacks
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? keccak256(abi.encodePacked(a, b)) : keccak256(abi.encodePacked(b, a));
}
}
2.2 Merkle Claim Contract
From foundry_projects/08_offchain_auth/34_MerkleTree/src/raw/MerkleTree.sol:
contract MerkleAirdrop {
bytes32 public immutable root;
mapping(address => bool) public hasClaimed;
event Claimed(address indexed account, uint256 amount);
constructor(bytes32 _root) {
root = _root;
}
function claim(address account, uint256 amount, bytes32[] calldata proof) external {
require(!hasClaimed[account], "Already claimed");
// 1. Compute leaf from account and allocation amount
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(account, amount))));
// 2. Verify proof against immutable root
require(MerkleProof.verify(proof, root, leaf), "Invalid proof");
// 3. Mark claimed before transfer
hasClaimed[account] = true;
emit Claimed(account, amount);
}
}
Double-hashing the leaf (keccak256(bytes.concat(keccak256(...)))) prevents second-preimage attacks where an attacker crafts an intermediate hash that matches an internal node.
3. High-Throughput Batching: The MultiCall Router
Web applications frequently require fetching multiple pieces of contract state upon page load: account balance, token allowance, staking reward, and protocol reserves. Executing these as individual HTTP JSON-RPC calls introduces round-trip network latency.
MultiCall aggregates these sub-calls into a single on-chain execution loop.
From foundry_projects/08_offchain_auth/38_MultiCall/src/raw/MultiCall.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract MultiCall {
struct Call {
address target;
bool allowFailure;
bytes callData;
}
struct Result {
bool success;
bytes returnData;
}
/// @notice Executes an array of calls, returning an array of results
function multicall(Call[] calldata calls) external returns (Result[] memory returnData) {
uint256 length = calls.length;
returnData = new Result[](length);
for (uint256 i = 0; i < length; i++) {
Call calldata calli = calls[i];
(bool success, bytes memory data) = calli.target.call(calli.callData);
returnData[i] = Result(success, data);
if (!calli.allowFailure && !success) {
revert("MultiCall: call failed");
}
}
}
}
3.1 The Value of allowFailure
allowFailure = false: Enforces strict atomicity. If any single call reverts (e.g., an unauthorized swap), the entire batch reverts.allowFailure = true: Enables best-effort batch reads and writes. If token B’s balance check reverts, token A’s result is still returned cleanly.
4. Testing MultiCall in Foundry
From foundry_projects/08_offchain_auth/38_MultiCall/test/raw/MultiCall.t.sol:
function testBatchAllowanceTransfer() public {
// Prepare calldata for two distinct token approvals
bytes memory call0 = abi.encodeWithSignature(
"transferFrom(address,address,uint256)", alice, bob, 100e18
);
bytes memory call1 = abi.encodeWithSignature(
"transferFrom(address,address,uint256)", alice, charlie, 200e18
);
MultiCall.Call[] memory calls = new MultiCall.Call[](2);
calls[0] = MultiCall.Call({target: address(tokenA), allowFailure: false, callData: call0});
calls[1] = MultiCall.Call({target: address(tokenB), allowFailure: false, callData: call1});
// Execute both in a single transaction
MultiCall.Result[] memory results = multicall.multicall(calls);
assertTrue(results[0].success);
assertTrue(results[1].success);
}
5. Production Systems Context
In production Web3 products: – ChainPunch (中文版): Combines daily check-in windows with cursor-based batch settlement. Instead of looping across all participants in a single transaction, the coordinator records task rules and allows participants to claim rewards independently on-chain (see Preserving Challenge Rules After Participants Join). – NOVA Membership (中文版): Uses Merkle roots to manage seasonal guest passes and promotional invitation trees without writing large address lists to storage slots.
Review live systems on the Fone Products Center (中文版) or read technical notes on Fone Insights.
Mass Distribution Architecture Comparison (10,000 Recipients)
| Distribution Architecture | On-Chain Setup Gas | Per-Recipient Claim Gas | Who Pays Gas? | Scalability & Trade-offs |
|---|---|---|---|---|
Push Loop (airdropBatch) |
0 setup | ~28,000 gas per recipient (~280M gas total) | Project Treasury | Hits block gas limit above ~500 recipients per tx; requires multi-tx chunking |
| On-Chain Allowlist Mapping | ~22,000 gas $ imes$ 10,000 ( 220M gas) | ~45,000 gas | Both (Heavy setup) | Prohibitive setup cost for large whitelists |
| Merkle Tree Pull Airdrop | 1 SSTORE (bytes32 root, ~22,100 gas) |
~52,000 gas ( hashes) | Claiming User | Scales to 1,000,000+ users with constant 32-byte on-chain storage |
| BitMap Merkle Airdrop | 1 SSTORE (bytes32 root, ~22,100 gas) |
~38,000 gas (256 claims per slot) | Claiming User | Optimal production pattern; packs 256 boolean flags into each uint256 word |
Verify It Locally with Foundry
Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/08_offchain_auth/34_MerkleTree):
# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide
# 2. Run the verified Foundry test suite for this module
cd foundry_projects/08_offchain_auth/34_MerkleTree && forge test -vvv
Expected local verification output:
[PASS] test_ClaimWithValidMerkleProof() (gas: 54120)
[PASS] test_RevertWhen_InvalidProof() (gas: 18940)
Suite result: ok. 2 passed; 0 failed; 0 skipped
Frequently Asked Questions (Technical FAQ)
Why must Merkle leaves be double-hashed (keccak256(bytes.concat(keccak256(abi.encode(...))))) in production?
Double-hashing prevents second preimage attacks where an attacker crafts a 64-byte leaf input that matches the concatenation of two internal 32-byte sibling nodes, allowing them to forge a proof for an internal tree node as if it were a leaf.
Why is msg.value dangerous inside a delegatecall-based Multicall function?
Because delegatecall preserves msg.value across every sub-call in the batch loop. If a contract function credits msg.value to the caller’s balance and exposes a multicall(bytes[]) helper, an attacker can send 1 ETH once and invoke deposit() 10 times inside a single multicall to credit 10 ETH.
How does a BitMap save gas over mapping(address => bool) in Merkle airdrops?
A mapping(address => bool) initializes a brand-new 32-byte storage slot (0 -> 1 cold SSTORE costing 22,100 gas) for every user. A mapping(uint256 => uint256) bitmap stores 256 claim flags per slot; once the first user in a 256-user bucket claims, the other 255 users update a non-zero slot (SSTORE costing only 5,000 gas).
Series & Related Engineering Guides
- Previous Lesson (S10): Off-Chain Authorization in Solidity: ECDSA Signatures, EIP-712 Typed Data, and ERC20Permit (EIP-2612)
- Next Lesson (S12): Treasury & Tokenomics Contracts in Solidity: PaymentSplit, TokenVesting, TokenLocker, and Timelock Governance
- Companion Security & Architecture Deep-Dive (T02): Raw Solidity vs. OpenZeppelin v5: Code Size, Gas, and Security Trade-offs Across 15 Protocols
- Production Engineering Case Study: Preventing Sybil Abuse in On-Chain Referral Systems
- Open-Source Codebase: imminer668/Solidity-Guide (
foundry_projects/08_offchain_auth/34_MerkleTree) - Commercial Platforms & Advisory: Fone Products Center (中文版) | Fone Services | Contact Engineering