Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# MilestoneFund

COMP7610 课程项目:支持者为项目出资,项目方按两个里程碑提交成果。支持者审批通过后,项目方依次提取 40% 和剩余 60% 的资金。仅使用 Sepolia 测试 ETH。合约 v2 起:出资封顶于目标金额(超额当场退回);审批或成果提交超时后,支持者可按贡献比例取回剩余托管资金。
COMP7610 课程项目:支持者为项目出资,项目方按两个里程碑提交成果。支持者审批通过后,任何账户都能释放该阶段的资金,第一阶段为 40%,第二阶段为余款。发起人领取已释放资金。仅使用 Sepolia 测试 ETH。出资封顶于目标金额(超额当场退回);审批或成果提交超时后,支持者可按贡献比例取回剩余托管资金。

**测试方式:组员用 Remix 部署合约,大家在各自电脑启动网页,通过 MetaMask 手动操作。** 只需一位组员部署到 Sepolia,再把合约地址发给其他人。

Expand Down Expand Up @@ -143,15 +143,17 @@ npm run dev
| 2 | B 打开该项目,出资 **0.01 ETH**。 | 显示 Successful,已筹和托管金额均为 0.01,停止接受出资。 |
| 3 | A 提交第一阶段成果说明和真实 GitHub/Demo 链接。 | 成果可查看,阶段显示 In review。 |
| 4 | B 审批第一阶段。 | 赞成权重 100%,显示 Approved。 |
| 5 | A 提取第一阶段资金。 | 提取 **0.004 ETH**,托管剩 **0.006 ETH**。 |
| 5 | A 点击 **Release & withdraw**,释放并提取第一阶段资金。 | 提取 **0.004 ETH**,托管剩 **0.006 ETH**。 |
| 6 | A 提交第二阶段成果和链接。 | 第二阶段显示 In review。 |
| 7 | B 审批第二阶段。 | 第二阶段显示 Approved。 |
| 8 | A 提取第二阶段资金。 | 提取 **0.006 ETH**,托管余额为 0,项目显示 Completed。 |
| 8 | A 点击 **Release & withdraw**,释放并提取第二阶段资金。 | 提取 **0.006 ETH**,托管余额为 0,项目显示 Completed。 |
| 9 | 刷新网页并重新打开项目。 | 完成状态及提款记录仍然正确。 |
| 10 | 打开页面中的交易链接。 | Sepolia Etherscan 能查到真实成功交易。 |

网页应显示钱包确认中、交易处理中、成功或失败提示。保存项目 ID、交易哈希和截图。钱包余额变化包含 gas,检查提款金额主要看页面记录和交易事件。

也可以在步骤 5 让 B 点击 **Release to creator balance**。这会开启第二阶段,并将 **0.004 ETH** 计入发起人的待领取余额。切换回 A 后,点击 **Withdraw payout** 领取。收款地址留空时发到 A 的钱包,也可以填写其他收款地址。若收款地址拒收 ETH,余额保留,A 可更换地址后重试。

## 6. 主要测试功能

不同场景尽量创建新项目,记录“通过、失败或未测试”。
Expand All @@ -165,18 +167,18 @@ npm run dev
| 发起人不能自投 | A 打开自己的项目,应看到限制提示;在 Remix VM 直接调用也应失败。 |
| 超额及封顶 | 目标 0.01,B 出 0.012。只接受 0.01,0.002 当场退回,两阶段预算为 0.004 和 0.006。 |
| 审批超时退款 | 每阶段从提交成果起计算审批截止时间。到期后未通过的阶段拒绝新投票,支持者可按出资比例领取退款。 |
| 提交超时退款 | 第一阶段从达标起算,第二阶段从第一阶段放款起算。到期后拒绝提交,切换两位支持者依次领取,确认第二位的报价不受首笔退款影响。 |
| 提交超时退款 | 第一阶段从达标起算,第二阶段从第一阶段释放时起算。到期后拒绝提交,切换两位支持者依次领取,确认第二位的报价不受首笔退款影响。 |
| 成果与权限 | 只有发起人能提交成果,同阶段不能重复提交或修改。 |
| 加权审批 | 恰好 50% 不通过,严格超过 50% 立即通过。详见下方示例。 |
| 提款权限 | 未批准不能提款,非发起人不能提款,已提阶段不能重复提款。 |
| 阶段顺序 | 第一阶段提款后,才能提交第二阶段。 |
| 释放与提款权限 | 任何账户都能释放已批准阶段,只有发起人能领取已释放款项。已释放的阶段不能重复释放。 |
| 阶段顺序 | 第一阶段释放后即可提交第二阶段。已计入发起人待领取余额的金额不参与退款。 |
| 重复操作 | 重复投票、提款或成果提交应失败,不改变金额或权重。 |
| 拒绝签名 | 在 MetaMask 拒绝交易,应显示拒绝提示并允许重试,不能显示成功。 |
| 刷新恢复 | 刷新后,金额、成果和状态应从合约正确读回。 |

