Votes.sol 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.6.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. require(blockNumber < block.number, "Votes: block not yet mined");
  66. return _totalCheckpoints.getAtProbablyRecentBlock(blockNumber);
  67. }
  68. /**
  69. * @dev Returns the current total supply of votes.
  70. */
  71. function _getTotalSupply() internal view virtual returns (uint256) {
  72. return _totalCheckpoints.latest();
  73. }
  74. /**
  75. * @dev Returns the delegate that `account` has chosen.
  76. */
  77. function delegates(address account) public view virtual override returns (address) {
  78. return _delegation[account];
  79. }
  80. /**
  81. * @dev Delegates votes from the sender to `delegatee`.
  82. */
  83. function delegate(address delegatee) public virtual override {
  84. address account = _msgSender();
  85. _delegate(account, delegatee);
  86. }
  87. /**
  88. * @dev Delegates votes from signer to `delegatee`.
  89. */
  90. function delegateBySig(
  91. address delegatee,
  92. uint256 nonce,
  93. uint256 expiry,
  94. uint8 v,
  95. bytes32 r,
  96. bytes32 s
  97. ) public virtual override {
  98. require(block.timestamp <= expiry, "Votes: signature expired");
  99. address signer = ECDSA.recover(
  100. _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
  101. v,
  102. r,
  103. s
  104. );
  105. require(nonce == _useNonce(signer), "Votes: invalid nonce");
  106. _delegate(signer, delegatee);
  107. }
  108. /**
  109. * @dev Delegate all of `account`'s voting units to `delegatee`.
  110. *
  111. * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
  112. */
  113. function _delegate(address account, address delegatee) internal virtual {
  114. address oldDelegate = delegates(account);
  115. _delegation[account] = delegatee;
  116. emit DelegateChanged(account, oldDelegate, delegatee);
  117. _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));
  118. }
  119. /**
  120. * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`
  121. * should be zero. Total supply of voting units will be adjusted with mints and burns.
  122. */
  123. function _transferVotingUnits(
  124. address from,
  125. address to,
  126. uint256 amount
  127. ) internal virtual {
  128. if (from == address(0)) {
  129. _totalCheckpoints.push(_add, amount);
  130. }
  131. if (to == address(0)) {
  132. _totalCheckpoints.push(_subtract, amount);
  133. }
  134. _moveDelegateVotes(delegates(from), delegates(to), amount);
  135. }
  136. /**
  137. * @dev Moves delegated votes from one delegate to another.
  138. */
  139. function _moveDelegateVotes(
  140. address from,
  141. address to,
  142. uint256 amount
  143. ) private {
  144. if (from != to && amount > 0) {
  145. if (from != address(0)) {
  146. (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount);
  147. emit DelegateVotesChanged(from, oldValue, newValue);
  148. }
  149. if (to != address(0)) {
  150. (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount);
  151. emit DelegateVotesChanged(to, oldValue, newValue);
  152. }
  153. }
  154. }
  155. /**
  156. * @dev Get number of checkpoints for `account`.
  157. */
  158. function _numCheckpoints(address account) internal view virtual returns (uint32) {
  159. return SafeCast.toUint32(_delegateCheckpoints[account].length());
  160. }
  161. /**
  162. * @dev Get the `pos`-th checkpoint for `account`.
  163. */
  164. function _checkpoints(address account, uint32 pos) internal view virtual returns (Checkpoints.Checkpoint memory) {
  165. return _delegateCheckpoints[account].getAtPosition(pos);
  166. }
  167. function _add(uint256 a, uint256 b) private pure returns (uint256) {
  168. return a + b;
  169. }
  170. function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
  171. return a - b;
  172. }
  173. /**
  174. * @dev Returns the contract's {EIP712} domain separator.
  175. */
  176. // solhint-disable-next-line func-name-mixedcase
  177. function DOMAIN_SEPARATOR() external view returns (bytes32) {
  178. return _domainSeparatorV4();
  179. }
  180. /**
  181. * @dev Must return the voting units held by an account.
  182. */
  183. function _getVotingUnits(address) internal view virtual returns (uint256);
  184. }