Votes.sol 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 "../../utils/Context.sol";
  5. import "../../utils/Nonces.sol";
  6. import "../../utils/Checkpoints.sol";
  7. import "../../utils/cryptography/EIP712.sol";
  8. import "./IVotes.sol";
  9. import "../../utils/math/SafeCast.sol";
  10. /**
  11. * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be
  12. * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of
  13. * "representative" that will pool delegated voting units from different accounts and can then use it to vote in
  14. * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to
  15. * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.
  16. *
  17. * This contract is often combined with a token contract such that voting units correspond to token units. For an
  18. * example, see {ERC721Votes}.
  19. *
  20. * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed
  21. * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the
  22. * cost of this history tracking optional.
  23. *
  24. * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return
  25. * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the
  26. * previous example, it would be included in {ERC721-_beforeTokenTransfer}).
  27. *
  28. * _Available since v4.5._
  29. */
  30. abstract contract Votes is IVotes, Context, EIP712, Nonces {
  31. using Checkpoints for Checkpoints.History;
  32. bytes32 private constant _DELEGATION_TYPEHASH =
  33. keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
  34. mapping(address => address) private _delegation;
  35. mapping(address => Checkpoints.History) private _delegateCheckpoints;
  36. Checkpoints.History private _totalCheckpoints;
  37. /**
  38. * @dev Returns the current amount of votes that `account` has.
  39. */
  40. function getVotes(address account) public view virtual override returns (uint256) {
  41. return _delegateCheckpoints[account].latest();
  42. }
  43. /**
  44. * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
  45. *
  46. * Requirements:
  47. *
  48. * - `blockNumber` must have been already mined
  49. */
  50. function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
  51. return _delegateCheckpoints[account].getAtProbablyRecentBlock(blockNumber);
  52. }
  53. /**
  54. * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
  55. *
  56. * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
  57. * Votes that have not been delegated are still part of total supply, even though they would not participate in a
  58. * vote.
  59. *
  60. * Requirements:
  61. *
  62. * - `blockNumber` must have been already mined
  63. */
  64. function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
  65. return _totalCheckpoints.getAtProbablyRecentBlock(blockNumber);
  66. }
  67. /**
  68. * @dev Returns the current total supply of votes.
  69. */
  70. function _getTotalSupply() internal view virtual returns (uint256) {
  71. return _totalCheckpoints.latest();
  72. }
  73. /**
  74. * @dev Returns the delegate that `account` has chosen.
  75. */
  76. function delegates(address account) public view virtual override returns (address) {
  77. return _delegation[account];
  78. }
  79. /**
  80. * @dev Delegates votes from the sender to `delegatee`.
  81. */
  82. function delegate(address delegatee) public virtual override {
  83. address account = _msgSender();
  84. _delegate(account, delegatee);
  85. }
  86. /**
  87. * @dev Delegates votes from signer to `delegatee`.
  88. */
  89. function delegateBySig(
  90. address delegatee,
  91. uint256 nonce,
  92. uint256 expiry,
  93. uint8 v,
  94. bytes32 r,
  95. bytes32 s
  96. ) public virtual override {
  97. require(block.timestamp <= expiry, "Votes: signature expired");
  98. address signer = ECDSA.recover(
  99. _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
  100. v,
  101. r,
  102. s
  103. );
  104. require(nonce == _useNonce(signer), "Votes: invalid nonce");
  105. _delegate(signer, delegatee);
  106. }
  107. /**
  108. * @dev Delegate all of `account`'s voting units to `delegatee`.
  109. *
  110. * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
  111. */
  112. function _delegate(address account, address delegatee) internal virtual {
  113. address oldDelegate = delegates(account);
  114. _delegation[account] = delegatee;
  115. emit DelegateChanged(account, oldDelegate, delegatee);
  116. _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
  117. }
  118. /**
  119. * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`
  120. * should be zero. Total supply of voting units will be adjusted with mints and burns.
  121. */
  122. function _transferVotingUnits(address from, address to, uint256 amount) internal virtual {
  123. if (from == address(0)) {
  124. _totalCheckpoints.push(_add, amount);
  125. }
  126. if (to == address(0)) {
  127. _totalCheckpoints.push(_subtract, amount);
  128. }
  129. _moveDelegateVotes(delegates(from), delegates(to), amount);
  130. }
  131. /**
  132. * @dev Moves delegated votes from one delegate to another.
  133. */
  134. function _moveDelegateVotes(address from, address to, uint256 amount) private {
  135. if (from != to && amount > 0) {
  136. if (from != address(0)) {
  137. (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount);
  138. emit DelegateVotesChanged(from, oldValue, newValue);
  139. }
  140. if (to != address(0)) {
  141. (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount);
  142. emit DelegateVotesChanged(to, oldValue, newValue);
  143. }
  144. }
  145. }
  146. /**
  147. * @dev Get number of checkpoints for `account`.
  148. */
  149. function _numCheckpoints(address account) internal view virtual returns (uint32) {
  150. return SafeCast.toUint32(_delegateCheckpoints[account].length());
  151. }
  152. /**
  153. * @dev Get the `pos`-th checkpoint for `account`.
  154. */
  155. function _checkpoints(address account, uint32 pos) internal view virtual returns (Checkpoints.Checkpoint memory) {
  156. return _delegateCheckpoints[account].getAtPosition(pos);
  157. }
  158. function _add(uint256 a, uint256 b) private pure returns (uint256) {
  159. return a + b;
  160. }
  161. function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
  162. return a - b;
  163. }
  164. /**
  165. * @dev Returns the contract's {EIP712} domain separator.
  166. */
  167. // solhint-disable-next-line func-name-mixedcase
  168. function DOMAIN_SEPARATOR() external view returns (bytes32) {
  169. return _domainSeparatorV4();
  170. }
  171. /**
  172. * @dev Must return the voting units held by an account.
  173. */
  174. function _getVotingUnits(address) internal view virtual returns (uint256);
  175. }