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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ npm run dev # 安装完成后,启动网页

## 3. 组员使用 Remix 部署合约

下面的 **0.8.24 / 优化开启 / Paris** 步骤用于按仓库默认配置部署当前合约。旧测试合约 `0x9b824CA674432B390E30A5164a76c04EeAa8f686` 是 **v1**,它的字节码复现见 [部署核对记录](docs/deployment-verification.md)。固定退款池和 `getExpiredRefundAmount` 报价接口都需要部署本版合约。先运行 `npm run compile:contract` 更新 ABI,部署后将新地址填入 `.env.local`。
下面的 **0.8.24 / 优化开启 / Paris** 步骤用于按仓库默认配置部署当前合约。旧测试合约 `0x9b824CA674432B390E30A5164a76c04EeAa8f686` 是 **v1**,它的字节码复现见 [部署核对记录](docs/deployment-verification.md)。要使用固定退款池、独立的阶段时限和链上报价,须部署本版合约。先运行 `npm run compile:contract` 更新 ABI,部署后将新地址填入 `.env.local`。

1. 在安装 MetaMask 的浏览器中打开 [Remix](https://remix.ethereum.org)。
2. 新建 `MilestoneFund.sol`,复制仓库中 `contracts/MilestoneFund.sol` 的全部内容。
Expand Down Expand Up @@ -164,8 +164,8 @@ npm run dev
| 多次出资 | 目标 0.01,B 先出 0.003,再出 0.007。累计应为 0.01,项目成功。 |
| 发起人不能自投 | A 打开自己的项目,应看到限制提示;在 Remix VM 直接调用也应失败。 |
| 超额及封顶 | 目标 0.01,B 出 0.012。只接受 0.01,0.002 当场退回,两阶段预算为 0.004 和 0.006。 |
| 审批超时退款 | 成果在审批窗口内未获通过,支持者可按出资比例领取。首笔成功退款将项目转为 Expired,后续支持者仍可领取。 |
| 提交超时退款 | 到期仍未提交成果时,切换两位支持者依次领取,确认第二位的链上报价不受首笔退款影响。 |
| 审批超时退款 | 每阶段从提交成果起计算审批截止时间。到期后未通过的阶段拒绝新投票,支持者可按出资比例领取退款。 |
| 提交超时退款 | 第一阶段从达标起算,第二阶段从第一阶段放款起算。到期后拒绝提交,切换两位支持者依次领取,确认第二位的报价不受首笔退款影响。 |
| 成果与权限 | 只有发起人能提交成果,同阶段不能重复提交或修改。 |
| 加权审批 | 恰好 50% 不通过,严格超过 50% 立即通过。详见下方示例。 |
| 提款权限 | 未批准不能提款,非发起人不能提款,已提阶段不能重复提款。 |
Expand All @@ -176,6 +176,8 @@ npm run dev

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

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

**50% 边界测试(Remix VM):**

1. A 创建目标 **100 wei** 的项目,B/C 为支持者,D 为无关账户。deadline 输入未来的 Unix 秒数,可在浏览器控制台计算 `Math.floor(Date.now() / 1000) + 3600` 后复制数值。
Expand Down
40 changes: 33 additions & 7 deletions contracts/MilestoneFund.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand All @@ -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");
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down
66 changes: 37 additions & 29 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
checkedContract,
injectedWallet,
readExpiredRefundAmount,
readMilestoneWindow,
readProvider,
switchToSepolia,
} from "./contract.js";
Expand Down Expand Up @@ -331,6 +332,7 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })
refunded,
approvals,
timeouts,
milestoneWindow,
expiredRefundAmount,
id,
} = data;
Expand Down Expand Up @@ -524,26 +526,26 @@ 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 =
isCurrentStage &&
contribution > 0n &&
!refunded &&
expiredRefundAmount === null &&
((approvalLeft !== null && approvalLeft <= 0) ||
(submitLeft !== null && submitLeft <= 0));
showWindowClosed;
const stateLabel = m.withdrawn
? "Released"
: m.approved
Expand Down Expand Up @@ -632,22 +634,22 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })
Needs more than 50% of contributed weight. Exactly 50% fails.
</p>

