
In Web3 community growth, bootcamp study cohorts, fitness check-ins, and stake-backed habit challenges (Cohort Wagering Challenges), one of the most damaging contract failures is a Single-Transaction Settlement Loop. Suppose a 21-day early-rising challenge attracts 1,000 members who each stake 100 USDT. At the end, a settlement function uses a for loop over all 1,000 participants, counts check-ins, calculates penalties, totals perfect-attendance weights, and calls token.transfer() to distribute rewards. EVM execution can easily exceed the Ethereum or Layer-2 block gas limit, such as 30,000,000 Gas. The transaction necessarily reverts with Out of Gas. Without batch checkpoints, the entire pool remains permanently locked in an unresolvable settlement.
External token-transfer failures create an even more dangerous denial of service (DoS via Token Revert). If just one of the 1,000 participants is blacklisted by the stablecoin contract or is a malicious contract without the required token-reception hook, a single failed transfer() inside the loop reverts settlement for everyone. The other 999 honest participants can never recover their principal and rewards.
To handle settlement for tens of thousands of participants without gas exhaustion, isolate individual failures, and conserve every unit of distributed funds, ChainPunch implements Two-Phase Batched Settlement via Cursors and Pull over Push Withdrawal in production. This article examines the complete Solidity implementation, Foundry stress tests, and frontend state machine.
Architecture: From UTC Day Boundaries to Two-Phase Settlement

