ERC20Votes.sol 8.4 KB

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