{(approvalLeft !== null || submitLeft !== null) && (
{secondsLeft !== null && (
<p className="form-note tight">
{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.`}
</p>
)}

<div className="milestone-actions">
{current && !m.submitted && isCreator && (
<form style={{ width: "100%" }} onSubmit={(e) => evidence(e, index)}>
<fieldset disabled={!ready || busy}>
<fieldset disabled={!ready || busy || actionWindowClosed}>
<label>
What did you deliver?
<textarea
Expand Down Expand Up @@ -675,7 +677,7 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose })
{current && m.submitted && !m.approved && contribution > 0n && (
<button
className="primary"
disabled={!ready || busy || approvals[index]}
disabled={!ready || busy || approvals[index] || actionWindowClosed}
onClick={() =>
transact(`Approve milestone ${index + 1}`, (c) =>
c.approveMilestone(id, index),
Expand Down Expand Up @@ -828,8 +830,7 @@ export default function App() {
refunded,
a0,
a1,
approvalTimeout,
submissionTimeout,
milestoneWindow,
expiredRefundAmount,
] = await Promise.all([
contract.getProject(selected, snapshot),
Expand All @@ -847,21 +848,28 @@ export default function App() {
account
? contract.hasApproved(selected, 1, account, snapshot)
: false,
// 0n means the deployed contract predates v2, so expiry hints stay hidden.
contract.APPROVAL_TIMEOUT(snapshot).catch(() => 0n),
contract.SUBMISSION_TIMEOUT(snapshot).catch(() => 0n),
readMilestoneWindow(contract, selected, snapshot),
account
? readExpiredRefundAmount(contract, selected, account, snapshot)
: 0n,
]);
let timeouts = null;
if (milestoneWindow === null) {
const [approval, submission] = await Promise.all([
contract.APPROVAL_TIMEOUT(snapshot).catch(() => 0n),
contract.SUBMISSION_TIMEOUT(snapshot).catch(() => 0n),
]);
timeouts = { approval, submission };
}
return {
id: selected,
project: project.toObject(),
milestones: [first.toObject(), second.toObject()],
contribution,
refunded,
approvals: [a0, a1],
timeouts: { approval: approvalTimeout, submission: submissionTimeout },
timeouts,
milestoneWindow,
expiredRefundAmount,
};
})(),
Expand Down
24 changes: 24 additions & 0 deletions src/abi/MilestoneFund.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
{
Expand Down
23 changes: 15 additions & 8 deletions src/contract.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,11 @@ export async function checkedContract(provider, config = CONFIG) {
return new Contract(getAddress(config.contractAddress), ABI, provider);
}

export async function readExpiredRefundAmount(
contract,
projectId,
account,
snapshot,
) {
async function readOptionalContractValue(read) {
try {
return await contract.getExpiredRefundAmount(projectId, account, snapshot);
return await read();
} catch (error) {
// Older deployments have no quote selector and return no data.
// Older deployments return no data for a selector they do not implement.
if (
(error?.code === "CALL_EXCEPTION" &&
(error.data === "0x" || error.data === null)) ||
Expand All @@ -103,6 +98,18 @@ export async function readExpiredRefundAmount(
}
}

export function readExpiredRefundAmount(contract, projectId, account, snapshot) {
return readOptionalContractValue(() =>
contract.getExpiredRefundAmount(projectId, account, snapshot),
);
}

export function readMilestoneWindow(contract, projectId, snapshot) {
return readOptionalContractValue(() =>
contract.getMilestoneWindow(projectId, snapshot),
);
}

export async function switchToSepolia() {
const wallet = injectedWallet();
if (!wallet) throw new Error("Install MetaMask, then reload this page.");
Expand Down
3 changes: 2 additions & 1 deletion tests/helpers/local-chain.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Loading
Loading