Last active
October 19, 2024 19:29
-
-
Save molecula451/3413ae44d998bace4261e2589c35a1ba to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.26+commit.8a97fa7a.js&optimize=false&runs=200&gist=
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
contract Voting { | |
enum VoteOption { Yes, No, None } | |
struct Voter { | |
bool hasVoted; | |
VoteOption vote; | |
uint256 votedAtBlock; | |
} | |
uint256 public requiredVotingPower; | |
uint256 public snapshotBlock; | |
uint256 public yesVotes; | |
uint256 public noVotes; | |
mapping(address => Voter) public voters; | |
event Voted(address indexed voter, VoteOption vote, uint256 blockNumber); | |
constructor(uint256 _requiredVotingPower, uint256 _snapshotBlock) { | |
requiredVotingPower = _requiredVotingPower; | |
snapshotBlock = _snapshotBlock; | |
} | |
// Vote function | |
function vote(VoteOption _vote) external { | |
require(block.number >= snapshotBlock, "Voting has not started yet."); | |
require(!voters[msg.sender].hasVoted, "You have already voted."); | |
require(_vote == VoteOption.Yes || _vote == VoteOption.No, "Invalid vote option."); | |
require(address(msg.sender).balance >= requiredVotingPower, "Insufficient balance to vote."); | |
uint256 votingPower = address(msg.sender).balance; | |
voters[msg.sender] = Voter({ | |
hasVoted: true, | |
vote: _vote, | |
votedAtBlock: block.number | |
}); | |
if (_vote == VoteOption.Yes) { | |
yesVotes += votingPower; | |
} else if (_vote == VoteOption.No) { | |
noVotes += votingPower; | |
} | |
emit Voted(msg.sender, _vote, block.number); | |
} | |
// Check if a voter has voted at a specific block | |
function checkVotedAtBlock(address _voter, uint256 _blockNumber) external view returns (bool) { | |
Voter memory voter = voters[_voter]; | |
return voter.hasVoted && voter.votedAtBlock == _blockNumber; | |
} | |
// Get the vote of a particular address | |
function getVote(address _voter) external view returns (VoteOption) { | |
require(voters[_voter].hasVoted, "This address has not voted yet."); | |
return voters[_voter].vote; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment