-
Notifications
You must be signed in to change notification settings - Fork 0
/
ElectionManager.sol
87 lines (71 loc) · 2.59 KB
/
ElectionManager.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
86
87
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.2;
contract ElectionManager {
address public owner;
string public electionName;
bool public electionConcluded;
uint256 public votingDeadline;
// List of owners
address[] public owners;
// Event for adding a new owner
event OwnerAdded(address newOwner);
// Event for removing an existing owner
event OwnerRemoved(address ownerRemoved);
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can call this function.");
_;
}
modifier electionInProgress() {
require(!electionConcluded, "The election has already concluded.");
require(block.timestamp <= votingDeadline, "Voting has ended.");
_;
}
// Constructor, contract creator becomes first owner
constructor() {
owner = msg.sender;
owners.push(owner);
}
// Define election name
function setElectionName(string memory _name) public onlyOwner {
electionName = _name;
}
// End election
function endElection() public onlyOwner electionInProgress {
electionConcluded = true;
}
// Get election status
function getElectionStatus() public view returns (string memory, bool, uint256) {
return (electionName, electionConcluded, votingDeadline);
}
// Verify if address is owner
function isOwner(address account) public view returns (bool) {
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] == account) {
return true;
}
}
return false;
}
// Add a new owner (only can be called by an existing owner)
function addOwner(address newOwner) public onlyOwner {
require(!isOwner(newOwner), "Address is already an owner.");
owners.push(newOwner);
emit OwnerAdded(newOwner);
}
// Remove an owner (only can be called by an existing owner)
function removeOwner(address ownerToRemove) public onlyOwner {
require(owners.length > 1, "There must be at least one owner.");
require(ownerToRemove != owner, "You cannot remove yourself if there is only one owner.");
uint256 indexToRemove;
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] == ownerToRemove) {
indexToRemove = i;
break;
}
}
require(indexToRemove != 0 || owners.length == 1, "You cannot remove the original owner.");
owners[indexToRemove] = owners[owners.length - 1];
owners.pop();
emit OwnerRemoved(ownerToRemove);
}
}