Votes.sol 9.5 KB

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