Solidity

如何在選舉智能合約中投票更多次?

  • April 14, 2018

我有一個用於選舉的簡單複制智能合約,其中選民只為一名候選人投票一次,然後被拒絕投票更多次。

但是是否有可能允許選民最多投票 3 次並每次**將選票發送給不同的候選人?**這意味著當您向一位候選人發送超過一票時,您將被拒絕。怎麼做?

編碼

contract Election {

struct Candidate {
   string name;
   uint voteCount;
}
struct Voter {
   uint voteIndex;
   bool voted;
   uint weight;
}

address public owner;
string public name;
mapping(address => Voter) public voters;
Candidate[] public candidates;
uint public auctionEnd;

event ElectionResult(string name, uint voteCount);

function Election(string _name, uint durationMinutes, string candidate1, string candidate2, string candidate3, string candidate4, string candidate5) public{
   owner = msg.sender;
   name = _name; 
   auctionEnd = now + (durationMinutes * 1 minutes);

   candidates.push(Candidate(candidate1, 0));
   candidates.push(Candidate(candidate2, 0));
   candidates.push(Candidate(candidate3, 0));
   candidates.push(Candidate(candidate4, 0));
   candidates.push(Candidate(candidate5, 0));
}

function authorize(address voter) public {
   require(msg.sender == owner);
   require(!voters[voter].voted);

   voters[voter].weight = 1;

}

function vote(uint voteIndex) public {
   require(now < auctionEnd);
   require(!voters[msg.sender].voted);

   voters[msg.sender].voted = true;
   voters[msg.sender].voteIndex = voteIndex;

   candidates[voteIndex].voteCount += voters[msg.sender].weight;
}

function end() public {
   require(msg.sender == owner);
   require(now >= auctionEnd);

   for(uint i=0; i < candidates.length; i++) {
       ElectionResult(candidates[i].name, candidates[i].voteCount);
   }
}
}

我同意@Nulik 的觀點,這更普遍地與程式有關。你想改變規則。基本上,您不想檢查選民是否投票過,而是想更改他們投票的次數。

struct Voter {
   uint voteIndex;
   bool voted;  // <= ever voted
   uint weight;
}

對此:

struct Voter {
   uint voteIndex;
   uint voted; // <== count of votes cast
   uint weight;
}

require(!voters[voter].voted);

對此

require(voters[voter].voted < 3);

voters[msg.sender].voted = true;

對此

voters[msg.sender].voted += 1;

這絕不是經過徹底測試,也沒有保修。這可能只是出於教育目的的開始。

希望能幫助到你。

引用自:https://ethereum.stackexchange.com/questions/45672