Skip to content

feat(contracts): testnet faucet for ad-hoc TOKEN distribution - #655

Merged
alpergundogdu merged 4 commits into
mainfrom
feat/contracts-testnet-faucet
May 22, 2026
Merged

alpergundogdu merged 4 commits into
mainfrom
feat/contracts-testnet-faucet

Conversation

@thiras

@thiras thiras commented May 21, 2026

Copy link
Copy Markdown
Contributor

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) — mirrors StakingRegistry's composition style:

  • AccessControl (3 roles: DEFAULT_ADMIN_ROLE for grants, GOVERNANCE_ROLE for setters + withdraw, PAUSER_ROLE for pause/unpause) + ReentrancyGuard + Pausable.
  • Constructor pulls initialFunding from a treasury address via safeTransferFrom — atomic deploy+fund — with zero-address / zero-amount reverts on every arg. initialCooldown == 0 is intentionally allowed (governance may want a no-cooldown burst for a short test; pause is the safety net).
  • claim() enforces per-address cooldown with a lastClaimedAt == 0 sentinel for first-time callers; CEI ordering with nonReentrant as the authoritative guard; emits Claimed(claimer, amount). Custom errors CooldownNotElapsed(remaining) and InsufficientBalance(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.
  • No upper bounds on claimAmount / cooldown — testnet-only, Pausable is 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:

  • Constructor happy path + zero-* revert sweep across every address and amount arg; cooldown == 0 permitted.
  • claim: happy path, partial-cooldown revert with exact remaining matched, succeeds after vm.warp, per-caller independence, insufficient-balance revert, Pausable.EnforcedPause, reentrancy via inline MaliciousERC20 mock that re-enters claim() during the SafeERC20 transfer — expects ReentrancyGuardReentrantCall to bubble through.
  • testFuzz_claim_cooldownBoundary(uint256 delta): asserts the strict iff — claim succeeds iff delta >= cooldown, and lastClaimedAt is invariant on revert.
  • Governance setters: only-role, value persistence, events with (old, new) pair.
  • withdraw: only-role, pause-independence, zero-to / zero-amount / insufficient-balance reverts.
  • pause / unpause and grantRole / revokeRole role-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 outside src; transitive compilation via the script + tests pulls it into the build graph. Comment records the separation rationale.
  • contracts/package.json: solhint glob extended to testnet/**/*.sol + script/**/*.sol.
  • contracts/.gas-snapshot: regenerated to include the new 36 cases.
  • .github/workflows/ci.yml (solidity build+test job): new grep gate step — fails CI if TestnetFaucet is referenced from contracts/src/ or any contracts/script/*.s.sol other than TestnetFaucet.s.sol.
  • docs/runbook.md: new "Testnet faucet" section covering testnet-only status, pre-funding source, and the withdraw escape hatch.

Out of the audited surface

TestnetFaucet is not part of the 14-contract production audit perimeter tracked in #452. Slither and aderyn in CI skip testnet/ (slither's build graph doesn't reach it; aderyn's src = "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

  • A subtle bug fixed during test authoring: vm.prank(caller) is single-call. Putting faucet.GOVERNANCE_ROLE() inside an abi.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 --check clean
  • FOUNDRY_PROFILE=ci forge build --sizes --deny warnings clean (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.sol 100% lines / statements / branches / funcs
  • npm run lint (solhint) clean
  • Local grep-gate simulation passes
  • Slither + aderyn don't flag the new path
  • CI: solidity build+test green (with new grep gate step)
  • CI: ci-success aggregator green

Refs: #636, #452 (audit perimeter), #644 (CI infra)

…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]>
Copilot AI review requested due to automatic review settings May 21, 2026 20:17
@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 87.50% (168/192 lines)
▼ -6.08pp vs base (93.58% → 87.50%)
Run: 26253062680

@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown

Gas snapshot

Gas changes vs base
Compiling 59 files with Solc 0.8.28
Solc 0.8.28 finished in 2.44s
Compiler run successful!

Ran 36 tests for test/StakingRegistry.t.sol:StakingRegistryTest
[PASS] testFuzz_slash_threeLegsSumToSlashAmount(uint256) (runs: 1024, μ: 267887, ~: 267939)
[PASS] test_constructor_revertsOnOutOfBoundsMinStake() (gas: 125485)
[PASS] test_constructor_revertsOnOutOfBoundsUnbondingPeriod() (gas: 125607)
[PASS] test_constructor_revertsOnZeroAdmin() (gas: 64369)
[PASS] test_constructor_revertsOnZeroToken() (gas: 64326)
[PASS] test_constructor_setsImmutableAndState() (gas: 23869)
[PASS] test_ejectNode_revertsWithoutBlacklistRole() (gas: 13066)
[PASS] test_ejectNode_setsFlagWithoutMovingTokens() (gas: 114331)
[PASS] test_isActive_requiresMinStakeAndNotEjected() (gas: 137540)
[PASS] test_recordSettlement_revertsWithoutReporterRole() (gas: 13022)
[PASS] test_recordSettlement_updatesTimestamp() (gas: 39711)
[PASS] test_requestUnstake_movesAmountToUnbonding() (gas: 137196)
[PASS] test_requestUnstake_revertsOnInflightRequest() (gas: 139841)
[PASS] test_requestUnstake_revertsOnInsufficientStake() (gas: 89060)
[PASS] test_setMinStake_revertsOutOfBounds() (gas: 17645)
[PASS] test_setMinStake_withinBoundsSucceeds() (gas: 20254)
[PASS] test_setUnbondingPeriod_revertsOutOfBounds() (gas: 17701)
[PASS] test_slash_appliesToActivePlusUnbonding() (gas: 307745)
[PASS] test_slash_autoEjectsWhenStakeFallsBelowHalfMinimum() (gas: 414072)
[PASS] test_slash_distributes50_30_20() (gas: 267038)
[PASS] test_slash_drawsFromUnbondingWhenActiveInsufficient() (gas: 310205)
[PASS] test_slash_notifiesSafetyReserve() (gas: 262215)
[PASS] test_slash_revertsOnZeroChallenger() (gas: 93093)
[PASS] test_slash_revertsWhenSafetyReserveNotWired() (gas: 102762)
[PASS] test_slash_revertsWithoutSlashRole() (gas: 92603)
[PASS] test_slash_tier1_is5Percent() (gas: 259294)
[PASS] test_slash_tier2_is15Percent() (gas: 325018)
[PASS] test_slash_tier3Stays50PercentBeyondThird() (gas: 522527)
[PASS] test_slash_tier3_is50Percent() (gas: 390852)
[PASS] test_stake_addsToActiveStake() (gas: 86918)
[PASS] test_stake_clearsEjectedFlagWhenRestakedToMinimum() (gas: 135568)
[PASS] test_stake_revertsOnZeroAmount() (gas: 18200)
[PASS] test_stake_revertsWhenPaused() (gas: 45265)
[PASS] test_unstake_returnsTokensAfterUnbonding() (gas: 135641)
[PASS] test_unstake_revertsBeforeUnbondingComplete() (gas: 128276)
[PASS] test_unstake_revertsWithNoRequest() (gas: 22449)
Suite result: ok. 36 passed; 0 failed; 0 skipped; finished in 257.00ms (255.00ms CPU time)

Ran 44 tests for test/TestnetFaucet.t.sol:TestnetFaucetTest
[PASS] testFuzz_claim_atOrAboveCooldown(uint256) (runs: 1024, μ: 91477, ~: 91528)
[PASS] testFuzz_claim_belowCooldown(uint256) (runs: 1024, μ: 85175, ~: 85389)
[PASS] test_admin_canGrantAndRevokeRoles() (gas: 56401)
[PASS] test_claim_blocksReentrancy() (gas: 1550228)
[PASS] test_claim_happyPath() (gas: 82821)
[PASS] test_claim_perCallerCooldownIndependence() (gas: 133478)
[PASS] test_claim_revertsBeforeCooldown() (gas: 83092)
[PASS] test_claim_revertsOnInsufficientBalance() (gas: 50715)
[PASS] test_claim_revertsOneSecondBeforeCooldownBoundary() (gas: 82996)
[PASS] test_claim_revertsWhenPaused() (gas: 39998)
[PASS] test_claim_succeedsAfterCooldown() (gas: 90430)
[PASS] test_claim_succeedsAtExactCooldownBoundary() (gas: 87103)
[PASS] test_constructor_allowsZeroCooldown() (gas: 1810378)
[PASS] test_constructor_revertsOnCooldownExceedingMax() (gas: 1015061)
[PASS] test_constructor_revertsOnMainnetChainId() (gas: 988198)
[PASS] test_constructor_revertsOnZeroAdmin() (gas: 985898)
[PASS] test_constructor_revertsOnZeroClaimAmount() (gas: 988045)
[PASS] test_constructor_revertsOnZeroFunding() (gas: 988061)
[PASS] test_constructor_revertsOnZeroGovernance() (gas: 985864)
[PASS] test_constructor_revertsOnZeroPauser() (gas: 985954)
[PASS] test_constructor_revertsOnZeroTokenAddress() (gas: 70468)
[PASS] test_constructor_revertsOnZeroTreasury() (gas: 987830)
[PASS] test_constructor_revertsWhenTreasuryNotApproved() (gas: 1110690)
[PASS] test_constructor_setsStateAndRoles() (gas: 43070)
[PASS] test_nonAdmin_cannotGrantRoles() (gas: 17889)
[PASS] test_pause_blocksClaimUnpauseRestores() (gas: 91691)
[PASS] test_pause_revertsOnNonPauser() (gas: 14607)
[PASS] test_setClaimAmount_revertsOnNonGovernance() (gas: 14702)
[PASS] test_setClaimAmount_revertsOnZero() (gas: 13338)
[PASS] test_setClaimAmount_updatesAndEmits() (gas: 22083)
[PASS] test_setCooldown_acceptsMaxCooldown() (gas: 20228)
[PASS] test_setCooldown_allowsZero() (gas: 94920)
[PASS] test_setCooldown_revertsOnExceedingMax() (gas: 13790)
[PASS] test_setCooldown_revertsOnNonGovernance() (gas: 14705)
[PASS] test_setCooldown_updatesAndEmits() (gas: 22231)
[PASS] test_timeUntilNext_tracksCooldownWindow() (gas: 82615)
[PASS] test_timeUntilNext_zeroBeforeFirstClaim() (gas: 10099)
[PASS] test_unpause_revertsOnNonPauser() (gas: 43483)
[PASS] test_withdraw_revertsOnInsufficientBalance() (gas: 26877)
[PASS] test_withdraw_revertsOnNonGovernance() (gas: 17089)
[PASS] test_withdraw_revertsOnZeroAmount() (gas: 20838)
[PASS] test_withdraw_revertsOnZeroTo() (gas: 18662)
[PASS] test_withdraw_transfersAndEmits() (gas: 44129)
[PASS] test_withdraw_worksWhilePaused() (gas: 68286)
Suite result: ok. 44 passed; 0 failed; 0 skipped; finished in 264.70ms (260.96ms CPU time)

Ran 10 tests for test/Token.t.sol:TokenTest
[PASS] testFuzz_burn_reducesSupplyByExactAmount(uint256) (runs: 1024, μ: 27735, ~: 27700)
[PASS] test_burnFrom_consumesAllowance() (gas: 38534)
[PASS] test_burn_reducesTotalSupplyAndBalance() (gas: 26044)
[PASS] test_constructor_metadata() (gas: 17896)
[PASS] test_constructor_mintsFullSupplyToHolder() (gas: 12954)
[PASS] test_constructor_revertsOnZeroInitialHolder() (gas: 83264)
[PASS] test_constructor_totalSupplyConstantMatches() (gas: 9364)
[PASS] test_noMintFunctionExposed() (gas: 10765)
[PASS] test_noVotesSurfaceExposed() (gas: 11991)
[PASS] test_permit_setsAllowance() (gas: 67380)
Suite result: ok. 10 passed; 0 failed; 0 skipped; finished in 54.05ms (57.08ms CPU time)

Ran 3 test suites in 312.86ms (575.75ms CPU time): 90 tests passed, 0 failed, 0 skipped (90 total tests)
━ StakingRegistryTest::testFuzz_slash_threeLegsSumToSlashAmount(uint256) (gas: 267939 → 267939 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnOutOfBoundsMinStake() (gas: 125485 → 125485 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnOutOfBoundsUnbondingPeriod() (gas: 125607 → 125607 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnZeroAdmin() (gas: 64369 → 64369 | 0 0.000%)
━ StakingRegistryTest::test_constructor_revertsOnZeroToken() (gas: 64326 → 64326 | 0 0.000%)
━ StakingRegistryTest::test_constructor_setsImmutableAndState() (gas: 23869 → 23869 | 0 0.000%)
━ StakingRegistryTest::test_ejectNode_revertsWithoutBlacklistRole() (gas: 13066 → 13066 | 0 0.000%)
━ StakingRegistryTest::test_ejectNode_setsFlagWithoutMovingTokens() (gas: 114331 → 114331 | 0 0.000%)
━ StakingRegistryTest::test_isActive_requiresMinStakeAndNotEjected() (gas: 137540 → 137540 | 0 0.000%)
━ StakingRegistryTest::test_recordSettlement_revertsWithoutReporterRole() (gas: 13022 → 13022 | 0 0.000%)
━ StakingRegistryTest::test_recordSettlement_updatesTimestamp() (gas: 39711 → 39711 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_movesAmountToUnbonding() (gas: 137196 → 137196 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_revertsOnInflightRequest() (gas: 139841 → 139841 | 0 0.000%)
━ StakingRegistryTest::test_requestUnstake_revertsOnInsufficientStake() (gas: 89060 → 89060 | 0 0.000%)
━ StakingRegistryTest::test_setMinStake_revertsOutOfBounds() (gas: 17645 → 17645 | 0 0.000%)
━ StakingRegistryTest::test_setMinStake_withinBoundsSucceeds() (gas: 20254 → 20254 | 0 0.000%)
━ StakingRegistryTest::test_setUnbondingPeriod_revertsOutOfBounds() (gas: 17701 → 17701 | 0 0.000%)
━ StakingRegistryTest::test_slash_appliesToActivePlusUnbonding() (gas: 307745 → 307745 | 0 0.000%)
━ StakingRegistryTest::test_slash_autoEjectsWhenStakeFallsBelowHalfMinimum() (gas: 414072 → 414072 | 0 0.000%)
━ StakingRegistryTest::test_slash_distributes50_30_20() (gas: 267038 → 267038 | 0 0.000%)
━ StakingRegistryTest::test_slash_drawsFromUnbondingWhenActiveInsufficient() (gas: 310205 → 310205 | 0 0.000%)
━ StakingRegistryTest::test_slash_notifiesSafetyReserve() (gas: 262215 → 262215 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsOnZeroChallenger() (gas: 93093 → 93093 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsWhenSafetyReserveNotWired() (gas: 102762 → 102762 | 0 0.000%)
━ StakingRegistryTest::test_slash_revertsWithoutSlashRole() (gas: 92603 → 92603 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier1_is5Percent() (gas: 259294 → 259294 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier2_is15Percent() (gas: 325018 → 325018 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier3Stays50PercentBeyondThird() (gas: 522527 → 522527 | 0 0.000%)
━ StakingRegistryTest::test_slash_tier3_is50Percent() (gas: 390852 → 390852 | 0 0.000%)
━ StakingRegistryTest::test_stake_addsToActiveStake() (gas: 86918 → 86918 | 0 0.000%)
━ StakingRegistryTest::test_stake_clearsEjectedFlagWhenRestakedToMinimum() (gas: 135568 → 135568 | 0 0.000%)
━ StakingRegistryTest::test_stake_revertsOnZeroAmount() (gas: 18200 → 18200 | 0 0.000%)
━ StakingRegistryTest::test_stake_revertsWhenPaused() (gas: 45265 → 45265 | 0 0.000%)
━ StakingRegistryTest::test_unstake_returnsTokensAfterUnbonding() (gas: 135641 → 135641 | 0 0.000%)
━ StakingRegistryTest::test_unstake_revertsBeforeUnbondingComplete() (gas: 128276 → 128276 | 0 0.000%)
━ StakingRegistryTest::test_unstake_revertsWithNoRequest() (gas: 22449 → 22449 | 0 0.000%)
━ TestnetFaucetTest::testFuzz_claim_atOrAboveCooldown(uint256) (gas: 91528 → 91528 | 0 0.000%)
━ TestnetFaucetTest::testFuzz_claim_belowCooldown(uint256) (gas: 85389 → 85389 | 0 0.000%)
━ TestnetFaucetTest::test_admin_canGrantAndRevokeRoles() (gas: 56401 → 56401 | 0 0.000%)
━ TestnetFaucetTest::test_claim_blocksReentrancy() (gas: 1550228 → 1550228 | 0 0.000%)
━ TestnetFaucetTest::test_claim_happyPath() (gas: 82821 → 82821 | 0 0.000%)
━ TestnetFaucetTest::test_claim_perCallerCooldownIndependence() (gas: 133478 → 133478 | 0 0.000%)
━ TestnetFaucetTest::test_claim_revertsBeforeCooldown() (gas: 83092 → 83092 | 0 0.000%)
━ TestnetFaucetTest::test_claim_revertsOnInsufficientBalance() (gas: 50715 → 50715 | 0 0.000%)
━ TestnetFaucetTest::test_claim_revertsOneSecondBeforeCooldownBoundary() (gas: 82996 → 82996 | 0 0.000%)
━ TestnetFaucetTest::test_claim_revertsWhenPaused() (gas: 39998 → 39998 | 0 0.000%)
━ TestnetFaucetTest::test_claim_succeedsAfterCooldown() (gas: 90430 → 90430 | 0 0.000%)
━ TestnetFaucetTest::test_claim_succeedsAtExactCooldownBoundary() (gas: 87103 → 87103 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_allowsZeroCooldown() (gas: 1810378 → 1810378 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnCooldownExceedingMax() (gas: 1015061 → 1015061 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnMainnetChainId() (gas: 988198 → 988198 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroAdmin() (gas: 985898 → 985898 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroClaimAmount() (gas: 988045 → 988045 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroFunding() (gas: 988061 → 988061 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroGovernance() (gas: 985864 → 985864 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroPauser() (gas: 985954 → 985954 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroTokenAddress() (gas: 70468 → 70468 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsOnZeroTreasury() (gas: 987830 → 987830 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_revertsWhenTreasuryNotApproved() (gas: 1110690 → 1110690 | 0 0.000%)
━ TestnetFaucetTest::test_constructor_setsStateAndRoles() (gas: 43070 → 43070 | 0 0.000%)
━ TestnetFaucetTest::test_nonAdmin_cannotGrantRoles() (gas: 17889 → 17889 | 0 0.000%)
━ TestnetFaucetTest::test_pause_blocksClaimUnpauseRestores() (gas: 91691 → 91691 | 0 0.000%)
━ TestnetFaucetTest::test_pause_revertsOnNonPauser() (gas: 14607 → 14607 | 0 0.000%)
━ TestnetFaucetTest::test_setClaimAmount_revertsOnNonGovernance() (gas: 14702 → 14702 | 0 0.000%)
━ TestnetFaucetTest::test_setClaimAmount_revertsOnZero() (gas: 13338 → 13338 | 0 0.000%)
━ TestnetFaucetTest::test_setClaimAmount_updatesAndEmits() (gas: 22083 → 22083 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_acceptsMaxCooldown() (gas: 20228 → 20228 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_allowsZero() (gas: 94920 → 94920 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_revertsOnExceedingMax() (gas: 13790 → 13790 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_revertsOnNonGovernance() (gas: 14705 → 14705 | 0 0.000%)
━ TestnetFaucetTest::test_setCooldown_updatesAndEmits() (gas: 22231 → 22231 | 0 0.000%)
━ TestnetFaucetTest::test_timeUntilNext_tracksCooldownWindow() (gas: 82615 → 82615 | 0 0.000%)
━ TestnetFaucetTest::test_timeUntilNext_zeroBeforeFirstClaim() (gas: 10099 → 10099 | 0 0.000%)
━ TestnetFaucetTest::test_unpause_revertsOnNonPauser() (gas: 43483 → 43483 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_revertsOnInsufficientBalance() (gas: 26877 → 26877 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_revertsOnNonGovernance() (gas: 17089 → 17089 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_revertsOnZeroAmount() (gas: 20838 → 20838 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_revertsOnZeroTo() (gas: 18662 → 18662 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_transfersAndEmits() (gas: 44129 → 44129 | 0 0.000%)
━ TestnetFaucetTest::test_withdraw_worksWhilePaused() (gas: 68286 → 68286 | 0 0.000%)
━ TokenTest::testFuzz_burn_reducesSupplyByExactAmount(uint256) (gas: 27700 → 27700 | 0 0.000%)
━ TokenTest::test_burnFrom_consumesAllowance() (gas: 38534 → 38534 | 0 0.000%)
━ TokenTest::test_burn_reducesTotalSupplyAndBalance() (gas: 26044 → 26044 | 0 0.000%)
━ TokenTest::test_constructor_metadata() (gas: 17896 → 17896 | 0 0.000%)
━ TokenTest::test_constructor_mintsFullSupplyToHolder() (gas: 12954 → 12954 | 0 0.000%)
━ TokenTest::test_constructor_revertsOnZeroInitialHolder() (gas: 83264 → 83264 | 0 0.000%)
━ TokenTest::test_constructor_totalSupplyConstantMatches() (gas: 9364 → 9364 | 0 0.000%)
━ TokenTest::test_noMintFunctionExposed() (gas: 10765 → 10765 | 0 0.000%)
━ TokenTest::test_noVotesSurfaceExposed() (gas: 11991 → 11991 | 0 0.000%)
━ TokenTest::test_permit_setsAllowance() (gas: 67380 → 67380 | 0 0.000%)

--------------------------------------------------------------------------------
Total tests: 90, ↑ 0, ↓ 0, ━ 90
Overall gas change: 0 (0.000%)

Run: 26253062680

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread contracts/testnet/TestnetFaucet.sol Resolved
Comment thread contracts/testnet/TestnetFaucet.sol Resolved
@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 89.97% (was 89.97%, ▲ +0.01%) — 16800/18672 lines

No Rust files changed in this PR.

History
Commit Total Δ vs base
bbead99 89.97% ● 0.00%
542b16e 89.97% ● 0.00%
5a8ae8e 89.97% ● 0.00%
440cf4e (HEAD) 89.97% ▲ +0.01%

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 include testnet/ and script/.
  • Adds a CI “grep gate” to ensure TestnetFaucet references don’t leak into contracts/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.

Comment thread contracts/script/TestnetFaucet.s.sol Resolved
Comment thread contracts/script/TestnetFaucet.s.sol Resolved
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]>
@thiras thiras changed the title feat(contracts): TestnetFaucet for ad-hoc TOKEN distribution on testnet feat(contracts): testnet faucet for ad-hoc TOKEN distribution May 21, 2026
thiras and others added 2 commits May 21, 2026 23:55
…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]>
@thiras
thiras requested a review from alpergundogdu May 21, 2026 21:21
// 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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This won't work on Arbitrum one, chain ID is 42161

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might add that later before deployment. It's apparently enough to gate forge

@alpergundogdu
alpergundogdu merged commit cdc6d4f into main May 22, 2026
18 checks passed
@alpergundogdu
alpergundogdu deleted the feat/contracts-testnet-faucet branch May 22, 2026 08:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(contracts): TestnetFaucet for ad-hoc TOKEN distribution on testnet

3 participants