A thorough, code-grounded security checklist for the crowdfund-dapp contracts. Every
item below maps to a pattern that is actually present (or deliberately absent) in this
codebase, with pointers to where it lives. Use it as a pre-deployment gate and as a guide
for external reviewers.
Status: unaudited. This document is a self-assessment checklist, not a substitute for an independent third-party audit. See Residual Risks.
| Contract | File | Role |
|---|---|---|
CrowdFund |
src/CrowdFund.sol |
Single all-or-nothing campaign (ETH or ERC20). Creator withdraws on success; contributors refund on failure. |
CrowdFundFactory |
src/CrowdFundFactory.sol |
CREATE2 deployer + per-creator index for CrowdFund campaigns. |
MilestoneCrowdFund |
src/MilestoneCrowdFund.sol |
Campaign that releases escrow in contributor-governed milestones with pro-rata refund on rejection. |
IERC20 |
src/IERC20.sol |
Minimal interface (only transfer, transferFrom, balanceOf). |
Out of scope / intentionally absent (do not assume these exist):
- No proxy / upgradeability (no
delegatecall, no storage-layout constraints). - No owner/admin, no
Ownable, noPausable, no privileged backdoor. - No price oracle, no external price feeds, no AMM interaction.
- No
SafeMathlibrary β relies on Solidity^0.8.20native checked arithmetic. - Test-only mocks under
test/mocks/are not production contracts and are excluded.
Actors
- Creator β defines campaign terms at construction; can withdraw on success / drive milestones. Cannot change terms after deploy (all terms are
immutableor set once). - Contributor β sends ETH/tokens; gets refund on failure; votes on milestones (weighted by contribution).
- Factory β stateless deployer; holds no funds; cannot touch a deployed campaign's escrow.
Trust assumptions
- The creator is not trusted with contributor funds beyond the contract's rules. Funds are escrowed by the campaign contract, released only by the encoded conditions (goal reached, or milestone approved by weighted majority).
- The ERC20 token, if used, is assumed to be reasonably well-behaved. Known token-class caveats (fee-on-transfer, rebasing, ERC777 hooks) are addressed below where mitigated and flagged where not.
block.timestampis trusted to within typical miner tolerance (~seconds) for deadline checks only.
[ ]= verify before mainnet deployment.- Each section states the pattern, where it lives, and how to verify it.
- Re-run the full suite for every change:
forge test(4 suites; ETHCrowdFund,CrowdFundFactory,CrowdFundERC20,MilestoneCrowdFund). The suite includes unit, edge-case, reentrancy, and fuzz tests. - Recommended static/dynamic tooling before sign-off:
slither .,forge test --fuzz-runs 100000, and an Echidna/Foundry invariant campaign on escrow conservation.
Pattern: Creator-only functions guard on msg.sender != creator, reverting NotCreator. creator is immutable, set once in the constructor and rejecting address(0) (ZeroCreator).
Where: CrowdFund.withdraw; MilestoneCrowdFund.requestMilestone, claimMilestone. Constructor ZeroCreator check in both.
- Every state-changing creator-only function checks
msg.sender == creatorfirst. -
creatorisimmutableand cannot be reassigned anywhere. - No function lets a third party set/transfer
creator. - Voting and refund paths are permissionless by design (any contributor), and verified to key off
contributions[msg.sender], not on caller identity. - Factory functions deploy campaigns owned by
msg.senderonly β no way to deploy a campaign owned by someone else.
Pattern: A nonReentrant modifier using a uint256 _locked flag (1 = unlocked, 2 = locked) wraps every value-moving entrypoint. Independently, all such functions follow Checks β Effects β Interactions: storage is updated before the external ETH/token call.
Where:
- Guard:
CrowdFund.{contribute, contribute(uint256), withdraw, refund};MilestoneCrowdFund.{contribute, contribute(uint256), claimMilestone, claimRefund, refund}. - CEI effects-before-interaction:
withdrawn = truebefore payout (CrowdFund.withdraw);contributions[msg.sender] = 0before payout (refund);status = Claimed; nextMilestone++before payout (claimMilestone);refundClaimed[msg.sender] = truebefore payout (claimRefund).
Note: requestMilestone and voteMilestone make no external calls and are intentionally not nonReentrant.
- Every function that sends ETH or calls a token is
nonReentrant. - In every such function, all relevant storage writes happen before the external call.
- The guard restores
_locked = 1after the call (no permanent lock on revert paths β Solidity reverts unwind it). - A malicious recipient (ERC777
tokensReceived, or a contractreceive()) re-entering a guarded function reverts. (Covered byMilestoneCrowdFundtest_Reentrancy_GuardBlocksReentrantClaim, which proves a nestedclaimMilestonebubbles up asTransferFailed.) - Cross-function reentrancy considered: e.g. re-entering
refundfromwithdrawβ blocked by the shared_lockedflag (one guard per contract instance).
Pattern: Refunds are pull-based β each contributor calls refund() / claimRefund() to withdraw their own share. The contract never loops over contributors to push funds, eliminating gas-griefing and one-bad-recipient-blocks-all failure modes.
Where: CrowdFund.refund, MilestoneCrowdFund.refund, MilestoneCrowdFund.claimRefund.
- No unbounded loop over contributors anywhere in a payout path.
- A single reverting recipient cannot block other contributors' refunds.
- Each refund is idempotency-guarded (see 4.4) so it cannot be drained twice.
Pattern: Every once-only action is gated by explicit state so it cannot repeat.
Where:
-
CrowdFund.withdrawn(bool) βAlreadyWithdrawn. -
CrowdFund.refund: zeroescontributions[msg.sender]β second call hitsNothingToRefund. -
MilestoneCrowdFundStatusenum (Pending β Active β Approved β Claimed, orβ Rejected) gatesrequestMilestone/voteMilestone/claimMilestone. -
hasVoted[index][voter]βAlreadyVoted(one vote per contributor per milestone). -
refundClaimed[account]βNothingToRefundon repeat. -
nextMilestoneenforces strict sequential ordering (NotNextMilestone). -
Withdraw can succeed at most once.
-
A contributor can refund their balance at most once (ETH path zeroes balance; milestone path sets
refundClaimed). -
A contributor can vote at most once per milestone.
-
Milestones can only progress forward through the state machine; no state can be re-entered (e.g. an
Activemilestone cannot be re-requested βMilestoneNotPending). -
Milestones must be claimed in order; you cannot skip ahead.
Pattern: Token moves go through low-level call helpers (_safeTransfer/_safeTransferFrom β _callToken) that tolerate non-compliant tokens which return no data, and revert (TokenTransferFailed) on a failed call or an explicit false return. This is the de-facto SafeERC20 semantics.
Where: _callToken, _safeTransferToken, _safeTransferFrom in both CrowdFund and MilestoneCrowdFund.
- Return value of every
transfer/transferFromis checked:!ok || (ret.length != 0 && !decode(ret,bool))reverts. - Tokens that return no data on success (e.g. classic USDT-style) are accepted.
- Tokens that return
falseinstead of reverting are treated as failures. - No raw
IERC20(token).transfer(...)call ignores the boolean result.
Pattern: On contribution, the contract credits the measured balance delta, not the requested amount: received = balanceAfter - balanceBefore, and reverts if received == 0. So fee-on-transfer / deflationary tokens are accounted correctly on the way in.
Where: CrowdFund.contribute(uint256), MilestoneCrowdFund.contribute(uint256). Tested by test_FeeOnTransfer_CreditsReceivedAmount and the FeeOnTransferERC20 mock.
- Inbound credit is based on actual balance change, not the input argument.
- Zero net received reverts (
ZeroContribution). -
β οΈ Outbound payouts send the recorded amount; with a fee-on-transfer token the recipient receives slightly less than recorded (see 9). This is a known token-class limitation, not a contract bug.
Pattern: A campaign is ETH-mode (token == address(0)) or token-mode, fixed at construction. The wrong entrypoint reverts: ETH contribute() on a token campaign β NotEthCampaign; token contribute(uint256) on an ETH campaign β NotTokenCampaign. ETH-mode payouts use call, token-mode payouts use the safe-transfer helpers, both routed through _payout/_balance which branch on token == address(0).
Where: contribute*, _payout, _balance in both contracts.
- ETH cannot be deposited into a token campaign via
contribute(). - The contract has no
receive()/payable fallback(except the explicitly-payablecontribute()), so stray ETH cannot enter a token campaign through a normal send. - Payout path matches campaign mode (ETH β
call, token β safe transfer).
Pattern: A non-zero token must be a contract. The constructor rejects an EOA/empty token: _token != address(0) && _token.code.length == 0 β InvalidToken. The factory's dedicated ERC20 entrypoint rejects address(0) β TokenNotSupported, so an intended-ERC20 campaign cannot silently fall back to ETH mode.
Where: CrowdFund constructor; CrowdFundFactory.createCampaignERC20.
- A token campaign cannot be constructed with an address that has no code.
-
createCampaignERC20rejects the zero token. - Note: a code-bearing but malicious token is not rejected here; mitigation relies on safe-transfer + reentrancy guard + CEI, not on a token whitelist.
Pattern: All construction terms are validated up front and become immutable/fixed.
Where: constructors of all three contracts; factory re-validates before paying for deployment.
-
creator != address(0)(ZeroCreator). -
goal != 0(ZeroGoal). -
deadline > block.timestamp(DeadlineInPast). -
MilestoneCrowdFund:milestones.length > 0(NoMilestones), each amount> 0(ZeroMilestone),descriptions.length == milestones.length(MilestoneCountMismatch), andsum(milestones) == goal(MilestoneSumMismatch). - Factory validates
goal/deadlinebefore deployment so it fails cheaply.
Pattern: Solidity ^0.8.20 checked arithmetic guards all add/sub/mul (no unchecked blocks in value math). Pro-rata refunds compute contributed * refundPool / totalRaised; integer division can leave dust (β€ a few wei) in the contract β funds are conserved and never over-paid.
Where: _record (accumulation), MilestoneCrowdFund.claimRefund / refundOwed. Fuzzed by testFuzz_ProRataRefundConserves (asserts residual balance β€ 1 wei) and testFuzz_ApprovalThreshold.
- No
uncheckedblocks around contribution/total/refund math. -
mulbeforedivordering in pro-rata to preserve precision. - Rounding dust is bounded and only ever leaves residue in the contract (never overdraws).
- A contributor whose pro-rata share rounds to
0revertsNothingToRefundrather than transferring zero.
Pattern: Voting weight = a contributor's contributions balance. Funding closes once totalRaised >= goal (FundingClosed), so both contributions and totalRaised are frozen throughout the execution phase β tallies cannot be manipulated mid-vote. Thresholds: approve when approveVotes * 2 > totalRaised (strict majority of all contributed value); reject when rejectVotes * 2 >= totalRaised (point at which approval is unreachable). A milestone finalizes the instant a threshold is crossed.
Where: voteMilestone, _checkFundingOpen.
- Vote weight is read from frozen
contributions; no new contributions can dilute/inflate weight after funding closes. -
totalRaiseddenominator is frozen during voting. - Approval requires strict majority (exact 50% does not pass β
test_Vote_ExactHalfApproveIsNotEnough). - Rejection at β₯50% opposition is final and halts the campaign (
CampaignHaltedblocks further requests). - A contributor cannot vote after the milestone finalized (
MilestoneNotActive). -
β οΈ A single contributor holding β₯50% weight can unilaterally approve or reject. This is by design (weighted governance), documented as a centralization consideration in (9).
Pattern: Campaigns are deployed with CREATE2 using salt = keccak256(creator, creatorCampaignCount). The address is predictable via computeAddress and unique per (creator, index). The init-code hash binds all constructor args, so a predicted address only matches if deployed with identical terms.
Where: _createCampaign, _computeAddress, _saltFor, _create2Address.
- Salt is unique per creator per campaign index β no address collision between a creator's campaigns.
-
computeAddressmatches the actual deployed address (covered bytest_ComputeAddress_MatchesDeploymentand ERC20 variant). - CREATE2 redeploy-to-same-address is impossible here because the salt's nonce (
_campaignsByCreator[creator].length) strictly increases β noselfdestruct+ redeploy metamorphic risk (contracts have noselfdestruct). - Front-running a predicted address: an attacker cannot occupy a creator's predicted address because the salt is bound to that creator and the init-code hash to the exact terms; deploying with the same salt from the factory still records under
msg.sender.
Pattern: All reverts use custom errors rather than revert strings β cheaper and machine-parseable.
- No
require(..., "string")in hot paths (all reverts are typed errors). - Error names are specific enough for off-chain decoding and test assertions (
vm.expectRevert(X.selector)).
| # | Class | Status in this codebase |
|---|---|---|
| Reentrancy (SWC-107) | nonReentrant guard + CEI on all payout fns; tested |
β Mitigated |
| Access control (SWC-105/106) | NotCreator checks; immutable creator; no admin |
β Mitigated |
| Integer over/underflow (SWC-101) | Solidity β₯0.8 checked math; no unchecked |
β Mitigated |
| Unchecked external call return (SWC-104) | ETH call ok checked; token return decoded |
β Mitigated |
| Uninitialized storage / shadowing | Immutables + explicit init (_locked = 1) |
β N/A |
delegatecall/proxy (SWC-112) |
None used | β N/A |
selfdestruct (SWC-106) |
None used | β N/A |
tx.origin auth (SWC-115) |
Not used; msg.sender only |
β N/A |
| Timestamp dependence (SWC-116) | Only deadline boundary; ~seconds tolerance | |
| DoS via unbounded loop / push payment (SWC-113/128) | Pull payments; no loops over users | β Mitigated |
| Front-running (SWC-114) | No price-sensitive ordering; CREATE2 salt creator-bound | |
| Weak randomness (SWC-120) | No randomness used | β N/A |
| Signature replay (SWC-117/121) | No signatures used | β N/A |
| Floating pragma (SWC-103) | ^0.8.20; pin to 0.8.20 for production deploys |
|
| ERC20 non-standard behavior | Safe-transfer + balance-delta accounting | β
Mitigated (in); |
Force-fed ETH (selfdestruct/coinbase) |
Accounting uses contributions/fixed amounts, not bare balance for credit |
β See 9 |
CrowdFund
-
contribute()β ETH-only, guarded, pre-deadline, non-zero, records before any call. -
contribute(uint256)β token-only, guarded, balance-delta credit, non-zero received. -
withdraw()β creator-only, goal reached, once-only, CEI, guarded. -
refund()β post-deadline, goal missed, per-contributor once, CEI, guarded. - View helpers (
isERC20,goalReached,isActive,timeRemaining) are pure reads with no side effects.
CrowdFundFactory
-
createCampaign(ETH and token overloads) β validates, deploys via CREATE2, indexes undermsg.sender. -
createCampaignERC20β rejects zero token, otherwise same path. -
computeAddressoverloads β pure prediction, no state change. - Enumeration views return stored arrays only.
MilestoneCrowdFund
-
contribute*β as CrowdFund, plusFundingClosedonce goal reached. -
requestMilestoneβ creator-only, goal reached, not halted, sequential,PendingβActive. -
voteMilestoneβ active milestone, contributor weight, one vote, threshold finalization. -
claimMilestoneβ creator-only,ApprovedβClaimed, advancesnextMilestone, CEI, guarded. -
claimRefundβ only after rejection, per-contributor once, pro-rata, CEI, guarded. -
refundβ failed-funding path (post-deadline, goal missed), distinct fromclaimRefund.
- CrowdFund (ETH):
address(this).balance == sum(contributions)untilwithdraw/refund; after a successfulwithdraw, balance is 0 (plus any force-fed ETH, which goes to the creator sincewithdrawpays out_balance()). - CrowdFund (failure): sum of refunds β€ total contributed; no contributor refunds more than they put in.
- Milestone:
sum(claimed milestone amounts) + remaining escrow == totalRaised(ignoring force-fed ETH and rounding dust). - Milestone (rejection):
sum(pro-rata refunds) β€ refundPool; residue β€ rounding dust. - No path lets total outflow exceed total inflow for any contributor or for the contract.
-
forge testpasses (unit + edge + reentrancy + fuzz across all 4 suites). - Fuzz tests run with elevated runs before release:
forge test --fuzz-runs 100000. -
forge coveragereviewed β every revert branch exercised. -
slither .reviewed; triage every finding (expect informational on low-level calls β intentional). - Optional: Echidna / Foundry invariant run on the conservation invariants in Β§7.
- Compiler pinned to a single version for production (
solc_version = "0.8.20"infoundry.toml), optimizer settings recorded for verification.
These are acknowledged, not silently ignored. A reviewer/deployer must accept them.
- Creator stalling (liveness). After the goal is reached,
MilestoneCrowdFundhas no deadline on the execution phase. If the creator never callsrequestMilestone, contributor funds remain escrowed indefinitely with no built-in timeout/rescue. Contributors only get a refund path if a milestone is requested and then rejected. Consider adding an execution-phase deadline or an inactivity-triggered refund before relying on this in production. - Fee-on-transfer / rebasing tokens (outbound & balance drift). Inbound contributions are credited by balance delta (safe). But milestone payouts send a fixed recorded amount; a fee-on-transfer token delivers slightly less to the creator, and rebasing tokens can desync
totalRaisedfrom actual balance. Prefer standard, non-rebasing ERC20s. - Weighted-governance centralization. Any contributor with β₯50% of contributed value can unilaterally approve every milestone or reject (halting the campaign). This is intentional but is a centralization/whale risk in low-participation campaigns.
- Timestamp tolerance. Deadline checks rely on
block.timestamp; a miner/validator can nudge it by a few seconds around the boundary. Impact is limited to last-second contribution/refund eligibility β no value can be stolen. - Force-fed ETH. ETH can be force-sent via
selfdestruct/coinbase to any contract. Accounting never credits force-fed ETH (contributions are tracked explicitly), so it cannot inflatetotalRaised, votes, or refund shares. InCrowdFunda successfulwithdrawforwards the entire_balance()(so force-fed ETH goes to the creator, not stuck). InMilestoneCrowdFund, force-fed ETH may remain as un-claimable dust after all milestones; it does not affect correctness. - Malicious token contracts. A code-bearing token is not whitelisted. Defense rests on
nonReentrant+ CEI + checked transfer returns. A pathological token (e.g. one that reverts selectively or returns lies) can grief its own campaign but cannot drain ETH from other campaigns (campaigns are isolated instances). - Floating pragma. Source uses
^0.8.20. Pin to an exact version at deploy time and record it for source verification. - Unaudited. No external audit has been performed. Treat as experimental.
| Item | Owner | Status |
|---|---|---|
| All Β§4 patterns verified in code | β | |
| Β§5 vulnerability checklist triaged | β | |
| Β§6 per-function checklist complete | β | |
| Β§7 invariants run (Foundry/Echidna) | β | |
Β§8 tooling gate passed (forge test, slither, fuzz) |
β | |
| Β§9 residual risks reviewed & accepted | β | |
| Compiler version pinned & recorded | β | |
| Constructor terms double-checked (creator/goal/deadline/milestones) | β | |
| External audit commissioned (recommended before mainnet value) | β |
Related: docs/SECURITY.md (summary) and /SECURITY.md (disclosure policy).