iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
Modern Web

區塊鏈&DAPP介紹系列 第 25

[區塊鏈&DAPP介紹 Day25] Dapp 實戰 投票系統 - 1

  • 分享至 

  • twitterImage
  •  

今天我們藉著昨天的 第一個 Dapp 來稍微修改一下,改成一個投票系統。

首先我們先來嘗試撰寫這個投票系統的合約,我們先在原本的 contract 資料夾裡面,新增一個 Voting.sol的檔案

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;

contract Voting {

    //候選提案列表
    bytes32[] public candidateList;
    
     //紀錄名稱與投票的數字
    mapping (bytes32 => uint8) public votesReceived;

    //建構子
    constructor( bytes32[] memory candidateNames) public {
        candidateList = candidateNames;
    }
    //檢查投票選項有效性
    function validCandiate(bytes32 candidate) view public returns (bool) {
        for(uint i = 0; i < candidateList.length; i++) {
            if (candidateList[i] == candidate) {
                return true;
            }
        }
        return false;
    }

    //增加票數
    function addVote(bytes32 candidate) public {
        //需要確認選項在不在
        require(validCandidate(candidate));
        votesReceived[candidate] += 1;
    }
    //查詢某選項的票數
    function queryVotes(bytes32 candidate) view public returns (uint8) {
        //需要先確認選項在不在
        require(validCandidate(candidate));
        return votesReceived[candidate];
    }

}

再來部署之前,需要在合約做一個初始化的動作,把選項填入,進入到 migrations 資料夾,打開 2_deploy_contracts.js 修改裡面的檔案為

var Voting = artifacts.require("./Voting.sol");
module.exports = function(deployer) {
  deployer.deploy(Voting, [web3.utils.utf8ToHex('去烤肉'),
    web3.utils.utf8ToHex('去逛街'),web3.utils.utf8ToHex('去游泳')]);
};

我們把選項初始化進去合約裡面,分別依序為 去烤肉去逛街去游泳

再來就能執行我們的編譯以及部屬的工作了。

$ truffle complie
$ truffle migrate

明天我們來談談 js & html 的部分怎麼做修改。


上一篇
[區塊鏈&DAPP介紹 Day24] Dapp 實戰 部署第一個 Dapp
下一篇
[區塊鏈&DAPP介紹 Day26] Dapp 實戰 投票系統 - 2
系列文
區塊鏈&DAPP介紹30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言