[區塊鏈-以太坊] 募資平台建立-Part 5. 確認資金花費項目

Chiwen Lai
6 min readJun 8, 2018

--

上一篇Part 4. 核准資金花費項目之後,接下來我們要讓提案人做確認並撥款給廠商。

  1. 由首頁的合約位址點入,帶到該募資計畫的詳細頁面。
  2. 從募資計畫的詳細頁面點選「查看花費項目」。
  3. 在花費項目頁面列出所有的花費項目,包含投票中,以及提案人已確認的花費。
  4. 針對投票中的花費項目,核准人數超過贊助人數二分之一,即可由提案人確認,將以太幣發送給廠商。已確認的花費項目則不再需要核准及提案人確認的按鈕了。

STEP 1: Backend

▼開啟/contracts/Campaign.sol,加上確認花費項目的Function。

function finalizeRequest(uint index) public ownerOnly {
// 1 - 宣告
Request storage request = requests[index];
// 2 - 檢查
require(request.approvalCount > (contributorsCount / 2));
require(!request.complete);
// 3 - 提案人確認後撥款
request.recipient.transfer(request.value);
request.complete = true;
}

// 1 — 宣告request為Request型態的變數,index由前端帶入,也就是當提案人在頁面確認的時候就指定是哪一筆花費項目。
// 2 — 檢查1是否核准人數已超過贊助者的二分之一(過半數通過才可撥款)ㄤ; 2該筆花費項目是否已確認過,已確認過的花費項目不需要再重複撥款。
// 3 — 確認花費項目,將該筆花費項目設定的金額傳送給廠商,也就是接收方位址。

STEP 2: 重新部署

▼合約寫好後需重新部署。

$ node compile.js
$ node deploy.js
Contract deployed to 0xdED7a62EC0F02613DE2A9AA4D963f2690EFb118d

▼將新的合約位址更新到factory.js,如下。

import web3 from "./web3";
import CampaignFactory from "./build/CampaignFactory.json";
const instance = new web3.eth.Contract(
JSON.parse(CampaignFactory.interface),
"0xdED7a62EC0F02613DE2A9AA4D963f2690EFb118d"
);
export default instance;

STEP 3: Frontend

▼在components/RequestRow.js,新增提案人確認的功能。

import React, { Component } from "react";
import { Table, Button } from "semantic-ui-react";
import web3 from "../ethereum/web3";
import Campaign from "../ethereum/campaign";
class RequestRow extends Component {
// 確認
onFinalize = async () => {
const campaign = Campaign(this.props.address);
const accounts = await web3.eth.getAccounts();
await campaign.methods.finalizeRequest(this.props.id).send({
from: accounts[0]
});
};
// 核准
onApprove = async () => {
const campaign = Campaign(this.props.address);
const accounts = await web3.eth.getAccounts();
await campaign.methods.approveRequest(this.props.id).send({
from: accounts[0]
});
};
render() {
const { Row, Cell } = Table;
const { id, request, contributorsCount } = this.props;
const readyToFinalize = request.approvalCount > contributorsCount / 2;
return (
<Row
disabled={request.complete}
positive={readyToFinalize && !request.complete}
>
<Cell>{id}</Cell>
<Cell>{request.description}</Cell>
<Cell>{web3.utils.fromWei(request.value, "ether")}</Cell>
<Cell>{request.recipient}</Cell>
<Cell>
{request.approvalCount}/{contributorsCount}
</Cell>
<Cell>
{request.complete ? null : (
<Button color="green" basic onClick={this.onApprove}>
Approve
</Button>
)}
</Cell>
// 增加提案人確認按鈕
<Cell>
{request.complete ? null : (
<Button color="teal" basic onClick={this.onFinalize}>
提案人確認
</Button>
)}
</Cell>

</Row>
);
}
}
export default RequestRow;

▼接下來直接在終端機crowdfunding目錄下面輸入

$ npm run dev

即可在瀏覽器http://localhost:3000觀看到更新後的畫面。

--

--