-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpoll.sol
85 lines (69 loc) · 2.69 KB
/
poll.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/// Memberitahu Complier bahwa kita mamakai bahasa pemograman solidity 0.6.6
pragma solidity ^0.6.6;
contract PollContract{
// Buat struct Poll yang berisi variable yang sudah kita buat di front end
struct Poll{
uint256 id;
string question;
string thumbnail;
uint64[] votes;
bytes32[] options;
}
struct Voter {
address id;
uint256[] votedIds;
mapping(uint256 => bool) votedMap;
}
Poll[] private polls;
mapping(address => Voter) private voters;
// Menbuat event createPoll
event PollCreated(uint256 _pollId);
// Fungsi untuk membuat poll
function createPoll(string memory _question, string memory _thumb, bytes32[] memory _options) public {
// Check apakah request dari front end kosong apa tidak
require(bytes(_question).length > 0, "Empty question");
require(_options.length > 1, "At least 2 options required");
uint256 pollId = polls.length;
Poll memory newPoll = Poll({
id: pollId,
question: _question,
thumbnail: _thumb,
options: _options,
votes: new uint64[](_options.length)
});
polls.push(newPoll);
emit PollCreated(pollId);
}
// Membuat fungsi untuk mengambil poll
function getPoll(uint256 _pollId) external view returns(uint256, string memory, string memory, uint64[] memory, bytes32[] memory){
// Buat validasi ketika pollId nya lebih dari pollId.length dan pollIdnya tidak boleh bernilai negatif / <0
require(_pollId < polls.length && _pollId >= 0, "No poll found");
return(
polls[_pollId].id,
polls[_pollId].question,
polls[_pollId].thumbnail,
polls[_pollId].votes,
polls[_pollId].options
);
}
// Membuat fungsi Vote
function vote (uint256 _pollId, uint64 _vote) external {
// Check kondisi Poll
require(_pollId < polls.length, "Poll does not exist");
require(_vote < polls[_pollId].options.length, "Invalid vote");
require(voters[msg.sender].votedMap[_pollId] == false, "You Already voted");
polls[_pollId].votes[_vote] += 1;
voters[msg.sender].votedIds.push(_pollId);
voters[msg.sender].votedMap[_pollId] = true;
}
// Membuat fungsi untuk mengambil
function getVoter(address _id) external view returns(address, uint256[] memory){
return(
voters[_id].id,
voters[_id].votedIds
);
}
function getTotalPolls() external view returns(uint256){
return polls.length;
}
}