Votes.sol 9.4 KB

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