From b8b6aae3aeba5fda6af2e385aca9e4ec9f7f3519 Mon Sep 17 00:00:00 2001 From: Jack Date: Thu, 5 Nov 2026 07:39:09 +0800 Subject: [PATCH 1/3] fix(contract): enforce per-milestone time windows --- contracts/MilestoneFund.sol | 40 +++++++++++++++++++++++++++++------ src/abi/MilestoneFund.json | 24 +++++++++++++++++++++ tests/helpers/local-chain.mjs | 3 ++- tests/milestone-fund.test.mjs | 35 ++++++++++++++++++++++++++++-- 4 files changed, 92 insertions(+), 10 deletions(-) diff --git a/contracts/MilestoneFund.sol b/contracts/MilestoneFund.sol index e4b0f17..76d9e9d 100644 --- a/contracts/MilestoneFund.sol +++ b/contracts/MilestoneFund.sol @@ -37,7 +37,7 @@ contract MilestoneFund { /// @dev Fixed at deployment and immutable afterwards, so the rules cannot be /// changed later by anyone. A short value is useful for demos. uint256 public immutable APPROVAL_TIMEOUT; - /// @notice How long the creator has to submit evidence after funding succeeds. + /// @notice How long the creator has to submit evidence after each milestone opens. uint256 public immutable SUBMISSION_TIMEOUT; uint256 public projectCount; @@ -48,6 +48,7 @@ contract MilestoneFund { mapping(uint256 => mapping(address => bool)) public refunded; bool private entered; mapping(uint256 => uint256) private expiredRefundPools; + mapping(uint256 => uint256) private secondMilestoneOpenedAt; event ProjectCreated(uint256 indexed projectId, address indexed creator, uint256 target, uint256 deadline); event ContributionReceived(uint256 indexed projectId, address indexed backer, uint256 amount); @@ -150,6 +151,7 @@ contract MilestoneFund { require(milestone < 2 && milestone == p.currentMilestone, "Wrong milestone"); Milestone storage m = milestones[projectId][milestone]; require(!m.submitted, "Evidence already submitted"); + require(block.timestamp < _milestoneDeadline(projectId, p, m), "Submission window closed"); require(bytes(evidence).length > 0 && bytes(evidence).length <= 4000, "Invalid evidence"); require(bytes(evidenceUrl).length > 0 && bytes(evidenceUrl).length <= 1000, "Invalid evidence URL"); m.evidence = evidence; @@ -165,6 +167,7 @@ contract MilestoneFund { require(milestone < 2 && milestone == p.currentMilestone, "Wrong milestone"); Milestone storage m = milestones[projectId][milestone]; require(m.submitted && !m.approved, "Approval not open"); + require(block.timestamp < _milestoneDeadline(projectId, p, m), "Approval window closed"); uint256 weight = contributions[projectId][msg.sender]; require(weight > 0, "Backers only"); require(!hasApproved[projectId][milestone][msg.sender], "Already approved"); @@ -194,7 +197,11 @@ contract MilestoneFund { m.withdrawnAmount = amount; p.escrowBalance -= amount; p.currentMilestone++; - if (milestone == 1) p.status = ProjectStatus.Completed; + if (milestone == 0) { + secondMilestoneOpenedAt[projectId] = block.timestamp; + } else { + p.status = ProjectStatus.Completed; + } emit FundsWithdrawn(projectId, milestone, amount); if (milestone == 1) emit ProjectCompleted(projectId); // All accounting is committed before the external call. Failure rolls it back. @@ -248,19 +255,38 @@ contract MilestoneFund { return _expiredRefundAmount(projectId, p, backer); } + /// @notice The current submission or approval deadline and whether the window is open. + /// @dev A zero deadline means there is no pending submission or approval. + function getMilestoneWindow(uint256 projectId) + external view validProject(projectId) returns (uint256 deadline, bool open) + { + Project storage p = projects[projectId]; + if (p.status != ProjectStatus.Successful && p.status != ProjectStatus.Expired) return (0, false); + Milestone storage m = milestones[projectId][p.currentMilestone]; + if (m.approved) return (0, false); + deadline = _milestoneDeadline(projectId, p, m); + open = block.timestamp < deadline; + } + function _expiredRefundBlocker(uint256 projectId, Project storage p) private view returns (string memory) { if (p.status != ProjectStatus.Successful && p.status != ProjectStatus.Expired) return "Project not active"; if (p.currentMilestone >= 2) return "Project completed"; Milestone storage m = milestones[projectId][p.currentMilestone]; - if (m.submitted) { - if (m.approved) return "Milestone already approved"; - if (block.timestamp < m.submittedAt + APPROVAL_TIMEOUT) return "Approval window still open"; - } else if (block.timestamp < p.successfulAt + SUBMISSION_TIMEOUT) { - return "Submission window still open"; + if (m.approved) return "Milestone already approved"; + if (block.timestamp < _milestoneDeadline(projectId, p, m)) { + return m.submitted ? "Approval window still open" : "Submission window still open"; } return ""; } + function _milestoneDeadline(uint256 projectId, Project storage p, Milestone storage m) + private view returns (uint256) + { + if (m.submitted) return m.submittedAt + APPROVAL_TIMEOUT; + uint256 openedAt = p.currentMilestone == 0 ? p.successfulAt : secondMilestoneOpenedAt[projectId]; + return openedAt + SUBMISSION_TIMEOUT; + } + function _expiredRefundAmount(uint256 projectId, Project storage p, address backer) private view returns (uint256) { if (refunded[projectId][backer]) return 0; uint256 pool = p.status == ProjectStatus.Expired ? expiredRefundPools[projectId] : p.escrowBalance; diff --git a/src/abi/MilestoneFund.json b/src/abi/MilestoneFund.json index b46adfe..33dddae 100644 --- a/src/abi/MilestoneFund.json +++ b/src/abi/MilestoneFund.json @@ -544,6 +544,30 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "projectId", + "type": "uint256" + } + ], + "name": "getMilestoneWindow", + "outputs": [ + { + "internalType": "uint256", + "name": "deadline", + "type": "uint256" + }, + { + "internalType": "bool", + "name": "open", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [ { diff --git a/tests/helpers/local-chain.mjs b/tests/helpers/local-chain.mjs index 4a7beaf..3787f2e 100644 --- a/tests/helpers/local-chain.mjs +++ b/tests/helpers/local-chain.mjs @@ -96,7 +96,8 @@ export async function localChain( isStatic: true, skipNonceIncrement: true, }); assert.equal(result.execResult.exceptionError, undefined, `Read ${name} failed`); - return target.iface.decodeFunctionResult(name, bytesToHex(result.execResult.returnValue))[0]; + const decoded = target.iface.decodeFunctionResult(name, bytesToHex(result.execResult.returnValue)); + return decoded.length === 1 ? decoded[0] : decoded; } const balance = async (address = fund.address) => (await vm.stateManager.getAccount(address))?.balance ?? 0n; async function fundFingerprint() { diff --git a/tests/milestone-fund.test.mjs b/tests/milestone-fund.test.mjs index e3d56c8..3cb1f18 100644 --- a/tests/milestone-fund.test.mjs +++ b/tests/milestone-fund.test.mjs @@ -15,6 +15,10 @@ async function payout(h, id, stage, amount) { assert.equal(await h.balance(h.accounts.A.address), before + amount - result.fee); return result; } +async function assertWindow(h, id, deadline, open) { + const window = await h.read("getMilestoneWindow", [id]); + assert.deepEqual(window.toArray(), [deadline, open]); +} for (const profile of profiles) { const artifacts = compileFixtures(profile); @@ -27,12 +31,18 @@ for (const profile of profiles) { await h.send("B", "contribute", [id], { value: 10n }); assert.equal(await h.read("contributions", [id, h.address("B")]), 50n); assert.equal((await h.read("getProject", [id])).status, 0n); + await assertWindow(h, id, 0n, false); const funded = await h.send("C", "contribute", [id], { value: 50n }); assert.equal(event(funded, "FundingSuccessful").totalRaised, 100n); + const submissionDeadline = h.now() + await h.read("SUBMISSION_TIMEOUT"); + await assertWindow(h, id, submissionDeadline, true); await h.send("D", "contribute", [id], { value: 1n, revert: "Funding closed" }); await h.send("B", "approveMilestone", [id, 0], { revert: "Approval not open" }); await h.send("B", "submitEvidence", evidence(id, 0), { revert: "Creator only" }); + h.at(submissionDeadline - 1n); await h.send("A", "submitEvidence", evidence(id, 0)); + const approvalDeadline = h.now() + await h.read("APPROVAL_TIMEOUT"); + await assertWindow(h, id, approvalDeadline, true); await h.send("A", "submitEvidence", evidence(id, 0), { revert: "Evidence already submitted" }); await h.send("D", "approveMilestone", [id, 0], { revert: "Backers only" }); await h.send("B", "approveMilestone", [id, 0]); @@ -42,8 +52,11 @@ for (const profile of profiles) { await h.send("B", "approveMilestone", [id, 0], { revert: "Already approved" }); await h.send("A", "withdrawMilestone", [id, 0], { revert: "Milestone not withdrawable" }); await h.send("A", "submitEvidence", evidence(id, 1), { revert: "Wrong milestone" }); + h.at(approvalDeadline - 1n); const approved = await h.send("C", "approveMilestone", [id, 0]); assert.equal(event(approved, "MilestoneApproved").milestone, 0n); + await assertWindow(h, id, 0n, false); + h.at(approvalDeadline + 1n); await h.send("B", "withdrawMilestone", [id, 0], { revert: "Creator only" }); await payout(h, id, 0, 40n); assert.equal(await h.balance(), 60n); @@ -64,6 +77,7 @@ for (const profile of profiles) { assert.equal(project.escrowBalance, 0n); assert.equal(project.totalRaised, 100n); assert.equal(await h.balance(), 0n); + await assertWindow(h, id, 0n, false); await h.send("A", "withdrawMilestone", [id, 1], { revert: "Project not successful" }); await h.send("B", "claimRefund", [id], { revert: "Project not failed" }); }); @@ -206,11 +220,17 @@ for (const profile of profiles) { await h.send(backer, "contribute", [id], { value: contributions[backer] }); } await h.send("A", "submitEvidence", evidence(id, 0)); + const deadline = h.now() + timeout; const quote = (backer) => h.read("getExpiredRefundAmount", [id, h.address(backer)]); + h.at(deadline - 1n); + await h.send("C", "approveMilestone", [id, 0]); + await assertWindow(h, id, deadline, true); assert.equal(await quote(first), 0n); await h.send(first, "claimExpiredRefund", [id], { revert: "Approval window still open" }); - h.at(h.now() + timeout); + h.at(deadline); + await assertWindow(h, id, deadline, false); + await h.send("B", "approveMilestone", [id, 0], { revert: "Approval window closed" }); assert.equal(await quote("D"), 0n); await h.send("D", "claimExpiredRefund", [id], { revert: "No refund available" }); assert.equal(await quote(second), contributions[second]); @@ -247,10 +267,18 @@ for (const profile of profiles) { await h.send("C", "contribute", [id], { value: 43n }); await h.send("A", "submitEvidence", evidence(id, 0)); await h.send("B", "approveMilestone", [id, 0]); + h.at(h.now() + timeout + 1n); await payout(h, id, 0, 41n); assert.equal(await h.balance(), 62n); - h.at(h.now() + timeout); + const deadline = h.now() + timeout; + await assertWindow(h, id, deadline, true); + h.at(deadline - 1n); + assert.equal(await h.read("getExpiredRefundAmount", [id, h.address("B")]), 0n); + await h.send("B", "claimExpiredRefund", [id], { revert: "Submission window still open" }); + h.at(deadline); + await assertWindow(h, id, deadline, false); + await h.send("A", "submitEvidence", evidence(id, 1), { revert: "Submission window closed" }); for (const [backer, expected] of [["C", 25n], ["B", 36n]]) { assert.equal(await h.read("getExpiredRefundAmount", [id, h.address(backer)]), expected); const refund = await h.send(backer, "claimExpiredRefund", [id]); @@ -302,9 +330,12 @@ for (const profile of profiles) { const successfulAt = h.now(); await h.send("B", "claimExpiredRefund", [id], { revert: "Submission window still open" }); h.at(successfulAt + timeout); + await assertWindow(h, id, successfulAt + timeout, false); + await h.send("A", "submitEvidence", evidence(id, 0), { revert: "Submission window closed" }); const refund = await h.send("B", "claimExpiredRefund", [id]); assert.equal(event(refund, "RefundClaimed").amount, 100n); assert.equal((await h.read("getProject", [id])).status, 4n); + await assertWindow(h, id, successfulAt + timeout, false); assert.equal(await h.balance(), 0n); }); From 272e41f2edbf538a9e029d4a6607b865d8de35e6 Mon Sep 17 00:00:00 2001 From: Jack Date: Thu, 5 Nov 2026 07:39:10 +0800 Subject: [PATCH 2/3] fix(ui): read the active milestone window from the contract --- src/App.jsx | 66 ++++++++++++++++++++++++------------------- src/contract.js | 23 +++++++++------ tests/wallet.test.mjs | 26 +++++++++++++++++ 3 files changed, 78 insertions(+), 37 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index 0fea4f7..72ba6de 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -11,6 +11,7 @@ import { checkedContract, injectedWallet, readExpiredRefundAmount, + readMilestoneWindow, readProvider, switchToSepolia, } from "./contract.js"; @@ -331,6 +332,7 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) refunded, approvals, timeouts, + milestoneWindow, expiredRefundAmount, id, } = data; @@ -524,17 +526,18 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) const isCurrentStage = BigInt(index) === p.currentMilestone; const current = p.status === 1n && isCurrentStage; const projected = p.status === 0n; - const approvalLeft = - m.submitted && !m.approved && timeouts?.approval > 0n - ? Number(m.submittedAt + timeouts.approval) - now - : null; - const submitLeft = - isCurrentStage && - !m.submitted && - (p.status === 1n || p.status === 4n) && - timeouts?.submission > 0n - ? Number(p.successfulAt + timeouts.submission) - now - : null; + const hasPendingWindow = + isCurrentStage && (p.status === 1n || p.status === 4n) && !m.approved; + const legacyTimeout = m.submitted ? timeouts?.approval : timeouts?.submission; + const legacyOpenedAt = m.submitted ? m.submittedAt : p.successfulAt; + const deadline = hasPendingWindow + ? milestoneWindow?.deadline ?? (legacyTimeout > 0n ? legacyOpenedAt + legacyTimeout : 0n) + : 0n; + const secondsLeft = deadline > 0n ? Number(deadline) - now : null; + const actionWindowClosed = hasPendingWindow && milestoneWindow?.open === false; + const showWindowClosed = milestoneWindow + ? actionWindowClosed + : secondsLeft !== null && secondsLeft <= 0; const canExpireRefund = isCurrentStage && (expiredRefundAmount ?? 0n) > 0n; const missingRefundQuote = @@ -542,8 +545,7 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) contribution > 0n && !refunded && expiredRefundAmount === null && - ((approvalLeft !== null && approvalLeft <= 0) || - (submitLeft !== null && submitLeft <= 0)); + showWindowClosed; const stateLabel = m.withdrawn ? "Released" : m.approved @@ -632,22 +634,22 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) Needs more than 50% of contributed weight. Exactly 50% fails.

- {(approvalLeft !== null || submitLeft !== null) && ( + {secondsLeft !== null && (

- {approvalLeft !== null - ? approvalLeft > 0 - ? `Approval closes in ${remainingText(approvalLeft)}.` - : "Approval window closed. Backers can reclaim the remaining escrow." - : submitLeft > 0 - ? `Creator has ${remainingText(submitLeft)} to submit evidence.` - : "No evidence submitted in time. Backers can reclaim the remaining escrow."} + {m.submitted + ? showWindowClosed + ? "Approval window closed. Backers can reclaim the remaining escrow." + : `Approval closes in ${remainingText(secondsLeft)}.` + : showWindowClosed + ? "No evidence submitted in time. Backers can reclaim the remaining escrow." + : `Creator has ${remainingText(secondsLeft)} to submit evidence.`}

)}
{current && !m.submitted && isCreator && (
evidence(e, index)}> -
+