Repository navigation
feat(contracts): testnet faucet for ad-hoc TOKEN distribution - #655
Conversation
…estnet Adds a per-address TOKEN faucet for testnet onboarding (closes #636, poc-blocking). The faucet lives under contracts/testnet/ — deliberately outside contracts/src/ so it cannot be mistaken for production code. A CI grep gate in solidity-build-test fails any PR that references TestnetFaucet from contracts/src/ or from any contracts/script/*.s.sol other than the testnet deploy script itself. Aligns with #452 "Out of the audited 14-contract surface". Contract surface (mirrors StakingRegistry's composition style): - AccessControl + ReentrancyGuard + Pausable - DEFAULT_ADMIN_ROLE grants / revokes; GOVERNANCE_ROLE owns setClaimAmount / setCooldown / withdraw; PAUSER_ROLE owns pause / unpause. - Constructor pulls initialFunding from the treasury via safeTransferFrom — atomic deploy+fund — and reverts on every zero-address / zero-amount arg. - claim() enforces a per-address cooldown with a sentinel for first-time claims; emits Claimed; CEI ordering with ReentrancyGuard as the authoritative guard. - timeUntilNext(address) view helper for clients deciding whether to surface a claim button. - withdraw is intentionally pause-independent so governance can drain a paused faucet without unpausing. - USDC is not in scope; Circle's Sepolia faucet covers that path. Tests — 36 cases, 1024 fuzz runs on cooldown boundary, 100% coverage (lines / statements / branches / funcs): - Constructor happy path + zero-* revert sweep; cooldown == 0 allowed. - claim happy path, partial-cooldown revert with exact remaining, succeeds after warp, per-caller independence, insufficient-balance revert, EnforcedPause, reentrancy via MaliciousERC20 mock. - testFuzz_claim_cooldownBoundary asserts strict iff delta >= cooldown with lastClaimedAt invariant on revert. - Governance setters: only-role, value persistence, events. - withdraw: only-role, pause-independence, zero/insufficient reverts. - Pause/unpause and grant/revoke role coverage. Tooling: - contracts/script/TestnetFaucet.s.sol deploys with env-driven config (defaults: 1000 TOKEN per 24h); broadcasts approve+deploy as treasury. - contracts/foundry.toml: testnet/ kept outside src; transitive compilation via script + tests pulls it into the build graph. Comment records the separation rationale. - contracts/package.json: solhint glob extended to cover testnet/ + script/. - contracts/.gas-snapshot: regenerated with the new 36 cases. - docs/runbook.md: new "Testnet faucet" section documenting testnet-only status, pre-funding source, and the withdraw escape hatch. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Contracts coverageLine coverage: 87.50% (168/192 lines) |
Gas snapshotGas changes vs baseRun: 26253062680 |
There was a problem hiding this comment.
Code Review
This pull request introduces a TestnetFaucet contract for testnet token distribution, featuring role-based access control, claim cooldowns, and pausing functionality. The implementation includes a deployment script, a comprehensive test suite covering fuzzing and reentrancy, and updated operational documentation. Feedback was provided to optimize gas efficiency by reordering function modifiers in the claim and withdraw functions to ensure that permission and state checks are evaluated before the reentrancy guard.
Coverage reportTotal: 89.97% (was 89.97%, ▲ +0.01%) — 16800/18672 lines No Rust files changed in this PR. History
|
There was a problem hiding this comment.
Pull request overview
Adds a testnet-only ERC20 faucet (TestnetFaucet) for ad-hoc TOKEN distribution on testnets, with documentation and CI enforcement intended to keep it out of the audited/production deploy surface.
Changes:
- Introduces
contracts/testnet/TestnetFaucet.sol(role-gated, pausable, non-reentrant per-address claim with cooldown) plus a full Foundry test suite. - Adds a dedicated Foundry deploy script (
contracts/script/TestnetFaucet.s.sol) and expands Solidity linting coverage to includetestnet/andscript/. - Adds a CI “grep gate” to ensure
TestnetFaucetreferences don’t leak intocontracts/src/or other deploy scripts, and documents operational use in the runbook.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| docs/runbook.md | Documents testnet-only status, funding model, and operational escape hatch (withdraw). |
| contracts/testnet/TestnetFaucet.sol | Implements the faucet contract (roles, cooldown, pause, withdraw). |
| contracts/test/TestnetFaucet.t.sol | Adds constructor/claim/governance/pause/withdraw tests + fuzz boundary coverage. |
| contracts/script/TestnetFaucet.s.sol | Adds deploy script intended to pre-approve and deploy+fund atomically. |
| contracts/package.json | Extends solhint globs to lint testnet/ and script/ Solidity. |
| contracts/foundry.toml | Documents the intended separation of testnet/ from production src/. |
| contracts/.gas-snapshot | Updates snapshot to include the new faucet tests. |
| .github/workflows/ci.yml | Adds CI grep gate to enforce testnet boundary for TestnetFaucet references. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Three fixes from the PR #655 review pass: 1. **Modifier ordering on `claim` and `withdraw`** (gemini) - `claim()`: `whenNotPaused nonReentrant` (was `nonReentrant whenNotPaused`). When the contract is paused, the cheap `paused` SLOAD now short-circuits before the reentrancy-guard SSTORE on the revert path. - `withdraw()`: `onlyRole(GOVERNANCE_ROLE) nonReentrant` (was `nonReentrant onlyRole`). Unauthorized callers revert on the cheap role check without paying the reentrancy-guard SSTORE. 2. **Deploy script: predicted address used the wrong nonce** (copilot) `vm.startBroadcast(treasury)` broadcasts both the `approve` tx and the `new TestnetFaucet` tx under the treasury sender. The approve consumes nonce N; the contract creation runs at nonce N+1. The prediction used N, so the post-deploy `AddressPredictionMismatch` invariant would have fired on every real deploy. Tests didn't catch this because `vm.prank` only impersonates for one tx, so `address(this)` (the test contract) was the actual CREATE caller — a different code path from `vm.startBroadcast`. Fix: `vm.getNonce(treasury) + 1`. 3. **Deploy script: ERC20 `approve` return value ignored** (copilot) Switched to `SafeERC20.forceApprove`. Reverts loudly on a token whose `approve` returns false instead of silently succeeding and letting the constructor `safeTransferFrom` fail later with a less actionable message. Regenerated `.gas-snapshot` to reflect the modifier reordering (small gas deltas on revert paths). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ate hardening Synthesizes findings from the four-agent PR review on #655. ## Contract (testnet/TestnetFaucet.sol) - **Chain-id guard.** Constructor now reverts `MainnetForbidden` when `block.chainid == 1`. Closes the doc-vs-code gap where the NatSpec claimed "MUST NOT be deployed to mainnet" but the only enforcement was CI/path convention — an operator pointing `forge create` at the file with a mainnet RPC could still deploy. Updated the NatSpec to describe all three layers (chain-id revert, CI grep gate, path convention) accurately. - **`MAX_COOLDOWN = 30 days` upper bound on `cooldown`.** Without it, `setCooldown(type(uint256).max)` (or anything close) made `last + cooldown` overflow on every claimer's next `claim()`, reverting with the unactionable `Panic(0x11)` and bricking `timeUntilNext()` too. The doc claim "blast radius is contained by Pausable" was false here — pause doesn't undo the bad cooldown value. New errors: `CooldownTooLarge(provided, max)` reverted from both the constructor and `setCooldown` when violated. - **Modifier-order comment tightened.** Old wording ("without paying the SSTORE on the pause-revert path") risked implying the SSTORE would persist if ordered wrong. Reworded to clarify the saving is the SSTORE's *execution* cost on the revert path; the end state is identical because reverts roll back any in-progress write. - **Removed over-applied `forge-lint: disable-next-line(block-timestamp)`** at the function-declaration line — covered nothing. ## Deploy script (script/TestnetFaucet.s.sol) - **`forceApprove` comment rewritten.** Old wording said it "reverts loudly on approve returning false", which is not what `forceApprove` primarily does. New comment correctly states its two reasons: USDT-style zero→non-zero allowance handling, and surfacing a `SafeERC20FailedOperation` revert rather than silently returning `false`. ## CI gate (.github/workflows/ci.yml) - **Explicit dir-existence check** before the grep. Previously the `2>/dev/null` + `|| true` combination silently degraded the gate to a no-op if `src/` or `script/` were ever renamed/removed. Now those paths going missing fails the job loudly. - **Documented the deliberate comment-matching behavior.** A future PR that needs to *name* `TestnetFaucet` in a `src/` doc comment should update the gate, not soften it. Inline note pins this. ## Tests (test/TestnetFaucet.t.sol) Added 8 cases (now 44 unit + 2 fuzz, up from 36 + 1; still 100% line / statement / branch / func coverage on the contract): - `test_constructor_revertsOnCooldownExceedingMax` — `> 30 days` reverts `CooldownTooLarge`. - `test_constructor_revertsOnMainnetChainId` — `vm.chainId(1)` reverts `MainnetForbidden`. - `test_constructor_revertsWhenTreasuryNotApproved` — primary failure mode the deploy-script invariants guard against; pins that `safeTransferFrom` is load-bearing. - `test_claim_revertsOneSecondBeforeCooldownBoundary` and `test_claim_succeedsAtExactCooldownBoundary` — pin the inequality direction (`<` vs `<=`) so an off-by-one mutation fails loudly. - `test_setCooldown_revertsOnExceedingMax` and `test_setCooldown_acceptsMaxCooldown` — pin the `setCooldown` cap in both directions. Replaced the single broad-range fuzz `testFuzz_claim_cooldownBoundary` with a paired fuzz: - `testFuzz_claim_belowCooldown` — `delta ∈ [0, COOLDOWN - 1]`, asserts revert with exact `remaining`. - `testFuzz_claim_atOrAboveCooldown` — `delta ∈ [COOLDOWN, 30 days]`, asserts success. Every fuzz run now exercises the boundary the test name claims; the old range made boundary samples a 1-in-2.5M event. Reworded the `MaliciousERC20._update` comment to explain *why* the reentrancy test produces signal: the re-entered `claim()` runs as `msg.sender = address(this)` (the token contract), a fresh address with `lastClaimedAt == 0`, so the cooldown sentinel does NOT short-circuit — `nonReentrant` is the only thing stopping the second `claim()`. Regenerated `.gas-snapshot`. Refs: PR #655 review by gemini-code-assist + copilot-pull-request-reviewer + four-agent triage. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`test_constructor_revertsWhenTreasuryNotApproved` used bare `vm.expectRevert()` which matches any revert — the test comment claimed it pinned `ERC20InsufficientAllowance` from `safeTransferFrom`, but a future regression that triggered an unrelated earlier revert (e.g. a reordered constructor check, or a new fixture combination that hits `ZeroAmount` first) would have silently passed. Now uses `abi.encodeWithSelector(IERC20Errors.ERC20InsufficientAllowance.selector, predicted, 0, INITIAL_FUNDING)` to pin both the selector and all three args (spender, allowance, needed). Flagged in the third PR review pass by two agents independently. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
| // with the CI grep gate and the `contracts/testnet/` path convention, | ||
| // this is the only layer that catches an operator pointing | ||
| // `forge create` directly at this file with a mainnet RPC. | ||
| if (block.chainid == 1) revert MainnetForbidden(); |
There was a problem hiding this comment.
This won't work on Arbitrum one, chain ID is 42161
There was a problem hiding this comment.
We might add that later before deployment. It's apparently enough to gate forge
Closes #636.
Summary
Adds a per-address TOKEN faucet for ad-hoc testnet onboarding. The contract lives under
contracts/testnet/, with a CI grep gate enforcing it can't leak into the production deploy surface (#452). USDC distribution stays Circle's job — out of scope here.What's in the box
Contract (
contracts/testnet/TestnetFaucet.sol) — mirrorsStakingRegistry's composition style:AccessControl(3 roles:DEFAULT_ADMIN_ROLEfor grants,GOVERNANCE_ROLEfor setters +withdraw,PAUSER_ROLEfor pause/unpause) +ReentrancyGuard+Pausable.initialFundingfrom atreasuryaddress viasafeTransferFrom— atomic deploy+fund — with zero-address / zero-amount reverts on every arg.initialCooldown == 0is intentionally allowed (governance may want a no-cooldown burst for a short test; pause is the safety net).claim()enforces per-address cooldown with alastClaimedAt == 0sentinel for first-time callers; CEI ordering withnonReentrantas the authoritative guard; emitsClaimed(claimer, amount). Custom errorsCooldownNotElapsed(remaining)andInsufficientBalance(balance, requested)for actionable client UX.timeUntilNext(address)view helper for clients deciding whether to surface a "claim" button.withdraw(address to, uint256 amount)is pause-independent so governance can drain a paused faucet without unpausing it.claimAmount/cooldown— testnet-only,Pausableis the safety net.Tests (
contracts/test/TestnetFaucet.t.sol) — 36 cases, 1024 fuzz runs on the cooldown boundary, 100% coverage across lines / statements / branches / funcs:cooldown == 0permitted.claim: happy path, partial-cooldown revert with exact remaining matched, succeeds aftervm.warp, per-caller independence, insufficient-balance revert,Pausable.EnforcedPause, reentrancy via inlineMaliciousERC20mock that re-entersclaim()during the SafeERC20 transfer — expectsReentrancyGuardReentrantCallto bubble through.testFuzz_claim_cooldownBoundary(uint256 delta): asserts the strict iff — claim succeeds iffdelta >= cooldown, andlastClaimedAtis invariant on revert.(old, new)pair.withdraw: only-role, pause-independence, zero-to / zero-amount / insufficient-balance reverts.pause/unpauseandgrantRole/revokeRolerole-based access control.Deploy script (
contracts/script/TestnetFaucet.s.sol) — separately named from any future production deploy script (the grep gate enforces this). Env-driven config with documented defaults (CLAIM_AMOUNT = 1_000e18,COOLDOWN_SECONDS = 1 days). Treasury broadcasts the approve+deploy pair in one go; post-deploy invariants checked via custom errors.Tooling
contracts/foundry.toml:testnet/deliberately kept outsidesrc; transitive compilation via the script + tests pulls it into the build graph. Comment records the separation rationale.contracts/package.json: solhint glob extended totestnet/**/*.sol+script/**/*.sol.contracts/.gas-snapshot: regenerated to include the new 36 cases..github/workflows/ci.yml(solidity build+testjob): new grep gate step — fails CI ifTestnetFaucetis referenced fromcontracts/src/or anycontracts/script/*.s.solother thanTestnetFaucet.s.sol.docs/runbook.md: new "Testnet faucet" section covering testnet-only status, pre-funding source, and thewithdrawescape hatch.Out of the audited surface
TestnetFaucetis not part of the 14-contract production audit perimeter tracked in #452. Slither and aderyn in CI skiptestnet/(slither's build graph doesn't reach it; aderyn'ssrc = "src"excludes it). The structural defense is the grep gate + the on-disk path + the deploy-script naming convention — all three would have to fail simultaneously for the faucet to land in a production deploy.Implementation notes
vm.prank(caller)is single-call. Puttingfaucet.GOVERNANCE_ROLE()inside anabi.encodeWithSelector(...)argument consumes the prank on that view call, leaving the next state-mutating call unpranked. Tests that probed role-rejection paths now hoist role reads above the prank.Test plan
forge fmt --checkcleanFOUNDRY_PROFILE=ci forge build --sizes --deny warningsclean (TestnetFaucet: 3,381 runtime / 4,347 initcode bytes)FOUNDRY_PROFILE=ci forge test— 82/82 passing across the full suite (36 new + 46 pre-existing)FOUNDRY_PROFILE=coverage forge coverage --report summary—testnet/TestnetFaucet.sol100% lines / statements / branches / funcsnpm run lint(solhint) cleansolidity build+testgreen (with new grep gate step)ci-successaggregator greenRefs: #636, #452 (audit perimeter), #644 (CI infra)