Votes.sol 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.2.0) (governance/utils/Votes.sol)
  3. pragma solidity ^0.8.20;
  4. import {IERC5805} from "../../interfaces/IERC5805.sol";
  5. import {Context} from "../../utils/Context.sol";
  6. import {Nonces} from "../../utils/Nonces.sol";
  7. import {EIP712} from "../../utils/cryptography/EIP712.sol";
  8. import {Checkpoints} from "../../utils/structs/Checkpoints.sol";
  9. import {SafeCast} from "../../utils/math/SafeCast.sol";
  10. import {ECDSA} from "../../utils/cryptography/ECDSA.sol";
  11. import {Time} from "../../utils/types/Time.sol";
  12. /**
  13. * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be
  14. * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of
  15. * "representative" that will pool delegated voting units from different accounts and can then use it to vote in
  16. * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to
  17. * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.
  18. *
  19. * This contract is often combined with a token contract such that voting units correspond to token units. For an
  20. * example, see {ERC721Votes}.
  21. *
  22. * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed
  23. * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the
  24. * cost of this history tracking optional.
  25. *
  26. * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return
  27. * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the
  28. * previous example, it would be included in {ERC721-_update}).
  29. */
  30. abstract contract Votes is Context, EIP712, Nonces, IERC5805 {
  31. using Checkpoints for Checkpoints.Trace208;
  32. bytes32 private constant DELEGATION_TYPEHASH =
  33. keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
  34. mapping(address account => address) private _delegatee;
  35. mapping(address delegatee => Checkpoints.Trace208) private _delegateCheckpoints;
  36. Checkpoints.Trace208 private _totalCheckpoints;
  37. /**
  38. * @dev The clock was incorrectly modified.
  39. */
  40. error ERC6372InconsistentClock();
  41. /**
  42. * @dev Lookup to future votes is not available.
  43. */
  44. error ERC5805FutureLookup(uint256 timepoint, uint48 clock);
  45. /**
  46. * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based
  47. * checkpoints (and voting), in which case {CLOCK_MODE} should be overridden as well to match.
  48. */
  49. function clock() public view virtual returns (uint48) {
  50. return Time.blockNumber();
  51. }
  52. /**
  53. * @dev Machine-readable description of the clock as specified in ERC-6372.
  54. */
  55. // solhint-disable-next-line func-name-mixedcase
  56. function CLOCK_MODE() public view virtual returns (string memory) {
  57. // Check that the clock was not modified
  58. if (clock() != Time.blockNumber()) {
  59. revert ERC6372InconsistentClock();
  60. }
  61. return "mode=blocknumber&from=default";
  62. }
  63. /**
  64. * @dev Validate that a timepoint is in the past, and return it as a uint48.
  65. */
  66. function _validateTimepoint(uint256 timepoint) internal view returns (uint48) {
  67. uint48 currentTimepoint = clock();
  68. if (timepoint >= currentTimepoint) revert ERC5805FutureLookup(timepoint, currentTimepoint);
  69. return SafeCast.toUint48(timepoint);
  70. }
  71. /**
  72. * @dev Returns the current amount of votes that `account` has.
  73. */
  74. function getVotes(address account) public view virtual returns (uint256) {
  75. return _delegateCheckpoints[account].latest();
  76. }
  77. /**
  78. * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
  79. * configured to use block numbers, this will return the value at the end of the corresponding block.
  80. *
  81. * Requirements:
  82. *
  83. * - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.
  84. */
  85. function getPastVotes(address account, uint256 timepoint) public view virtual returns (uint256) {
  86. return _delegateCheckpoints[account].upperLookupRecent(_validateTimepoint(timepoint));
  87. }
  88. /**
  89. * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
  90. * configured to use block numbers, this will return the value at the end of the corresponding block.
  91. *
  92. * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
  93. * Votes that have not been delegated are still part of total supply, even though they would not participate in a
  94. * vote.
  95. *
  96. * Requirements:
  97. *
  98. * - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.
  99. */
  100. function getPastTotalSupply(uint256 timepoint) public view virtual returns (uint256) {
  101. return _totalCheckpoints.upperLookupRecent(_validateTimepoint(timepoint));
  102. }
  103. /**
  104. * @dev Returns the current total supply of votes.
  105. */
  106. function _getTotalSupply() internal view virtual returns (uint256) {
  107. return _totalCheckpoints.latest();
  108. }
  109. /**
  110. * @dev Returns the delegate that `account` has chosen.
  111. */
  112. function delegates(address account) public view virtual returns (address) {
  113. return _delegatee[account];
  114. }
  115. /**
  116. * @dev Delegates votes from the sender to `delegatee`.
  117. */
  118. function delegate(address delegatee) public virtual {
  119. address account = _msgSender();
  120. _delegate(account, delegatee);
  121. }
  122. /**
  123. * @dev Delegates votes from signer to `delegatee`.
  124. */
  125. function delegateBySig(
  126. address delegatee,
  127. uint256 nonce,
  128. uint256 expiry,
  129. uint8 v,
  130. bytes32 r,
  131. bytes32 s
  132. ) public virtual {
  133. if (block.timestamp > expiry) {
  134. revert VotesExpiredSignature(expiry);
  135. }
  136. address signer = ECDSA.recover(
  137. _hashTypedDataV4(keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
  138. v,
  139. r,
  140. s
  141. );
  142. _useCheckedNonce(signer, nonce);
  143. _delegate(signer, delegatee);
  144. }
  145. /**
  146. * @dev Delegate all of `account`'s voting units to `delegatee`.
  147. *
  148. * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
  149. */
  150. function _delegate(address account, address delegatee) internal virtual {
  151. address oldDelegate = delegates(account);
  152. _delegatee[account] = delegatee;
  153. emit DelegateChanged(account, oldDelegate, delegatee);
  154. _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
  155. }
  156. /**
  157. * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`
  158. * should be zero. Total supply of voting units will be adjusted with mints and burns.
  159. */
  160. function _transferVotingUnits(address from, address to, uint256 amount) internal virtual {
  161. if (from == address(0)) {
  162. _push(_totalCheckpoints, _add, SafeCast.toUint208(amount));
  163. }
  164. if (to == address(0)) {
  165. _push(_totalCheckpoints, _subtract, SafeCast.toUint208(amount));
  166. }
  167. _moveDelegateVotes(delegates(from), delegates(to), amount);
  168. }
  169. /**
  170. * @dev Moves delegated votes from one delegate to another.
  171. */
  172. function _moveDelegateVotes(address from, address to, uint256 amount) internal virtual {
  173. if (from != to && amount > 0) {
  174. if (from != address(0)) {
  175. (uint256 oldValue, uint256 newValue) = _push(
  176. _delegateCheckpoints[from],
  177. _subtract,
  178. SafeCast.toUint208(amount)
  179. );
  180. emit DelegateVotesChanged(from, oldValue, newValue);
  181. }
  182. if (to != address(0)) {
  183. (uint256 oldValue, uint256 newValue) = _push(
  184. _delegateCheckpoints[to],
  185. _add,
  186. SafeCast.toUint208(amount)
  187. );
  188. emit DelegateVotesChanged(to, oldValue, newValue);
  189. }
  190. }
  191. }
  192. /**
  193. * @dev Get number of checkpoints for `account`.
  194. */
  195. function _numCheckpoints(address account) internal view virtual returns (uint32) {
  196. return SafeCast.toUint32(_delegateCheckpoints[account].length());
  197. }
  198. /**
  199. * @dev Get the `pos`-th checkpoint for `account`.
  200. */
  201. function _checkpoints(
  202. address account,
  203. uint32 pos
  204. ) internal view virtual returns (Checkpoints.Checkpoint208 memory) {
  205. return _delegateCheckpoints[account].at(pos);
  206. }
  207. function _push(
  208. Checkpoints.Trace208 storage store,
  209. function(uint208, uint208) view returns (uint208) op,
  210. uint208 delta
  211. ) private returns (uint208 oldValue, uint208 newValue) {
  212. return store.push(clock(), op(store.latest(), delta));
  213. }
  214. function _add(uint208 a, uint208 b) private pure returns (uint208) {
  215. return a + b;
  216. }
  217. function _subtract(uint208 a, uint208 b) private pure returns (uint208) {
  218. return a - b;
  219. }
  220. /**
  221. * @dev Must return the voting units held by an account.
  222. */
  223. function _getVotingUnits(address) internal view virtual returns (uint256);
  224. }