Skip to content

Commit 378914c

Browse files
Amxxarr00
andauthored
Delegate override vote (#5192)
Co-authored-by: Arr00 <[email protected]>
1 parent 0034c30 commit 378914c

15 files changed

+924
-22
lines changed

.changeset/great-lions-hear.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openzeppelin-solidity': patch
3+
---
4+
5+
`VotesExtended`: Create an extension of `Votes` which checkpoints balances and delegates.

.changeset/pink-wasps-hammer.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openzeppelin-solidity': patch
3+
---
4+
5+
`GovernorCountingOverridable`: Add a governor counting module that enables token holders to override the vote of their delegate.

contracts/governance/Governor.sol

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,13 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
260260
bytes memory params
261261
) internal virtual returns (uint256);
262262

263+
/**
264+
* @dev Hook that should be called every time the tally for a proposal is updated.
265+
*
266+
* Note: This function must run successfully. Reverts will result in the bricking of governance
267+
*/
268+
function _tallyUpdated(uint256 proposalId) internal virtual {}
269+
263270
/**
264271
* @dev Default additional encoded parameters used by castVote methods that don't include them
265272
*
@@ -649,6 +656,8 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
649656
emit VoteCastWithParams(account, proposalId, support, votedWeight, reason, params);
650657
}
651658

659+
_tallyUpdated(proposalId);
660+
652661
return votedWeight;
653662
}
654663

@@ -732,7 +741,7 @@ abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor, IERC72
732741
*
733742
* If requirements are not met, reverts with a {GovernorUnexpectedProposalState} error.
734743
*/
735-
function _validateStateBitmap(uint256 proposalId, bytes32 allowedStates) private view returns (ProposalState) {
744+
function _validateStateBitmap(uint256 proposalId, bytes32 allowedStates) internal view returns (ProposalState) {
736745
ProposalState currentState = state(proposalId);
737746
if (_encodeStateBitmap(currentState) & allowedStates == bytes32(0)) {
738747
revert GovernorUnexpectedProposalState(proposalId, currentState, allowedStates);

contracts/governance/README.adoc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ Counting modules determine valid voting options.
3030

3131
* {GovernorCountingFractional}: A more modular voting system that allows a user to vote with only part of its voting power, and to split that weight arbitrarily between the 3 different options (Against, For and Abstain).
3232

33+
* {GovernorCountingOverridable}: An extended version of `GovernorCountingSimple` which allows delegatees to override their delegates while the vote is live.
34+
3335
Timelock extensions add a delay for governance decisions to be executed. The workflow is extended to require a `queue` step before execution. With these modules, proposals are executed by the external timelock contract, thus it is the timelock that has to hold the assets that are being governed.
3436

3537
* {GovernorTimelockAccess}: Connects with an instance of an {AccessManager}. This allows restrictions (and delays) enforced by the manager to be considered by the Governor and integrated into the AccessManager's "schedule + execute" workflow.
@@ -66,6 +68,8 @@ NOTE: Functions of the `Governor` contract do not include access control. If you
6668

6769
{{GovernorCountingFractional}}
6870

71+
{{GovernorCountingOverride}}
72+
6973
{{GovernorVotes}}
7074

7175
{{GovernorVotesQuorumFraction}}
@@ -88,6 +92,8 @@ NOTE: Functions of the `Governor` contract do not include access control. If you
8892

8993
{{Votes}}
9094

95+
{{VotesExtended}}
96+
9197
== Timelock
9298

9399
In a governance system, the {TimelockController} contract is in charge of introducing a delay between a proposal and its execution. It can be used with or without a {Governor}.
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
// SPDX-License-Identifier: MIT
2+
3+
pragma solidity ^0.8.20;
4+
5+
import {SignatureChecker} from "../../utils/cryptography/SignatureChecker.sol";
6+
import {SafeCast} from "../../utils/math/SafeCast.sol";
7+
import {VotesExtended} from "../utils/VotesExtended.sol";
8+
import {GovernorVotes} from "./GovernorVotes.sol";
9+
10+
/**
11+
* @dev Extension of {Governor} which enables delegatees to override the vote of their delegates. This module requires a
12+
* token token that inherits `VotesExtended`.
13+
*/
14+
abstract contract GovernorCountingOverridable is GovernorVotes {
15+
bytes32 public constant OVERRIDE_BALLOT_TYPEHASH =
16+
keccak256("OverrideBallot(uint256 proposalId,uint8 support,address voter,uint256 nonce,string reason)");
17+
18+
/**
19+
* @dev Supported vote types. Matches Governor Bravo ordering.
20+
*/
21+
enum VoteType {
22+
Against,
23+
For,
24+
Abstain
25+
}
26+
27+
struct VoteReceipt {
28+
uint8 casted; // 0 if vote was not casted. Otherwise: support + 1
29+
bool hasOverriden;
30+
uint208 overridenWeight;
31+
}
32+
33+
struct ProposalVote {
34+
uint256[3] votes;
35+
mapping(address voter => VoteReceipt) voteReceipt;
36+
}
37+
38+
event VoteReduced(address indexed voter, uint256 proposalId, uint8 support, uint256 weight);
39+
event OverrideVoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
40+
41+
error GovernorAlreadyOverridenVote(address account);
42+
43+
mapping(uint256 proposalId => ProposalVote) private _proposalVotes;
44+
45+
/**
46+
* @dev See {IGovernor-COUNTING_MODE}.
47+
*/
48+
// solhint-disable-next-line func-name-mixedcase
49+
function COUNTING_MODE() public pure virtual override returns (string memory) {
50+
return "support=bravo,override&quorum=for,abstain&overridable=true";
51+
}
52+
53+
/**
54+
* @dev See {IGovernor-hasVoted}.
55+
*/
56+
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
57+
return _proposalVotes[proposalId].voteReceipt[account].casted != 0;
58+
}
59+
60+
/**
61+
* @dev Check if an `account` has overridden their delegate for a proposal.
62+
*/
63+
function hasVotedOverride(uint256 proposalId, address account) public view virtual returns (bool) {
64+
return _proposalVotes[proposalId].voteReceipt[account].hasOverriden;
65+
}
66+
67+
/**
68+
* @dev Accessor to the internal vote counts.
69+
*/
70+
function proposalVotes(
71+
uint256 proposalId
72+
) public view virtual returns (uint256 againstVotes, uint256 forVotes, uint256 abstainVotes) {
73+
uint256[3] storage votes = _proposalVotes[proposalId].votes;
74+
return (votes[uint8(VoteType.Against)], votes[uint8(VoteType.For)], votes[uint8(VoteType.Abstain)]);
75+
}
76+
77+
/**
78+
* @dev See {Governor-_quorumReached}.
79+
*/
80+
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
81+
uint256[3] storage votes = _proposalVotes[proposalId].votes;
82+
return quorum(proposalSnapshot(proposalId)) <= votes[uint8(VoteType.For)] + votes[uint8(VoteType.Abstain)];
83+
}
84+
85+
/**
86+
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be strictly over the againstVotes.
87+
*/
88+
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
89+
uint256[3] storage votes = _proposalVotes[proposalId].votes;
90+
return votes[uint8(VoteType.For)] > votes[uint8(VoteType.Against)];
91+
}
92+
93+
/**
94+
* @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).
95+
*
96+
* NOTE: called by {Governor-_castVote} which emits the {IGovernor-VoteCast} (or {IGovernor-VoteCastWithParams})
97+
* event.
98+
*/
99+
function _countVote(
100+
uint256 proposalId,
101+
address account,
102+
uint8 support,
103+
uint256 totalWeight,
104+
bytes memory /*params*/
105+
) internal virtual override returns (uint256) {
106+
ProposalVote storage proposalVote = _proposalVotes[proposalId];
107+
108+
if (support > uint8(VoteType.Abstain)) {
109+
revert GovernorInvalidVoteType();
110+
}
111+
112+
if (proposalVote.voteReceipt[account].casted != 0) {
113+
revert GovernorAlreadyCastVote(account);
114+
}
115+
116+
totalWeight -= proposalVote.voteReceipt[account].overridenWeight;
117+
proposalVote.votes[support] += totalWeight;
118+
proposalVote.voteReceipt[account].casted = support + 1;
119+
120+
return totalWeight;
121+
}
122+
123+
/// @dev Variant of {Governor-_countVote} that deals with vote overrides.
124+
function _countOverride(uint256 proposalId, address account, uint8 support) internal virtual returns (uint256) {
125+
ProposalVote storage proposalVote = _proposalVotes[proposalId];
126+
127+
if (support > uint8(VoteType.Abstain)) {
128+
revert GovernorInvalidVoteType();
129+
}
130+
131+
if (proposalVote.voteReceipt[account].hasOverriden) {
132+
revert GovernorAlreadyOverridenVote(account);
133+
}
134+
135+
uint256 proposalSnapshot = proposalSnapshot(proposalId);
136+
uint256 overridenWeight = VotesExtended(address(token())).getPastBalanceOf(account, proposalSnapshot);
137+
address delegate = VotesExtended(address(token())).getPastDelegate(account, proposalSnapshot);
138+
uint8 delegateCasted = proposalVote.voteReceipt[delegate].casted;
139+
140+
proposalVote.voteReceipt[account].hasOverriden = true;
141+
proposalVote.votes[support] += overridenWeight;
142+
if (delegateCasted == 0) {
143+
proposalVote.voteReceipt[delegate].overridenWeight += SafeCast.toUint208(overridenWeight);
144+
} else {
145+
uint8 delegateSupport = delegateCasted - 1;
146+
proposalVote.votes[delegateSupport] -= overridenWeight;
147+
emit VoteReduced(delegate, proposalId, delegateSupport, overridenWeight);
148+
}
149+
150+
return overridenWeight;
151+
}
152+
153+
/// @dev variant of {Governor-_castVote} that deals with vote overrides.
154+
function _castOverride(
155+
uint256 proposalId,
156+
address account,
157+
uint8 support,
158+
string calldata reason
159+
) internal virtual returns (uint256) {
160+
_validateStateBitmap(proposalId, _encodeStateBitmap(ProposalState.Active));
161+
162+
uint256 overridenWeight = _countOverride(proposalId, account, support);
163+
164+
emit OverrideVoteCast(account, proposalId, support, overridenWeight, reason);
165+
166+
_tallyUpdated(proposalId);
167+
168+
return overridenWeight;
169+
}
170+
171+
/// @dev Public function for casting an override vote
172+
function castOverrideVote(
173+
uint256 proposalId,
174+
uint8 support,
175+
string calldata reason
176+
) public virtual returns (uint256) {
177+
address voter = _msgSender();
178+
return _castOverride(proposalId, voter, support, reason);
179+
}
180+
181+
/// @dev Public function for casting an override vote using a voter's signature
182+
function castOverrideVoteBySig(
183+
uint256 proposalId,
184+
uint8 support,
185+
address voter,
186+
string calldata reason,
187+
bytes calldata signature
188+
) public virtual returns (uint256) {
189+
bool valid = SignatureChecker.isValidSignatureNow(
190+
voter,
191+
_hashTypedDataV4(
192+
keccak256(
193+
abi.encode(
194+
OVERRIDE_BALLOT_TYPEHASH,
195+
proposalId,
196+
support,
197+
voter,
198+
_useNonce(voter),
199+
keccak256(bytes(reason))
200+
)
201+
)
202+
),
203+
signature
204+
);
205+
206+
if (!valid) {
207+
revert GovernorInvalidSignature(voter);
208+
}
209+
210+
return _castOverride(proposalId, voter, support, reason);
211+
}
212+
}