网页会隐藏或禁用不允许的操作。验证合约本身是否拒绝时,请在 **Remix VM** 中选对应账户直接调用。只有 `contribute` 需要填写 Remix 的 Value,其他调用要把 Value 改回 **0**。项目编号从 0 开始;第一阶段参数是 0,第二阶段是 1。

提交成果和投票都必须在链上截止秒之前确认。到达截止秒时,未完成的提交或审批窗口关闭,符合条件的支持者可以退款。已在截止前批准的阶段仍可在之后提款。网页通过 `getMilestoneWindow` 读取当前截止时间和开关状态。
提交成果和投票都必须在链上截止秒之前确认。到达截止秒时,未完成的提交或审批窗口关闭,符合条件的支持者可以退款。已在截止前批准的阶段仍可在之后释放。网页通过 `getMilestoneWindow` 读取当前截止时间和开关状态。

短超时演示可使用两个均有出资的支持者账户。倒计时归零后,等页面确认链上已截止,再用第一位支持者领取。核对交易成功提示的实付金额,切换到第二位支持者,确认其可领金额仍与首笔领取前一致。筹款失败的退款为全额出资,里程碑超时退款按未放款的托管金额计算。

Expand Down
55 changes: 42 additions & 13 deletions contracts/MilestoneFund.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
pragma solidity ^0.8.24;

