基于以太坊的分布式投票系统solidity合约代码
生活随笔
收集整理的這篇文章主要介紹了
基于以太坊的分布式投票系统solidity合约代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
pragma solidity ^ 0.4.26;contract Ballot {string public name; //投票的名稱,name of the Ballotaddress public chairman; //合約擁有者的地址bool public closed; // 記錄投票是否結束// 獲勝票數比例uint public proportion; // 獲勝時得票數占總票數的最低比例, 例如50%就賦值為50uint public totalVotes; // 總票數// 加投票權集合, 表示哪些人有投票權address[] voters;struct Proposal { // 候選人信息的結構體bytes32 name;uint voteCount; // 候選人的得票數}Proposal[] public proposals; // 候選人的結構體(可變長)數組mapping(address => bool) voteRecords; // 投票者是否投票(默認false)uint[] winningProposals = [0];bytes32[] winningProposalsName; // 記錄winning候選人名字的數組constructor(string _name, bytes32[] _proposals, uint _proportion, address[] _voters) public { // 合約的構造函數chairman = msg.sender; // 記錄合約的擁有者closed = false; // 合約默認處于打開name = _name; // 投票的名稱,如 "選舉學生會主席"for(uint i = 0; i < _proposals.length; i++) {proposals.push(Proposal({name: _proposals[i],voteCount: 0}));}proportion = _proportion;voters = _voters;totalVotes = voters.length;}function setChairman(address _chairman) external { // 更換合約擁有者時用chairman = _chairman;}function vote(uint proposal) public { //給候選人投票, 需傳入候選人的序號及投票者的地址address voterAddress = msg.sender;require(!closed, "the ballot is already closed."); // 保證合約沒有關閉,即投票沒有結束// 看投票者的地址是否在合法名單中bool legal = false;for(uint i = 0; i < voters.length; i++){if(voters[i] == voterAddress){legal = true;break;}}require(legal, "the voter is illeagal!");require(proposal < proposals.length, "the prosal is invalid!");require(!voteRecords[voterAddress], "Already voted."); // 保證投票者沒有投過票voteRecords[voterAddress] = true;proposals[proposal].voteCount += 1; // 候選人得票數加一}function closeBallot() public { // 關閉投票require(chairman == msg.sender, "only the chairman can close the ballot."); // 只有擁有者可以關閉投票closed = true;}function getWinningProposals() internal { //統計投票的獲勝者winningProposals.length = 0;uint winningVoteCount = 0;for(uint i = 0; i < proposals.length; i++) {if(proposals[i].voteCount * 100 / totalVotes >= proportion) {winningProposals.push(i);}}if(winningProposals.length == 0){for(i = 0; i < proposals.length; i++){if(proposals[i].voteCount > winningVoteCount){winningVoteCount = proposals[i].voteCount;}}for(i = 0; i < proposals.length; i++){if(proposals[i].voteCount == winningVoteCount){winningProposals.push(i);}}}}function winnerName() public view returns (bytes32[]) { // 返回得票數最高的候選人的名字require(closed, "only when the ballot is closed can you examine the winner");getWinningProposals();for(uint i = 0; i < winningProposals.length; i++){winningProposalsName.push(proposals[winningProposals[i]].name);}return winningProposalsName;}function getProposalNumber() public view returns (uint){return proposals.length;}}
總結
以上是生活随笔為你收集整理的基于以太坊的分布式投票系统solidity合约代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人工智能-基于U^2-Net的肖像画生成
- 下一篇: Linux GCC用法