pragma solidity ^0.8.0;contract Voting {struct Poll {string question;string[] options;uint[] votes; uint totalVotes;bool active;}mapping(uint => Poll) public polls;uint public pollCount;event PollCreated(uint pollId, string question, string[] options);event Voted(uint pollId, uint optionId, address voter);function createPoll(string memory question, string[] memory options) public {require(options.length > 0, "At least one option is required.");Poll storage newPoll = polls[pollCount];newPoll.question = question;newPoll.options = options;newPoll.votes = new uint[](options.length); newPoll.active = true;newPoll.totalVotes = 0;emit PollCreated(pollCount, question, options);pollCount++;}function vote(uint pollId, uint optionId) public {require(pollId < pollCount, "Poll does not exist.");require(optionId < polls[pollId].options.length, "Invalid option.");require(polls[pollId].active, "Poll is not active.");polls[pollId].votes[optionId]++;polls[pollId].totalVotes++;emit Voted(pollId, optionId, msg.sender);}function endPoll(uint pollId) public {require(pollId < pollCount, "Poll does not exist.");polls[pollId].active = false;}function getResults(uint pollId) public view returns (uint[] memory) {require(pollId < pollCount, "Poll does not exist.");return polls[pollId].votes; }function getPollQuestion(uint pollId) public view returns (string memory) {require(pollId < pollCount, "Poll does not exist.");return polls[pollId].question;}function getPollOptions(uint pollId) public view returns (string[] memory) {require(pollId < pollCount, "Poll does not exist.");return polls[pollId].options;}
}
- 数据结构
Poll: 存储每个投票的相关信息。
question: 投票问题。
options: 投票选项数组。
votes: 对应每个选项的投票数。
totalVotes: 投票总数。
active: 投票是否处于激活状态。 - 状态变量
polls: 一个映射(mapping),将投票 ID 映射到 Poll 结构。
pollCount: 记录当前投票的总数。 - 事件
PollCreated: 当创建投票时触发,记录投票 ID、问题和选项。
Voted: 当有人投票时触发,记录投票 ID、选项 ID 和投票者地址。 - 功能函数
createPoll:
创建新的投票。
检查选项数量是否有效。
初始化新的 Poll,并记录在 polls 中。
触发 PollCreated 事件。
vote:
用户对某个投票进行投票。
检查投票 ID 和选项 ID 的有效性。
增加对应选项的投票数和总投票数。
触发 Voted 事件。
endPoll:
结束某个投票。
设置对应投票的 active 状态为 false。
getResults:
返回指定投票的投票结果(即每个选项的投票数)。
getPollQuestion:
返回指定投票的问题。
getPollOptions:
返回指定投票的所有选项。