ERC20Votes.sol 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Votes.sol)
  3. pragma solidity ^0.8.0;
  4. import "./draft-ERC20Permit.sol";
  5. import "../../../utils/math/Math.sol";
  6. import "../../../governance/utils/IVotes.sol";
  7. import "../../../utils/math/SafeCast.sol";
  8. import "../../../utils/cryptography/ECDSA.sol";
  9. /**
  10. * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
  11. * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
  12. *
  13. * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
  14. *
  15. * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
  16. * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
  17. * power can be queried through the public accessors {getVotes} and {getPastVotes}.
  18. *
  19. * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
  20. * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
  21. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
  22. * will significantly increase the base gas cost of transfers.
  23. *
  24. * _Available since v4.2._
  25. */
  26. abstract contract ERC20Votes is IVotes, ERC20Permit {
  27. struct Checkpoint {
  28. uint32 fromBlock;
  29. uint224 votes;
  30. }
  31. bytes32 private constant _DELEGATION_TYPEHASH =
  32. keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
  33. mapping(address => address) private _delegates;
  34. mapping(address => Checkpoint[]) private _checkpoints;
  35. Checkpoint[] private _totalSupplyCheckpoints;
  36. /**
  37. * @dev Get the `pos`-th checkpoint for `account`.
  38. */
  39. function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
  40. return _checkpoints[account][pos];
  41. }
  42. /**
  43. * @dev Get number of checkpoints for `account`.
  44. */
  45. function numCheckpoints(address account) public view virtual returns (uint32) {
  46. return SafeCast.toUint32(_checkpoints[account].length);
  47. }
  48. /**
  49. * @dev Get the address `account` is currently delegating to.
  50. */
  51. function delegates(address account) public view virtual override returns (address) {
  52. return _delegates[account];
  53. }
  54. /**
  55. * @dev Gets the current votes balance for `account`
  56. */
  57. function getVotes(address account) public view override returns (uint256) {
  58. uint256 pos = _checkpoints[account].length;
  59. return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
  60. }
  61. /**
  62. * @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
  63. *
  64. * Requirements:
  65. *
  66. * - `blockNumber` must have been already mined
  67. */
  68. function getPastVotes(address account, uint256 blockNumber) public view override returns (uint256) {
  69. require(blockNumber < block.number, "ERC20Votes: block not yet mined");
  70. return _checkpointsLookup(_checkpoints[account], blockNumber);
  71. }
  72. /**
  73. * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
  74. * It is but NOT the sum of all the delegated votes!
  75. *
  76. * Requirements:
  77. *
  78. * - `blockNumber` must have been already mined
  79. */
  80. function getPastTotalSupply(uint256 blockNumber) public view override returns (uint256) {
  81. require(blockNumber < block.number, "ERC20Votes: block not yet mined");
  82. return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
  83. }
  84. /**
  85. * @dev Lookup a value in a list of (sorted) checkpoints.
  86. */
  87. function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
  88. // We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
  89. //
  90. // During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
  91. // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
  92. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
  93. // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
  94. // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
  95. // out of bounds (in which case we're looking too far in the past and the result is 0).
  96. // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
  97. // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
  98. // the same.
  99. uint256 high = ckpts.length;
  100. uint256 low = 0;
  101. while (low < high) {
  102. uint256 mid = Math.average(low, high);
  103. if (ckpts[mid].fromBlock > blockNumber) {
  104. high = mid;
  105. } else {
  106. low = mid + 1;
  107. }
  108. }
  109. return high == 0 ? 0 : ckpts[high - 1].votes;
  110. }
  111. /**
  112. * @dev Delegate votes from the sender to `delegatee`.
  113. */
  114. function delegate(address delegatee) public virtual override {
  115. _delegate(_msgSender(), delegatee);
  116. }
  117. /**
  118. * @dev Delegates votes from signer to `delegatee`
  119. */
  120. function delegateBySig(
  121. address delegatee,
  122. uint256 nonce,
  123. uint256 expiry,
  124. uint8 v,
  125. bytes32 r,
  126. bytes32 s
  127. ) public virtual override {
  128. require(block.timestamp <= expiry, "ERC20Votes: signature expired");
  129. address signer = ECDSA.recover(
  130. _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
  131. v,
  132. r,
  133. s
  134. );
  135. require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
  136. _delegate(signer, delegatee);
  137. }
  138. /**
  139. * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
  140. */
  141. function _maxSupply() internal view virtual returns (uint224) {
  142. return type(uint224).max;
  143. }
  144. /**
  145. * @dev Snapshots the totalSupply after it has been increased.
  146. */
  147. function _mint(address account, uint256 amount) internal virtual override {
  148. super._mint(account, amount);
  149. require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
  150. _writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
  151. }
  152. /**
  153. * @dev Snapshots the totalSupply after it has been decreased.
  154. */
  155. function _burn(address account, uint256 amount) internal virtual override {
  156. super._burn(account, amount);
  157. _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
  158. }
  159. /**
  160. * @dev Move voting power when tokens are transferred.
  161. *
  162. * Emits a {DelegateVotesChanged} event.
  163. */
  164. function _afterTokenTransfer(
  165. address from,
  166. address to,
  167. uint256 amount
  168. ) internal virtual override {
  169. super._afterTokenTransfer(from, to, amount);
  170. _moveVotingPower(delegates(from), delegates(to), amount);
  171. }
  172. /**
  173. * @dev Change delegation for `delegator` to `delegatee`.
  174. *
  175. * Emits events {DelegateChanged} and {DelegateVotesChanged}.
  176. */
  177. function _delegate(address delegator, address delegatee) internal virtual {
  178. address currentDelegate = delegates(delegator);
  179. uint256 delegatorBalance = balanceOf(delegator);
  180. _delegates[delegator] = delegatee;
  181. emit DelegateChanged(delegator, currentDelegate, delegatee);
  182. _moveVotingPower(currentDelegate, delegatee, delegatorBalance);
  183. }
  184. function _moveVotingPower(
  185. address src,
  186. address dst,
  187. uint256 amount
  188. ) private {
  189. if (src != dst && amount > 0) {
  190. if (src != address(0)) {
  191. (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
  192. emit DelegateVotesChanged(src, oldWeight, newWeight);
  193. }
  194. if (dst != address(0)) {
  195. (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
  196. emit DelegateVotesChanged(dst, oldWeight, newWeight);
  197. }
  198. }
  199. }
  200. function _writeCheckpoint(
  201. Checkpoint[] storage ckpts,
  202. function(uint256, uint256) view returns (uint256) op,
  203. uint256 delta
  204. ) private returns (uint256 oldWeight, uint256 newWeight) {
  205. uint256 pos = ckpts.length;
  206. oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
  207. newWeight = op(oldWeight, delta);
  208. if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
  209. ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
  210. } else {
  211. ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
  212. }
  213. }
  214. function _add(uint256 a, uint256 b) private pure returns (uint256) {
  215. return a + b;
  216. }
  217. function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
  218. return a - b;
  219. }
  220. }