Votes.sol 9.2 KB

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