forked from DeFiHackLabs/Web3-CTF-Intensive-CoLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VotingMachine.sol
86 lines (69 loc) · 2.84 KB
/
VotingMachine.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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract VoteToken is ERC20("Vote Token", "vToken") {
address public owner;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
constructor() {
owner = msg.sender;
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(address _from, uint256 _amount) public onlyOwner {
_burn(_from, _amount);
_moveDelegates(_delegates[_from], address(0), _amount);
}
mapping(address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
function _moveDelegates(address from, address to, uint256 amount) internal {
if (from != to && amount > 0) {
if (from != address(0)) {
uint32 fromNum = numCheckpoints[from];
uint256 fromOld = fromNum > 0 ? checkpoints[from][fromNum - 1].votes : 0;
uint256 fromNew = fromOld - amount;
_writeCheckpoint(from, fromNum, fromOld, fromNew);
}
if (to != address(0)) {
uint32 toNum = numCheckpoints[to];
uint256 toOld = toNum > 0 ? checkpoints[to][toNum - 1].votes : 0;
uint256 toNew = toOld + amount;
_writeCheckpoint(to, toNum, toOld, toNew);
}
}
}
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
mapping(address => uint32) public numCheckpoints;
function delegates(address _addr) external view returns (address) {
return _delegates[_addr];
}
function delegate(address _addr) external {
return _delegate(msg.sender, _addr);
}
function getVotes(address _addr) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[_addr];
return nCheckpoints > 0 ? checkpoints[_addr][nCheckpoints - 1].votes : 0;
}
function _delegate(address _addr, address delegatee) internal {
address currentDelegate = _delegates[_addr];
uint256 _addrBalance = balanceOf(_addr);
_delegates[_addr] = delegatee;
_moveDelegates(currentDelegate, delegatee, _addrBalance);
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = uint32(block.number);
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
}
}