/// @title MilestoneFund Lite - two-stage, contribution-weighted crowdfunding.
/// @notice Educational prototype. No owner, admin withdrawal, or fee. Funds can no
/// longer lock forever: an approval that times out, or evidence the creator never
/// submits, lets backers reclaim their share of the remaining escrow.
/// @notice Educational prototype. No owner, admin withdrawal, or fee. Anyone can
/// release an approved milestone. Only the creator can claim the released payout.
contract MilestoneFund {
enum ProjectStatus { Funding, Successful, Failed, Completed, Expired }

Expand All @@ -26,6 +25,7 @@ contract MilestoneFund {
string evidence;
string evidenceUrl;
uint256 approvalWeight;
// The amount released from escrow, including funds credited for later claim.
uint256 withdrawnAmount;
uint256 submittedAt;
bool submitted;
Expand All @@ -49,6 +49,7 @@ contract MilestoneFund {
bool private entered;
mapping(uint256 => uint256) private expiredRefundPools;
mapping(uint256 => uint256) private secondMilestoneOpenedAt;
mapping(uint256 => uint256) public claimablePayouts;

event ProjectCreated(uint256 indexed projectId, address indexed creator, uint256 target, uint256 deadline);
event ContributionReceived(uint256 indexed projectId, address indexed backer, uint256 amount);
Expand All @@ -57,7 +58,9 @@ contract MilestoneFund {
event EvidenceSubmitted(uint256 indexed projectId, uint8 indexed milestone, string evidence, string evidenceUrl);
event ApprovalCast(uint256 indexed projectId, uint8 indexed milestone, address indexed backer, uint256 weight);
event MilestoneApproved(uint256 indexed projectId, uint8 indexed milestone);
event MilestoneReleased(uint256 indexed projectId, uint8 indexed milestone, uint256 amount);
event FundsWithdrawn(uint256 indexed projectId, uint8 indexed milestone, uint256 amount);
event PayoutClaimed(uint256 indexed projectId, address indexed recipient, uint256 amount);
event ProjectCompleted(uint256 indexed projectId);
event RefundClaimed(uint256 indexed projectId, address indexed backer, uint256 amount);
event ExcessRefunded(uint256 indexed projectId, address indexed backer, uint256 amount);
Expand Down Expand Up @@ -181,16 +184,44 @@ contract MilestoneFund {
}
}

/// @notice First stage gets floor(totalRaised * 40 / 100); second gets remainder.
/// @notice Release and pay an approved milestone to the creator in one transaction.
function withdrawMilestone(uint256 projectId, uint8 milestone) external validProject(projectId) nonReentrant {
Project storage p = projects[projectId];
require(msg.sender == p.creator, "Creator only");
uint256 amount = _releaseMilestone(projectId, milestone, p);
emit FundsWithdrawn(projectId, milestone, amount);
if (milestone == 1) emit ProjectCompleted(projectId);
_sendPayout(p.creator, amount);
}

/// @notice Advance an approved milestone and credit its payout without sending ETH.
function releaseMilestone(uint256 projectId, uint8 milestone) external validProject(projectId) nonReentrant {
uint256 amount = _releaseMilestone(projectId, milestone, projects[projectId]);
claimablePayouts[projectId] += amount;
emit MilestoneReleased(projectId, milestone, amount);
if (milestone == 1) emit ProjectCompleted(projectId);
}

/// @notice The creator can collect the project's released payouts at a chosen address.
function claimPayout(uint256 projectId, address payable recipient) external validProject(projectId) nonReentrant {
require(msg.sender == projects[projectId].creator, "Creator only");
require(recipient != address(0), "Invalid payout recipient");
uint256 amount = claimablePayouts[projectId];
require(amount > 0, "No payout available");
claimablePayouts[projectId] = 0;
emit PayoutClaimed(projectId, recipient, amount);
_sendPayout(recipient, amount);
}

function _releaseMilestone(uint256 projectId, uint8 milestone, Project storage p)
private returns (uint256 amount)
{
require(p.status == ProjectStatus.Successful, "Project not successful");
require(milestone < 2 && milestone == p.currentMilestone, "Wrong milestone");
Milestone storage m = milestones[projectId][milestone];
require(m.approved && !m.withdrawn, "Milestone not withdrawable");
// floor(total * 2 / 5), split into quotient and remainder to avoid overflow.
uint256 amount = milestone == 0
amount = milestone == 0
? (p.totalRaised / 5) * 2 + (p.totalRaised % 5) * 2 / 5
: p.escrowBalance;
m.withdrawn = true;
Expand All @@ -202,14 +233,12 @@ contract MilestoneFund {
} 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.
// A zero payout skips the call entirely, so a rejecting creator cannot block it.
if (amount > 0) {
(bool sent,) = p.creator.call{value: amount}("");
require(sent, "ETH transfer failed");
}
}

function _sendPayout(address payable recipient, uint256 amount) private {
if (amount == 0) return;
(bool sent,) = recipient.call{value: amount}("");
require(sent, "ETH transfer failed");
}

function claimRefund(uint256 projectId) external validProject(projectId) nonReentrant {
Expand Down
97 changes: 78 additions & 19 deletions src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { BrowserProvider, getAddress } from "ethers";
import { BrowserProvider, ZeroAddress, getAddress } from "ethers";
import {
CONFIGURED,
CONFIG_ERROR,
Expand Down Expand Up @@ -319,6 +319,7 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })
approvals,
milestoneWindow,
expiredRefundAmount,
claimablePayout,
blockTimestamp,
id,
} = data;
Expand Down Expand Up @@ -369,6 +370,18 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })
setError(errorMessage(e));
}
}
async function withdrawPayout(event) {
event.preventDefault();
setError("");
try {
const enteredAddress = new FormData(event.currentTarget).get("recipient").trim();
const recipient = getAddress(enteredAddress || account);
if (recipient === ZeroAddress) throw new Error("Enter a nonzero payout recipient address.");
await transact("Withdraw released payout", (c) => c.claimPayout(id, recipient));
} catch (e) {
setError(errorMessage(e));
}
}

return (
<section className="detail-panel" aria-label="Project details">
Expand Down Expand Up @@ -434,6 +447,32 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })
</div>
</div>

