Votes.sol 9.4 KB

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