Votes.sol 9.2 KB

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