ChainPunch divides the challenge lifecycle into configuration, UTC-day check-ins and makeups, two-phase batch settlement, and individual withdrawals:
+-----------------------------------------------------------------------------------+
| ChainPunch Full-Stack Challenge Pipeline |
+-----------------------------------------------------------------------------------+
| 1. Task Creation and UTC Normalization (Lifecycle Configuration) |
| - Align start to UTC midnight: normalizedStartDate = (startDate / 1 days) * 1d |
| - Check daily window: currentTime = timestamp % 1 days, [dailyStart, dailyEnd] |
| - Penalties: Mode 1 (full forfeiture for any absence) vs Mode 2 (proportional) |
+-----------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------------+
| 2. Daily Check-In and Paid Makeup |
| - dailyCheckIn[user][dayIndex] flags; consecutiveCheckIns tracks streaks |
| - Makeup rules: past missed days only, before task end, count <= duration/10, pay makeupFee |
+-----------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------------+
| 3. Two-Phase Batch Settlement State Machine |
| [Phase 1: collectStatistics] |
| - SETTLEMENT_BATCH_SIZE = 100; accumulate penalties in pool and attendance weight |
| - finishStatistics: deduct platform/creator fees; credit statistics work rewards |
| ----------------------------------------------------------------------------- |
| [Phase 2: distributeRewards] |
| - Advance cursor; calculate principal + weighted reward: Math.mulDiv(rewards, w, weight) |
| - Conservation: decrement remainingRewards / remainingWeight; last user absorbs dust |
| - Worker rewards: 80% by work performed; 20% completionBonus to final caller |
+-----------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------------+
| 4. Independent Creator and User Withdrawals (Non-Reentrant Pull Claim) |
| - Separate balance accounting: claimable[taskId][user] += earned |
| - withdrawTaskFunds affects only the caller; one failure never blocks others |
+-----------------------------------------------------------------------------------+
Architecture Tradeoffs: Why Settle On-Chain in Batches?
For community competitions or check-in wagers with hundreds or thousands of participants, common approaches compare as follows:
| Architecture | Block Gas Risk | Immunity to Token-Blacklist DoS | Decentralization and Censorship Resistance | Operations and Off-Chain Signing Cost |
|---|---|---|---|---|
| Single-transaction Push loop | Very high (>300 users causes Out of Gas lockup) | 0% (one failure blocks the whole pool) | High (entirely smart contracts) | 0 (no off-chain maintenance) |
| Off-chain calculation + Merkle claims | Very low (update only the Merkle Root) | 100% (independent Proof withdrawals) | Very low (operator can alter off-chain check-ins) | Very high (persistent database and proof-generation API) |
| ChainPunch two-phase cursor settlement (Accrual + Pull) | Zero risk (fixed 100-record batches, Gas < 8 million) | 100% (independent credits and user withdrawals) | Very high (entirely autonomous on-chain rules) | Low (any Keeper or user can earn gas reimbursement rewards) |
Inside CheckInTask.sol
All check-in, penalty, and distribution logic in CheckInTask.sol is driven by timestamp arithmetic and a state machine.
1. UTC Day Normalization and Input Validation
At the blockchain level, block.timestamp is a continuously increasing Unix timestamp in seconds. Unnormalized local times create substantial confusion for participants across time zones. At the createTask entry point, ChainPunch truncates startDate to UTC midnight:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
contract CheckInTask is ReentrancyGuard {
using SafeERC20 for IERC20;
IERC20 public immutable token;
bool public paused;
address public owner;
uint256 public constant SETTLEMENT_BATCH_SIZE = 100; // Maximum records per settlement transaction
uint256 public constant PROGRESS_REWARD_PERCENT = 80;
uint256 public constant MAX_DURATION = 365; // Maximum 365 days
uint256 public constant MIN_STAKE_AMOUNT = 1e15; // Minimum stake
uint256 public platformFeeRate = 1; // Default 1%
uint256 public platformFeeAccumulated;
struct Task {
address creator;
uint256 stakeAmount;
uint256 maxParticipants;
uint256 endTime;
uint256 participantsCount;
bool claimed;
uint256 penaltyMode; // 1: Any absence forfeits the full stake; 2: Proportional deduction by missed days
address[] participants;
mapping(address => uint256) stake;
mapping(address => mapping(uint256 => bool)) dailyCheckIn;
uint256 dailyStartTime; // Daily check-in start in seconds (UTC 0 ~ 86400)
uint256 dailyEndTime; // Daily check-in end in seconds
uint256 startDate; // Normalized UTC midnight timestamp
mapping(address => uint256) consecutiveCheckIns;
mapping(address => uint256) lastCheckInDay;
uint256 maxMakeups; // Maximum makeups (<= duration / 10)
uint256 makeupFee; // Makeup fee as a percentage of stake
mapping(address => uint256) makeupCount;
uint256 claimRewardRate; // Settlement worker reward rate (e.g. 5%)
uint256 creatorFeeRate; // Creator management fee rate (e.g. 10%)
mapping(address => uint256) totalCheckIns;
string title;
string description;
uint256 platformFeeRate; // Platform rate locked at creation
uint256 makeupFeesCollected;
mapping(address => bool) joined;
mapping(address => uint256) rewardAllocated;
bool settling;
bool refundPool;
uint256 remainingRewards;
uint256 remainingWeight;
uint256 settlementCursor; // Distribution cursor
}
struct Settlement {
bool statisticsComplete;
uint256 statisticsCursor; // Statistics cursor
uint256 totalStake;
uint256 totalWeight;
uint256 pool;
uint256 distributionReward;
uint256 completionReward;
uint256 distributionRewardAllocated;
address[] statisticsWorkers;
uint256[] statisticsWork;
}
mapping(uint256 => Task) public tasks;
mapping(uint256 => Settlement) public settlements;
mapping(uint256 => mapping(address => uint256)) public claimable;
mapping(uint256 => mapping(address => uint256)) public withdrawn;
uint256 public taskCount;
createTask checks that the start date falls within the next 30 days and deterministically aligns it to UTC midnight by dividing by 1 days and then multiplying by 1 days:
function createTask(TaskParams calldata params) external notPaused nonReentrant {
require(params.stakeAmount >= MIN_STAKE_AMOUNT, "Stake amount too low");
require(params.maxParticipants > 0 && params.maxParticipants <= 1000, "Invalid participants range");
require(params.duration > 0 && params.duration <= MAX_DURATION, "Invalid duration");
require(params.penaltyMode == 1 || params.penaltyMode == 2, "Invalid penalty mode");
require(params.dailyStartTime < params.dailyEndTime, "Invalid time window");
require(params.dailyStartTime < 24 hours && params.dailyEndTime < 24 hours, "Invalid time");
require(params.maxMakeups <= params.duration / 10, "Too many makeups allowed");
// Normalize the start date to UTC midnight
uint256 normalizedStartDate = (params.startDate / 1 days) * 1 days;
require(normalizedStartDate >= block.timestamp, "Start date cannot be in the past");
require(normalizedStartDate <= block.timestamp + 30 days, "Start date too far in the future");
taskCount++;
Task storage newTask = tasks[taskCount];
newTask.creator = msg.sender;
newTask.stakeAmount = params.stakeAmount;
newTask.maxParticipants = params.maxParticipants;
newTask.endTime = normalizedStartDate + params.duration * 1 days;
newTask.startDate = normalizedStartDate;
newTask.dailyStartTime = params.dailyStartTime;
newTask.dailyEndTime = params.dailyEndTime;
newTask.penaltyMode = params.penaltyMode;
newTask.maxMakeups = params.maxMakeups;
newTask.makeupFee = params.makeupFee;
newTask.platformFeeRate = platformFeeRate;
newTask.claimRewardRate = params.claimRewardRate;
newTask.creatorFeeRate = params.creatorFeeRate;
newTask.title = params.title;
newTask.description = params.description;
emit TaskCreated(taskCount, msg.sender, params.stakeAmount, newTask.endTime, ...);
}
2. Check-In Validation and Makeup Anti-Abuse Rules
Daily check-in computes currentDay from the number of days since the task started. The modulo operation block.timestamp % 1 days gives the offset within the day, which must fall within [dailyStartTime, dailyEndTime]:
function checkIn(uint256 _taskId) external notPaused nonReentrant validTaskId(_taskId) {
Task storage task = tasks[_taskId];
require(task.stake[msg.sender] > 0, "Not a participant");
require(block.timestamp < task.endTime, "Task has ended");
require(block.timestamp >= task.startDate, "Task has not started");
// Extract seconds within the day and validate the check-in window
uint256 currentTime = block.timestamp % 1 days;
require(currentTime >= task.dailyStartTime && currentTime <= task.dailyEndTime, "Not in check-in time window");
uint256 currentDay = (block.timestamp - task.startDate) / 1 days;
require(!task.dailyCheckIn[msg.sender][currentDay], "Already checked in today");
task.dailyCheckIn[msg.sender][currentDay] = true;
// Maintain the consecutive check-in counter
if (currentDay > 0 && task.dailyCheckIn[msg.sender][currentDay - 1]) {
task.consecutiveCheckIns[msg.sender]++;
} else {
task.consecutiveCheckIns[msg.sender] = 1;
}
task.lastCheckInDay[msg.sender] = task.startDate / 1 days + currentDay;
task.totalCheckIns[msg.sender]++;
emit UserCheckedIn(_taskId, msg.sender, currentDay);
}
The makeup logic imposes four rules against Sybil activity and opportunistic abuse:
- No future makeups:
_day < currentDayprevents checking in ahead of time for today or a future day. - No duplicate check-ins:
!task.dailyCheckIn[msg.sender][_day]prevents a makeup from inflating a day already recorded. - Strict count limits:
makeupCount < maxMakeups, capped at 10% of the total duration. - Real payment required:
makeupFee = stakeAmount * task.makeupFee / 100. Makeup fees enter the total reward pool as additional returns for participants who finish with full attendance.
function makeup(uint256 _taskId, uint256 _day) external notPaused nonReentrant validTaskId(_taskId) {
Task storage task = tasks[_taskId];
require(task.stake[msg.sender] > 0, "Not a participant");
require(block.timestamp < task.endTime, "Task has ended");
require(block.timestamp >= task.startDate, "Task has not started");
uint256 currentDay = (block.timestamp - task.startDate) / 1 days;
require(_day < currentDay, "Cannot makeup for future or today");
require(!task.dailyCheckIn[msg.sender][_day], "Already checked in for this day");
require(task.makeupCount[msg.sender] < task.maxMakeups, "No makeup chances left");
uint256 fee = (task.stakeAmount * task.makeupFee) / 100;
if (fee > 0) {
uint256 beforeBalance = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), fee);
require(token.balanceOf(address(this)) - beforeBalance == fee, "Unsupported token transfer fee");
}
task.makeupFeesCollected += fee;
task.dailyCheckIn[msg.sender][_day] = true;
task.makeupCount[msg.sender]++;
task.totalCheckIns[msg.sender]++;
emit UserMadeup(_taskId, msg.sender, _day);
}
3. Two-Phase Cursor Settlement: Eliminating Out of Gas
Once the task ends (block.timestamp >= endTime), settlement begins. ChainPunch splits settlement into two phases, with each transaction processing at most SETTLEMENT_BATCH_SIZE = 100 records.
Any on-chain user or Keeper bot can call claimTask to advance settlement. To reward third parties for processing large datasets, 80% of claimReward is distributed by progress (40% each for statistics and distribution), proportionally to records processed in each phase. The remaining 20%, completionReward, goes to the caller who completes settlement.
function claimTask(uint256 _taskId) external nonReentrant validTaskId(_taskId) {
Task storage task = tasks[_taskId];
require(block.timestamp >= task.endTime, "Task is not finished yet");
require(!task.claimed, "Task already claimed");
Settlement storage settlement = settlements[_taskId];
// Initialize settlement context
if (!task.settling) {
require(!paused, "Contract is paused");
task.settling = true;
settlement.pool = task.makeupFeesCollected;
task.makeupFeesCollected = 0;
}
uint256 totalDays = (task.endTime - task.startDate) / 1 days;
// Phase 1: Statistics
if (!settlement.statisticsComplete) {
collectStatistics(_taskId, task, settlement, totalDays);
if (task.participantsCount == 0) {
task.claimed = true;
emit TaskClaimed(_taskId, msg.sender);
}
return; // Never execute both phases in the same transaction
}
// Phase 2: Distribution
distributeRewards(_taskId, task, totalDays);
// Credit the settlement worker's progress reward
uint256 earned = Math.mulDiv(settlement.distributionReward, task.settlementCursor, task.participantsCount);
credit(_taskId, msg.sender, earned - settlement.distributionRewardAllocated);
settlement.distributionRewardAllocated = earned;
// Complete the entire settlement
if (task.settlementCursor == task.participantsCount) {
task.claimed = true;
credit(_taskId, msg.sender, settlement.completionReward); // Award the completion bonus
emit TaskClaimed(_taskId, msg.sender);
}
emit SettlementProgress(_taskId, task.settlementCursor, task.participantsCount);
}
Phase 1: Statistics (collectStatistics)
The cursor advances from statisticsCursor to min(cursor + 100, participantsCount), performing only state reads and penalty calculations. Because the final penalty pool is not yet known, this phase records each caller’s work contribution:
function collectStatistics(uint256 taskId, Task storage task, Settlement storage settlement, uint256 totalDays) internal {
uint256 from = settlement.statisticsCursor;
uint256 end = Math.min(from + SETTLEMENT_BATCH_SIZE, task.participantsCount);
for (uint256 i = from; i < end; i++) {
address user = task.participants[i];
uint256 stake = task.stake[user];
if (stake == 0) continue; // Skip users who exited through emergency withdrawal
uint256 penalty = calculatePenalty(task, user, totalDays);
settlement.pool += penalty;
settlement.totalStake += stake;
// Accumulate eligible distribution weight
settlement.totalWeight += task.penaltyMode == 1
? (task.totalCheckIns[user] == totalDays ? 1 : 0)
: task.totalCheckIns[user];
if (penalty > 0) emit UserPunished(taskId, user, penalty);
}
settlement.statisticsCursor = end;
if (end > from) {
settlement.statisticsWorkers.push(msg.sender);
settlement.statisticsWork.push(end - from);
}
// Finalize accounting when statistics are complete
if (end == task.participantsCount) {
finishStatistics(taskId, task, settlement);
}
emit StatisticsProgress(taskId, end, task.participantsCount);
}
Once statistics are complete, finishStatistics fixes the final pool, allocates platform and creator fees proportionally, and credits each statistics worker’s gas reimbursement reward:
function finishStatistics(uint256 taskId, Task storage task, Settlement storage settlement) internal {
uint256 pool = settlement.pool;
uint256 platformFee = Math.mulDiv(pool, task.platformFeeRate, 100);
uint256 claimReward = Math.mulDiv(pool, task.claimRewardRate, 100);
uint256 creatorFee = Math.mulDiv(pool, task.creatorFeeRate, 100);
// If everyone is eliminated (totalWeight == 0), refund proportionally to original stakes
task.refundPool = settlement.totalWeight == 0;
task.remainingWeight = task.refundPool ? settlement.totalStake : settlement.totalWeight;
task.remainingRewards = pool - platformFee - claimReward - creatorFee;
settlement.statisticsComplete = true;
platformFeeAccumulated += platformFee;
credit(taskId, task.creator, creatorFee);
// Distribute statistics-phase rewards
uint256 progressReward = Math.mulDiv(claimReward, PROGRESS_REWARD_PERCENT, 100);
uint256 statisticsReward = progressReward / 2;
settlement.distributionReward = progressReward - statisticsReward;
settlement.completionReward = claimReward - progressReward;
uint256 processed;
uint256 allocated;
for (uint256 i; i < settlement.statisticsWorkers.length; i++) {
processed += settlement.statisticsWork[i];
uint256 earned = Math.mulDiv(statisticsReward, processed, task.participantsCount);
credit(taskId, settlement.statisticsWorkers[i], earned - allocated);
allocated = earned;
}
}
Phase 2: Distribution (distributeRewards) and Decrementing-Balance Conservation
During distribution, settlementCursor also advances in steps of 100. For each eligible participant, the system calculates returned principal (principal = stake - penalty) and the pool bonus (bonus).
The key mathematical design is decrementing the remaining balances: bonus = Math.mulDiv(remainingRewards, weight, remainingWeight) remainingRewards ← remainingRewards − bonus remainingWeight ← remainingWeight − weight
For the last eligible participant, weight = remainingWeight, so the result must be bonus = remainingRewards. All small integer-division remainders (Rounding Dust) therefore accrue naturally to that participant. No unclaimable orphan funds remain in the contract, preserving the exact token total:
function distributeRewards(uint256 _taskId, Task storage task, uint256 totalDays) internal {
uint256 end = task.settlementCursor + SETTLEMENT_BATCH_SIZE;
if (end > task.participantsCount) end = task.participantsCount;
for (uint256 i = task.settlementCursor; i < end; i++) {
address user = task.participants[i];
uint256 stake = task.stake[user];
if (stake == 0) continue;
uint256 principal = stake - calculatePenalty(task, user, totalDays);
uint256 weight = task.refundPool ? stake : (task.penaltyMode == 1
? (task.totalCheckIns[user] == totalDays ? 1 : 0)
: task.totalCheckIns[user]);
uint256 bonus;
if (weight > 0) {
// Decrementing balances let the last eligible user absorb all rounding dust
bonus = Math.mulDiv(task.remainingRewards, weight, task.remainingWeight);
task.remainingRewards -= bonus;
task.remainingWeight -= weight;
}
task.stake[user] = 0; // Zero the stake
uint256 reward = principal + bonus;
task.rewardAllocated[user] = reward;
// Credit the individual claimable balance; no external ERC-20 transfer here
credit(_taskId, user, reward);
emit RewardAllocated(_taskId, user, reward, 0, bonus);
}
task.settlementCursor = end;
}
4. Pull Withdrawals and Blacklist Isolation
During settlement, the contract only increments claimable[taskId][user] through its internal credit function. It never sends external transfers. Creators, participants, and Keepers can call withdrawTaskFunds at any time to withdraw their credited funds:
function withdrawTaskFunds(uint256 _taskId) external nonReentrant validTaskId(_taskId) {
uint256 amount = claimable[_taskId][msg.sender];
require(amount > 0, "Nothing to withdraw");
claimable[_taskId][msg.sender] = 0; // Follow Checks-Effects-Interactions
withdrawn[_taskId][msg.sender] += amount;
token.safeTransfer(msg.sender, amount);
emit TaskFundsWithdrawn(_taskId, msg.sender, amount);
}
This provides a decisive security benefit: if a participant’s wallet is sanctioned and blacklisted, or reverts while receiving tokens, only that address’s own withdrawTaskFunds call fails. Reward calculation, settlement progress, and withdrawals for the other 999 users are entirely unaffected.
Frontend State and Interaction: ethers.js with 10-Second Polling
ChainPunch uses Next.js and useChainData for lightweight awareness of on-chain state.
1. Independent Withdrawals Without Approve
Many Web3 frontends incorrectly ask users to submit an ERC-20 approve transaction before withdrawing. In ChainPunch, withdrawTaskFunds retrieves assets already accounted for in the contract’s claimable balance; no token approval is needed. Frontend tests strictly assert that withdrawal requests initiate no token authorization:
// Excerpt from CheckInTask_Frontend/utils/contract.js
export async function withdrawTaskFunds(signer, id, onProgress, signal) {
const contract = await writeContract(signer);
onProgress?.('请在钱包确认提取本任务的全部待提现金额,无需代币授权。');
return confirm(signer, () => contract.withdrawTaskFunds(id), onProgress, signal);
}
2. Two Progress Bars for Settlement (SettlementPanel)
A thousand-person challenge may require multiple claimTask calls. The dedicated SettlementPanel shows both the statistics cursor (0~1000) and distribution cursor (0~1000) as progress bars. Any user can click to act as a Keeper and earn a gas reimbursement reward immediately:
// Excerpt from CheckInTask_Frontend/components/SettlementPanel.js
export default function SettlementPanel({ task, disabled, onSettle }) {
const c = useCopy();
return (
<section className="surface space-y-3 settlement-panel">
<h2>{c('结算进度', 'Settlement progress')} · {task.settlementPhase}</h2>
<p>
{c('统计', 'Statistics')} {task.statisticsCursor}/{task.settlementTotal} 条 ·
{c('分配', 'Allocation')} {task.settlementCursor}/{task.settlementTotal} 条
</p>
<progress className="batch-bar" value={task.statisticsCursor} max={task.settlementTotal || 1} />
<progress className="batch-bar" value={task.settlementCursor} max={task.settlementTotal || 1} />
{task.status === 'settlement' && (
<button className="button-primary w-full" disabled={disabled || !task.canSettle} onClick={onSettle}>
{task.settling
? task.statisticsComplete
? c('继续分配 · 最多 100 条', 'Continue allocation · Up to 100')
: c('继续统计 · 最多 100 条', 'Continue statistics · Up to 100')
: c('开始结算 · 统计阶段', 'Begin settlement · Statistics')}
</button>
)}
</section>
);
}
Foundry Tests: Stress Testing and Conservation Fuzzing
ChainPunch includes comprehensive Foundry regression suites (Regression.t.sol and SecurityReview.t.sol) to verify security at extreme boundaries.
1. Maximum-Capacity Gas Test with 1,000 Participants
The test has 1,000 users stake and join, then advances batch settlement after the task ends. It asserts that one 100-person batch consumes strictly less than 8,000,000 Gas, well below Ethereum’s 30-million block limit and inexpensive on Base / Arbitrum:
function testMaximumParticipantsSettlementGas() public {
CheckInTask.TaskParams memory p = CheckInTask.TaskParams({
stakeAmount: 1 ether,
maxParticipants: 1000,
duration: 1,
penaltyMode: 2,
dailyStartTime: 0,
dailyEndTime: 86399,
maxMakeups: 0,
makeupFee: 0,
claimRewardRate: 5,
creatorFeeRate: 10,
startDate: start,
title: "Capacity",
description: ""
});
app.createTask(p);
// Join 1000 participants in a batch
for (uint256 i = 1; i <= 1000; i++) {
address user = address(uint160(1000 + i));
token.transfer(user, 1 ether);
vm.startPrank(user);
token.approve(address(app), 1 ether);
app.joinTask(3);
vm.stopPrank();
}
vm.warp(start + 1 days);
// Measure gas for one settlement batch
uint256 gasBefore = gasleft();
app.claimTask(3);
uint256 used = gasBefore - gasleft();
emit log_named_uint("Settlement gas, 1000 users", used);
assertLt(used, 8000000); // Strictly assert less than 8 million gas
}
2. Fuzzing Reward Conservation
Random check-in masks (uint32 maskA, uint32 maskB) and penalty modes (Mode 1 and Mode 2) simulate attendance and absences over 10 days. After the challenge ends, all participants’ withdrawals plus platform management fees must equal the initial stakes exactly:
function testFuzz_RewardConservation(uint32 maskA, uint32 maskB, uint8 mode) public {
CheckInTask.TaskParams memory p = CheckInTask.TaskParams({
stakeAmount: 100 ether + 7, // Non-divisible amount with a remainder
maxParticipants: 2,
duration: 10,
penaltyMode: uint256(mode % 2) + 1,
dailyStartTime: 0,
dailyEndTime: 86399,
maxMakeups: 0,
makeupFee: 0,
claimRewardRate: 5,
creatorFeeRate: 10,
startDate: start,
title: "Conservation",
description: ""
});
app.createTask(p);
vm.prank(alice); app.joinTask(3);
vm.prank(bob); app.joinTask(3);
uint256 initial = token.balanceOf(alice) + token.balanceOf(bob) + token.balanceOf(address(this));
// Check in using random masks
for (uint256 day; day < 10; day++) {
vm.warp(start + day * 1 days + 1);
if ((maskA & (1 << day)) != 0) { vm.prank(alice); app.checkIn(3); }
if ((maskB & (1 << day)) != 0) { vm.prank(bob); app.checkIn(3); }
}
vm.warp(start + 10 days);
settleAndWithdraw(3);
uint256 paid = token.balanceOf(alice) + token.balanceOf(bob) + token.balanceOf(address(this)) - initial;
// Assert exact conservation: total paid + retained platform fees == initial stakes
assertEq(paid + app.platformFeeAccumulated(), 200 ether + 14);
}
3. Isolating Blocked Participants and Creators
The test blacklists a creator or participant in the underlying token contract (token.blockRecipient(CREATOR)). Batch settlement must still finish, and an unblocked participant must still withdraw 84 ether. The failure remains confined to one user:
function testBlockedCreatorDoesNotBlockSettlementOrOthersWithdrawals() public {
token.blockRecipient(CREATOR); // Simulate a sanctioned creator address
vm.warp(START + 1 days);
finish(1, KEEPER); // The entire settlement still completes
assertEq(funds().claimable(1, CREATOR), 1010 ether);
// Creator withdrawal reverts because the recipient is blocked
vm.prank(CREATOR);
vm.expectRevert("Recipient blocked");
funds().withdrawTaskFunds(1);
// An ordinary unblocked user can withdraw without interference
withdraw(1, userAt(0));
assertEq(token.balanceOf(userAt(0)), 84 ether);
}
Four Production Rules for On-Chain Community Growth Tools
If you are designing a Web3 study cohort, stake-refund check-in wager, or long-term engagement incentive, enforce these four requirements during architecture review:
- Never iterate over all users in one transaction: Set a fixed batch size, such as 100, and persist progress in an on-chain cursor to keep gas within a controlled safety range.
- Separate statistics from distribution: Never distribute rewards before calculating the complete penalty pool and total weight. Freeze the full dataset before computing returns per unit of weight.
- Use Pull Claims: Settlement computes and writes the
claimableledger mapping; users initiate physical token transfers. Decoupled accounting prevents malicious DoS through token blacklists. - Absorb rounding through decrementing balances: With discrete integer arithmetic, avoid a separate dust-adjustment scheme. Reduce the remaining reward pool and weight after each allocation so the last eligible user automatically absorbs 1-wei remainders and token conservation holds.
Enterprise Web3 Growth Systems and Architecture Consulting
Fone provides full-stack implementation from complex on-chain economic models and cursor state machines to responsive DApp frontends. If you are building community referrals, DAO contribution incentives, or need gas optimization and security review for existing high-concurrency contracts, we can help:
- Explore the on-chain habit-wagering and challenge prototype: ChainPunch Demo
- Explore enterprise referral memberships and entitlements: NOVA Membership
- Read about wallet state machines and failure handling: Wallet login: design the failure states first and Build an Idempotent Order API
- Book a project assessment with a senior Web3 architect: Contact the Fone Engineering Team