投票 Ballet Domo智能合约修改如下:
根据例子学习Solidity — Solidity develop 文档
https://solidity-cn.readthedocs.io/zh/develop/solidity-by-example.html原文在上述资料中,重要的问题是,命名搞的非常糟糕,用近似的词命名各种变量,看起来很费劲。
pragma solidity ^0.5.17;
//vote contract
contract Ballot {
//define voter struct
struct VoterStruct {
uint weight ;
bool voted;
address delegateAddr;
uint voteNum;
}
//define proposals struct
struct ProposalStruct {
bytes32 proposalName;
uint voteCount;
}
address public chairPersion;
mapping(address => VoterStruct) voters;
ProposalStruct[] public proposals;
//constructor function
constructor(bytes32[] memory _proposalNames ) public {
chairPersion = msg.sender;
voters[chairPersion].weight = 1;
for (uint i= 0; i < _proposalNames.length;i++){
//add element
proposals.push(
ProposalStruct({proposalName:_proposalNames[i],voteCount:0})
);
}
}
//give vote right
function giveRightToVote(address _voter) public {
require(msg.sender == chairPersion,"only chairpersion can give right to vote.");
require(!voters[_voter].voted,"The voter always voted!");
require(voters[_voter].weight == 0);
voters[_voter].weight = 1;
}
//delegate to someone
function delegate(address _to) public {
VoterStruct storage voterSenderTmp = voters[msg.sender];
require(!voterSenderTmp.voted,"you always voted");
require( _to != msg.sender,"SelfVoted is not allwed");
while (voters[_to].delegateAddr != address(0)){
_to = voters[_to].delegateAddr;
require(_to != msg.sender ,"Found loop in delegation");
}
voterSenderTmp.voted = true;
voterSenderTmp.delegateAddr = _to;
VoterStruct storage voterDelegateTmp = voters[_to];
if (voterDelegateTmp.voted){
proposals[voterDelegateTmp.voteNum].voteCount += voterSenderTmp.weight;
}else{
//???
voterDelegateTmp.weight = voterSenderTmp.weight;
voters[_to].weight = voterSenderTmp.weight;
}
}
function voteDo(uint _proposalNum) public{
// VoterStruct storage voterSenderTmp = voters[msg.sender];
// require(!voterSenderTmp.voted,"Aleady voted!");
require(!voters[msg.sender].voted,"Aleady voted!");
voters[msg.sender].voted = true;
voters[msg.sender].voteNum = _proposalNum;
proposals[_proposalNum].voteCount+= voters[msg.sender].weight;
}
function winningProposal() public view returns (uint num_,bytes32 name_){
uint countTmp = 0;
for(uint p = 0; p < proposals.length; p++){
if (proposals[p].voteCount > countTmp){
countTmp = proposals[p].voteCount;
num_ = p;
}
}
name_ = proposals[num_].proposalName;
return (num_,name_);
}
}
本文介绍了使用Solidity编程语言构建的一个智能合约——BalletDomo,该合约用于实现投票功能。合约定义了VoterStruct和ProposalStruct结构体,分别表示选民和提案。合约包含构造函数、赋予投票权、委托投票和投票操作。通过智能合约,可以确保选举过程的透明性和安全性。

被折叠的 条评论
为什么被折叠?



