diff --git a/README.md b/README.md index 8e046bd..e6bee12 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MilestoneFund -COMP7610 课程项目:支持者为项目出资,项目方按两个里程碑提交成果。支持者审批通过后,项目方依次提取 40% 和剩余 60% 的资金。仅使用 Sepolia 测试 ETH。合约 v2 起:出资封顶于目标金额(超额当场退回);审批或成果提交超时后,支持者可按贡献比例取回剩余托管资金。 +COMP7610 课程项目:支持者为项目出资,项目方按两个里程碑提交成果。支持者审批通过后,任何账户都能释放该阶段的资金,第一阶段为 40%,第二阶段为余款。发起人领取已释放资金。仅使用 Sepolia 测试 ETH。出资封顶于目标金额(超额当场退回);审批或成果提交超时后,支持者可按贡献比例取回剩余托管资金。 **测试方式:组员用 Remix 部署合约,大家在各自电脑启动网页,通过 MetaMask 手动操作。** 只需一位组员部署到 Sepolia,再把合约地址发给其他人。 @@ -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. 主要测试功能 不同场景尽量创建新项目,记录“通过、失败或未测试”。 @@ -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` 读取当前截止时间和开关状态。 短超时演示可使用两个均有出资的支持者账户。倒计时归零后,等页面确认链上已截止,再用第一位支持者领取。核对交易成功提示的实付金额,切换到第二位支持者,确认其可领金额仍与首笔领取前一致。筹款失败的退款为全额出资,里程碑超时退款按未放款的托管金额计算。 diff --git a/contracts/MilestoneFund.sol b/contracts/MilestoneFund.sol index 76d9e9d..0604eb1 100644 --- a/contracts/MilestoneFund.sol +++ b/contracts/MilestoneFund.sol @@ -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 } @@ -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; @@ -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); @@ -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); @@ -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; @@ -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 { diff --git a/src/App.jsx b/src/App.jsx index 80f527c..0b5e7e3 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -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, @@ -319,6 +319,7 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) approvals, milestoneWindow, expiredRefundAmount, + claimablePayout, blockTimestamp, id, } = data; @@ -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 (
@@ -434,6 +447,32 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) + {claimablePayout > 0n && ( +
+
+ Creator payout available + +
+ {isCreator && ( +
+ + +
+ )} +
+ )} + {refunded && (

✓ Your refund has been paid. @@ -507,19 +546,20 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) {p.status === 3n && (

- ✓ Both milestones are complete. All project funds have been released. + ✓ Both milestones are complete. All funds have been released from escrow.

)}

The milestones

- Evidence → Approval → Withdrawal + Evidence → Approval → Release
{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) @@ -571,7 +611,7 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) {projected && p.totalRaised === 0n ? "—" - : `${eth(budget(p.totalRaised, index))} ETH`} + : `${eth(stageBudget)} ETH`} {projected && p.totalRaised > 0n && ( <> of {eth(p.totalRaised)} ETH raised @@ -579,7 +619,7 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) {m.withdrawn && ( - Released: {eth(m.withdrawnAmount)} ETH + Released from escrow: {eth(m.withdrawnAmount)} ETH )} @@ -682,20 +722,36 @@ function ProjectDetails({ data, account, ready, busy, now, transact, onClose }) : `Approve · ${eth(contribution)} ETH weight`} )} - {current && m.approved && !m.withdrawn && isCreator && ( - + {current && m.approved && !m.withdrawn && ( + <> + {isCreator && stageBudget > 0n && ( + + )} + +

+ Anyone can release this stage. Only the creator can withdraw its payout. +

+ )} {refundState === "unavailable" && (

@@ -851,6 +907,7 @@ export default function App() { a1, milestoneWindow, expiredRefundAmount, + claimablePayout, ] = await Promise.all([ contract.getProject(selected, snapshot), contract.getMilestone(selected, 0, snapshot), @@ -871,6 +928,7 @@ export default function App() { account ? readExpiredRefundAmount(contract, selected, account, snapshot) : 0n, + contract.claimablePayouts(selected, snapshot), ]); return { id: selected, @@ -883,6 +941,7 @@ export default function App() { approvals: [a0, a1], milestoneWindow, expiredRefundAmount, + claimablePayout, }; })(), ]); diff --git a/src/abi/MilestoneFund.json b/src/abi/MilestoneFund.json index 33dddae..b0e6c63 100644 --- a/src/abi/MilestoneFund.json +++ b/src/abi/MilestoneFund.json @@ -203,6 +203,56 @@ "name": "MilestoneApproved", "type": "event" }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "uint256", + "name": "projectId", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "uint8", + "name": "milestone", + "type": "uint8" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "MilestoneReleased", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "uint256", + "name": "projectId", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "address", + "name": "recipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "PayoutClaimed", + "type": "event" + }, { "anonymous": false, "inputs": [ @@ -342,6 +392,24 @@ "stateMutability": "nonpayable", "type": "function" }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "projectId", + "type": "uint256" + }, + { + "internalType": "address payable", + "name": "recipient", + "type": "address" + } + ], + "name": "claimPayout", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, { "inputs": [ { @@ -355,6 +423,25 @@ "stateMutability": "nonpayable", "type": "function" }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "name": "claimablePayouts", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [ { @@ -705,6 +792,24 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "projectId", + "type": "uint256" + }, + { + "internalType": "uint8", + "name": "milestone", + "type": "uint8" + } + ], + "name": "releaseMilestone", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, { "inputs": [ { diff --git a/src/styles.css b/src/styles.css index 64bbf12..4e3eeda 100644 --- a/src/styles.css +++ b/src/styles.css @@ -943,7 +943,8 @@ button:disabled { .stat.highlight > strong { color: var(--accent-ink); } -.contribute-form { +.contribute-form, +.payout-form { display: flex; align-items: flex-end; gap: 12px; @@ -953,7 +954,8 @@ button:disabled { border-radius: var(--radius-sm); background: var(--surface-2); } -.contribute-form label { +.contribute-form label, +.payout-form label { flex: 1; margin: 0; } @@ -1456,7 +1458,8 @@ footer .brand { .detail-stats { grid-template-columns: 1fr; } - .contribute-form { + .contribute-form, + .payout-form { flex-direction: column; align-items: stretch; } diff --git a/tests/fixtures/PaymentReceiver.sol b/tests/fixtures/PaymentReceiver.sol index c428a11..f2d03ec 100644 --- a/tests/fixtures/PaymentReceiver.sol +++ b/tests/fixtures/PaymentReceiver.sol @@ -6,9 +6,13 @@ import "MilestoneFund.sol"; // Local-test fixture: verifies that a rejected ETH transfer rolls back accounting. contract PaymentReceiver { MilestoneFund public immutable fund; + address private immutable owner; bool public rejectPayments = true; - constructor(address fundAddress) { fund = MilestoneFund(fundAddress); } + constructor(address fundAddress) { + fund = MilestoneFund(fundAddress); + owner = msg.sender; + } function create(uint256 target, uint256 deadline) external { fund.createProject("Receiver project", "Transfer rollback test", target, deadline, "First", "Second"); @@ -18,6 +22,10 @@ contract PaymentReceiver { function evidenceFor(uint256 projectId, uint8 milestone) external { fund.submitEvidence(projectId, milestone, "Delivered", "https://example.com/demo"); } function withdraw(uint256 projectId) external { fund.withdrawMilestone(projectId, 0); } function withdrawFor(uint256 projectId, uint8 milestone) external { fund.withdrawMilestone(projectId, milestone); } + function claimPayoutTo(uint256 projectId, address payable recipient) external { + require(msg.sender == owner, "Receiver owner only"); + fund.claimPayout(projectId, recipient); + } function refund(uint256 projectId) external { fund.claimRefund(projectId); } function expiredRefund(uint256 projectId) external { fund.claimExpiredRefund(projectId); } function allowPayments() external { rejectPayments = false; } diff --git a/tests/milestone-fund.test.mjs b/tests/milestone-fund.test.mjs index 3cb1f18..2c8e1f9 100644 --- a/tests/milestone-fund.test.mjs +++ b/tests/milestone-fund.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; +import { ZeroAddress } from "ethers"; import { compileFixtures, localChain, profiles } from "./helpers/local-chain.mjs"; const evidence = (id, stage) => [id, stage, "Delivered for testing", "https://example.com/demo"]; @@ -210,6 +211,97 @@ for (const profile of profiles) { assert.equal(await h.balance(), 60n); }); + test(`${profile.name}: anyone can release two approved milestones and only the creator can collect`, async () => { + const h = await localChain(artifacts); + const id = await h.create(); + const recipient = h.address("C"); + await h.send("B", "contribute", [id], { value: 100n }); + await h.send("D", "releaseMilestone", [id, 0], { revert: "Milestone not withdrawable" }); + await h.send("A", "submitEvidence", evidence(id, 0)); + await h.send("B", "approveMilestone", [id, 0]); + h.at(h.now() + await h.read("APPROVAL_TIMEOUT")); + const first = await h.send("D", "releaseMilestone", [id, 0]); + assert.equal(event(first, "MilestoneReleased").amount, 40n); + assert.equal((await h.read("getProject", [id])).escrowBalance, 60n); + assert.equal(await h.read("claimablePayouts", [id]), 40n); + assert.equal(await h.balance(), 100n, "Releasing must not send any ETH"); + await assertWindow(h, id, h.now() + await h.read("SUBMISSION_TIMEOUT"), true); + await h.send("D", "releaseMilestone", [id, 0], { revert: "Wrong milestone" }); + await h.send("D", "claimPayout", [id, h.address("D")], { revert: "Creator only" }); + await h.send("A", "claimPayout", [id, ZeroAddress], { revert: "Invalid payout recipient" }); + + await h.send("A", "submitEvidence", evidence(id, 1)); + await h.send("B", "approveMilestone", [id, 1]); + const second = await h.send("D", "releaseMilestone", [id, 1]); + assert.equal(event(second, "MilestoneReleased").amount, 60n); + assert.equal(event(second, "ProjectCompleted").projectId, id); + assert.equal((await h.read("getProject", [id])).escrowBalance, 0n); + assert.equal((await h.read("getProject", [id])).status, 3n); + assert.equal(await h.read("claimablePayouts", [id]), 100n); + await h.send("D", "releaseMilestone", [id, 1], { revert: "Project not successful" }); + + const before = await h.balance(h.accounts.C.address); + const claim = await h.send("A", "claimPayout", [id, recipient]); + const paid = event(claim, "PayoutClaimed"); + assert.equal(paid.amount, 100n); + assert.equal(paid.recipient.toLowerCase(), recipient); + assert.equal(await h.balance(h.accounts.C.address), before + 100n); + assert.equal(await h.read("claimablePayouts", [id]), 0n); + assert.equal(await h.balance(), 0n); + await h.send("A", "claimPayout", [id, recipient], { revert: "No payout available" }); + }); + + test(`${profile.name}: a rejecting creator can redirect released funds after the next stage expires`, async () => { + const h = await localChain(artifacts); + const receiver = await h.deploy("A", artifacts.receiver, [h.fund.address.toString()]); + const receiverAddress = receiver.address.toString(); + await h.send("A", "create", [100n, h.now() + 100n], { target: receiver }); + const id = 0n; + await h.send("B", "contribute", [id], { value: 100n }); + await h.send("A", "evidence", [id], { target: receiver }); + await h.send("B", "approveMilestone", [id, 0]); + await h.send("A", "withdraw", [id], { target: receiver, revert: "ETH transfer failed" }); + + await h.send("D", "releaseMilestone", [id, 0]); + assert.equal(await h.balance(receiver.address), 0n); + assert.equal(await h.read("claimablePayouts", [id]), 40n); + await h.send("A", "claimPayoutTo", [id, receiverAddress], { + target: receiver, revert: "ETH transfer failed", + }); + assert.equal(await h.read("claimablePayouts", [id]), 40n); + + h.at(h.now() + await h.read("SUBMISSION_TIMEOUT")); + assert.equal(await h.read("getExpiredRefundAmount", [id, h.address("B")]), 60n); + const refund = await h.send("B", "claimExpiredRefund", [id]); + assert.equal(event(refund, "RefundClaimed").amount, 60n); + assert.equal((await h.read("getProject", [id])).status, 4n); + assert.equal((await h.read("getProject", [id])).escrowBalance, 0n); + assert.equal(await h.balance(), 40n); + + const before = await h.balance(h.accounts.C.address); + const claim = await h.send("A", "claimPayoutTo", [id, h.address("C")], { target: receiver }); + assert.equal(event(claim, "PayoutClaimed").amount, 40n); + assert.equal(await h.balance(h.accounts.C.address), before + 40n); + assert.equal(await h.read("claimablePayouts", [id]), 0n); + assert.equal(await h.balance(), 0n); + }); + + test(`${profile.name}: a direct payout leaves earlier credited funds available`, async () => { + const h = await localChain(artifacts); + const id = await h.create(); + await h.send("B", "contribute", [id], { value: 100n }); + await h.send("A", "submitEvidence", evidence(id, 0)); + await h.send("B", "approveMilestone", [id, 0]); + await h.send("D", "releaseMilestone", [id, 0]); + await h.send("A", "submitEvidence", evidence(id, 1)); + await h.send("B", "approveMilestone", [id, 1]); + await payout(h, id, 1, 60n); + assert.equal(await h.read("claimablePayouts", [id]), 40n); + assert.equal(await h.balance(), 40n); + await h.send("A", "claimPayout", [id, h.address("A")]); + assert.equal(await h.balance(), 0n); + }); + test(`${profile.name}: approval timeout refunds both backers in either claim order`, async () => { const h = await localChain(artifacts); const timeout = await h.read("APPROVAL_TIMEOUT");