contracts/governance/extensions/GovernorPreventLateQuorum.sol

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,20 +44,12 @@ abstract contract GovernorPreventLateQuorum is Governor {
4444
}
4545

4646
/**
47-
* @dev Casts a vote and detects if it caused quorum to be reached, potentially extending the voting period. See
48-
* {Governor-_castVote}.
47+
* @dev Vote tally updated and detects if it caused quorum to be reached, potentially extending the voting period.
4948
*
5049
* May emit a {ProposalExtended} event.
5150
*/
52-
function _castVote(
53-
uint256 proposalId,
54-
address account,
55-
uint8 support,
56-
string memory reason,
57-
bytes memory params
58-
) internal virtual override returns (uint256) {
59-
uint256 result = super._castVote(proposalId, account, support, reason, params);
60-
51+
function _tallyUpdated(uint256 proposalId) internal virtual override {
52+
super._tallyUpdated(proposalId);
6153
if (_extendedDeadlines[proposalId] == 0 && _quorumReached(proposalId)) {
6254
uint48 extendedDeadline = clock() + lateQuorumVoteExtension();
6355

@@ -67,8 +59,6 @@ abstract contract GovernorPreventLateQuorum is Governor {
6759

6860
_extendedDeadlines[proposalId] = extendedDeadline;
6961
}
70-
71-
return result;
7262
}
7363

7464
/**
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// SPDX-License-Identifier: MIT
2+
pragma solidity ^0.8.20;
3+
4+
import {Checkpoints} from "../../utils/structs/Checkpoints.sol";
5+
import {Votes} from "./Votes.sol";
6+
import {SafeCast} from "../../utils/math/SafeCast.sol";
7+
8+
/**
9+
* @dev Extension of {Votes} that adds exposes checkpoints for delegations and balances.
10+
*/
11+
abstract contract VotesExtended is Votes {
12+
using SafeCast for uint256;
13+
using Checkpoints for Checkpoints.Trace160;
14+
using Checkpoints for Checkpoints.Trace208;
15+
16+
mapping(address delegatee => Checkpoints.Trace160) private _delegateCheckpoints;
17+
mapping(address account => Checkpoints.Trace208) private _balanceOfCheckpoints;
18+
19+
/**
20+
* @dev Returns the delegate of an `account` at a specific moment in the past. If the `clock()` is
21+
* configured to use block numbers, this will return the value at the end of the corresponding block.
22+
*
23+
* Requirements:
24+
*
25+
* - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.
26+
*/
27+
function getPastDelegate(address account, uint256 timepoint) public view virtual returns (address) {
28+
uint48 currentTimepoint = clock();
29+
if (timepoint >= currentTimepoint) {
30+
revert ERC5805FutureLookup(timepoint, currentTimepoint);
31+
}
32+
return address(_delegateCheckpoints[account].upperLookupRecent(timepoint.toUint48()));
33+
}
34+
35+
/**
36+
* @dev Returns the `balanceOf` of an `account` at a specific moment in the past. If the `clock()` is
37+
* configured to use block numbers, this will return the value at the end of the corresponding block.
38+
*
39+
* Requirements:
40+
*
41+
* - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.
42+
*/
43+
function getPastBalanceOf(address account, uint256 timepoint) public view virtual returns (uint256) {
44+
uint48 currentTimepoint = clock();
45+
if (timepoint >= currentTimepoint) {
46+
revert ERC5805FutureLookup(timepoint, currentTimepoint);
47+
}
48+
return _balanceOfCheckpoints[account].upperLookupRecent(timepoint.toUint48());
49+
}
50+
51+
/// @inheritdoc Votes
52+
function _delegate(address account, address delegatee) internal virtual override {
53+
super._delegate(account, delegatee);
54+
55+
_delegateCheckpoints[account].push(clock(), uint160(delegatee));
56+
}
57+
58+
/// @inheritdoc Votes
59+
function _transferVotingUnits(address from, address to, uint256 amount) internal virtual override {
60+
super._transferVotingUnits(from, to, amount);
61+
if (from != to) {
62+
if (from != address(0)) {
63+
_balanceOfCheckpoints[from].push(clock(), _getVotingUnits(from).toUint208());
64+
}
65+
if (to != address(0)) {
66+
_balanceOfCheckpoints[to].push(clock(), _getVotingUnits(to).toUint208());
67+
}
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)