solidity-投票

pragma solidity ^0.4.22;
/*对已经有的方案进行投票,如果超过了投票时间那么投票无效*/
contract Ballot {
    uint256 public voteEnd; //投票截止时间,自1970-1-1以来的秒数
	struct Voter {
		uint weight;  //给予的票。0:没票,1:一票
		bool voted;  //true代表已经给过票了
	}
    struct Proposal {		// 代表一份方案的数据结构
        uint voteCount; // 方案接受的投票数
        string ballotName;  //
    }
	mapping(address => Voter) public voters;	//这个状态变量存储了所有潜在投票人
	Proposal public proposals;
	function Ballot(string ballotName,uint voteTime) public {  //初始化方案。填入方案的名称和投票的结束时间(以小时为单位)
	       // uint256 public voteEnd; //投票截止时间,自1970-1-1以来的秒数
	        //require(keccak256(ballotName)==keccak256("多重签名"),"方案名错误");  //字符串比较需要先转化成hash
	        voteEnd = now + voteTime*3600;
            Proposal({
                ballotName:ballotName,
                voteCount:0});
    }
	function giveRightToVote() public returns(string msg_){    //先判断是否给过票了,如果没有给过则给一张票
	    if(msg.sender == 0x14723a09acff6d2a60dcdf7aa4aff308fddc160c || msg.sender == 0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db ||msg.sender == 0x583031d1113ad414f02576bd6afabfb302140225){
			if(voters[msg.sender].voted==false){		//false没有给过票,然后我就需要给他一张票
				voters[msg.sender].voted = true; 
				 voters[msg.sender].weight = 1;
				 msg_ = "给票成功";
				}else{
	        msg_ = "已给过票";
				}
    		}else{
			msg_ = "当前账号不具有投票权利";
	    }
	    
	}
	
	function vote(uint voteResult) public returns(string msg_){  //投票意见:1表示同意,2表示不同意
	require(now < voteEnd,"已过投票截止时间");
	if(voters[msg.sender].weight==1){		//手上有票才有资格投票
	    if(voteResult==1){
	        proposals.voteCount+= voters[msg.sender].weight;
	        voters[msg.sender].weight=0;
	        msg_ = "同意该方案";
		}else{
	        voters[msg.sender].weight=0;
	        msg_ ="不同意该方案";
	        }
	    }else{
	        msg_ = "请勿多次投票";
	    }
	}
	//判断投票是否通过,如果没有投票就相当于同意该方案
	function result() public returns(string msg_){
	    require(now >= voteEnd,"投票尚未结束");		//投票时间没有结束前不统计投票结果
	    if(voters[0x14723a09acff6d2a60dcdf7aa4aff308fddc160c].voted==false){ 
	        proposals.voteCount+=1;
	    }
	    if(voters[0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db].voted==false){
	        proposals.voteCount+=1;
	    }
	    if(voters[0x583031d1113ad414f02576bd6afabfb302140225].voted==false){
	        proposals.voteCount+=1;
	    }
	   // if(proposals.voteCount==3){
	    if(proposals.voteCount>1){
	        msg_ = "方案通过";
	    }else{
	        msg_ = "方案不通过";
	    }
        
    }

}

你可能感兴趣的:(solidity-投票)