用solidity写一个简单的投票合约
时间: 2023-10-15 15:02:34 浏览: 198
可以的,以下是一个基于Solidity的简单投票合约,便于您参考:
```
pragma solidity ^0.8.0;
contract Voting {
uint public totalVotes;
mapping (bytes32 => uint) public votesReceived;
bytes32[] public candidateList;
constructor(bytes32[] memory candidateNames) {
candidateList = candidateNames;
}
function voteForCandidate(bytes32 candidate) public {
require(validCandidate(candidate));
votesReceived[candidate] += 1;
totalVotes += 1;
}
function totalVotesFor(bytes32 candidate) public view returns (uint) {
require(validCandidate(candidate));
return votesReceived[candidate];
}
function validCandidate(bytes32 candidate) public view returns (bool) {
for(uint i = 0; i < candidateList.length; i++) {
if(candidateList[i] == candidate) {
return true;
}
}
return false;
}
}
```
上述合约允许您为候选人投票,并记录每个候选人所获得的投票数。候选人列表在合约构造函数中被初始化,您可以通过调用总投票数和每个候选人的总票数来查询当前的选举情况。请注意,此合约仅供参考,您可以根据实际需求进行修改。