-
Notifications
You must be signed in to change notification settings - Fork 0
/
VotingContract.sol
69 lines (53 loc) · 1.63 KB
/
VotingContract.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract Voting {
struct Vote {
bool choice;
bool voted;
}
struct Topic {
string name;
string description;
bool open;
mapping(address => Vote) votes;
uint256 yesCount;
uint256 noCount;
}
address public admin;
ERC20 public token;
mapping(uint256 => Topic) public topics;
uint256 public nextTopicId;
constructor(address _token) {
admin = msg.sender;
token = ERC20(_token);
}
function createTopic(string memory name, string memory description) external {
require(msg.sender == admin, "only admin");
Topic storage topic = topics[nextTopicId++];
topic.name = name;
topic.description = description;
topic.open = true;
}
function vote(uint256 topicId, bool choice) external {
Topic storage topic = topics[topicId];
require(msg.sender != admin, "admin cannot vote");
require(topic.open, "voting not open");
Vote storage v = topic.votes[msg.sender];
require(!v.voted, "already voted");
v.choice = choice;
v.voted = true;
if (choice) {
topic.yesCount++;
} else {
topic.noCount++;
}
}
function closeVoting(uint256 topicId) external {
require(msg.sender == admin, "only admin");
Topic storage topic = topics[topicId];
require(topic.open, "voting already closed");
topic.open = false;
// Rewarding logic goes here.
}
}