{claimablePayout > 0n && (
<section aria-label="Creator payout">
<div className="stat highlight">
<span>Creator payout available</span>
<strong><Eth value={claimablePayout} /></strong>
</div>
{isCreator && (
<form className="payout-form" onSubmit={withdrawPayout}>
<label>
Recipient address · defaults to your wallet
<input
name="recipient"
placeholder={account}
spellCheck={false}
autoComplete="off"
disabled={!ready || busy}
/>
</label>
<button className="primary" disabled={!ready || busy}>
Withdraw payout
</button>
</form>
)}
</section>
)}

{refunded && (
<p className="success-note">
✓ Your refund has been paid.
Expand Down Expand Up @@ -507,19 +546,20 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })

{p.status === 3n && (
<p className="success-note">
✓ Both milestones are complete. All project funds have been released.
✓ Both milestones are complete. All funds have been released from escrow.
</p>
)}

<div className="section-heading milestone-heading">
<h3>The milestones</h3>
<span>Evidence → Approval → Withdrawal</span>
<span>Evidence → Approval → Release</span>
</div>

{milestones.map((m, index) => {
const isCurrentStage = BigInt(index) === p.currentMilestone;
const current = p.status === 1n && isCurrentStage;
const projected = p.status === 0n;
const stageBudget = budget(p.totalRaised, index);
const deadline =
isCurrentStage && milestoneWindow?.deadline > 0n
? deadlineView(milestoneWindow.deadline, milestoneWindow.open, now)
Expand Down Expand Up @@ -571,15 +611,15 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })
<b>
{projected && p.totalRaised === 0n
? "—"
: `${eth(budget(p.totalRaised, index))} ETH`}
: `${eth(stageBudget)} ETH`}
</b>
{projected && p.totalRaised > 0n && (
<> of {eth(p.totalRaised)} ETH raised</>
)}
</span>
{m.withdrawn && (
<span>
Released: <b>{eth(m.withdrawnAmount)} ETH</b>
Released from escrow: <b>{eth(m.withdrawnAmount)} ETH</b>
</span>
)}
</div>
Expand Down Expand Up @@ -682,20 +722,36 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })
: `Approve · ${eth(contribution)} ETH weight`}
</button>
)}
{current && m.approved && !m.withdrawn && isCreator && (
<button
className="primary"
disabled={!ready || busy}
onClick={() =>
transact(`Withdraw milestone ${index + 1}`, (c) =>
c.withdrawMilestone(id, index),
)
}
>
{budget(p.totalRaised, index) === 0n
? "Withdraw · 0 ETH, advances the stage"
: `Withdraw · ${eth(budget(p.totalRaised, index))} ETH ↗`}
</button>
{current && m.approved && !m.withdrawn && (
<>
{isCreator && stageBudget > 0n && (
<button
className="primary"
disabled={!ready || busy}
onClick={() =>
transact(`Release and withdraw milestone ${index + 1}`, (c) =>
c.withdrawMilestone(id, index),
)
}
>
Release &amp; withdraw · {eth(stageBudget)} ETH
</button>
)}
<button
className={isCreator && stageBudget > 0n ? "ghost" : "primary"}
disabled={!ready || busy}
onClick={() =>
transact(`Release milestone ${index + 1}`, (c) =>
c.releaseMilestone(id, index),
)
}
>
{stageBudget === 0n ? "Release milestone · 0 ETH" : "Release to creator balance"}
</button>
<p className="form-note tight">
Anyone can release this stage. Only the creator can withdraw its payout.
</p>
</>
)}
{refundState === "unavailable" && (
<p className="form-note">
Expand Down Expand Up @@ -851,6 +907,7 @@ export default function App() {
a1,
milestoneWindow,
expiredRefundAmount,
claimablePayout,
] = await Promise.all([
contract.getProject(selected, snapshot),
contract.getMilestone(selected, 0, snapshot),
Expand All @@ -871,6 +928,7 @@ export default function App() {
account
? readExpiredRefundAmount(contract, selected, account, snapshot)
: 0n,
contract.claimablePayouts(selected, snapshot),
]);
return {
id: selected,
Expand All @@ -883,6 +941,7 @@ export default function App() {
approvals: [a0, a1],
milestoneWindow,
expiredRefundAmount,
claimablePayout,
};
})(),
]);
Expand Down
Loading
Loading