ERC20Votes.sol 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. /**
  27. * @dev Get the `pos`-th checkpoint for `account`.
  28. */
  29. function checkpoints(address account, uint32 pos) external view virtual override returns (Checkpoint memory) {
  30. return _checkpoints[account][pos];
  31. }
  32. /**
  33. * @dev Get number of checkpoints for `account`.
  34. */
  35. function numCheckpoints(address account) external view virtual override returns (uint32) {
  36. return SafeCast.toUint32(_checkpoints[account].length);
  37. }
  38. /**
  39. * @dev Get the address `account` is currently delegating to.
  40. */
  41. function delegates(address account) public view virtual override returns (address) {
  42. return _delegates[account];
  43. }
  44. /**
  45. * @dev Gets the current votes balance for `account`
  46. */
  47. function getCurrentVotes(address account) external view override returns (uint256) {
  48. uint256 pos = _checkpoints[account].length;
  49. return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
  50. }
  51. /**
  52. * @dev Determine the number of votes for `account` at the begining of `blockNumber`.
  53. */
  54. function getPriorVotes(address account, uint256 blockNumber) external view override returns (uint256) {
  55. require(blockNumber < block.number, "ERC20Votes::getPriorVotes: not yet determined");
  56. Checkpoint[] storage ckpts = _checkpoints[account];
  57. // We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
  58. //
  59. // During the loop, the index of the wanted checkpoint remains in the range [low, high).
  60. // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
  61. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
  62. // - If the middle checkpoint is before `blockNumber`, we look in [mid+1, high)
  63. // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
  64. // out of bounds (in which case we're looking too far in the past and the result is 0).
  65. // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
  66. // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
  67. // the same.
  68. uint256 high = ckpts.length;
  69. uint256 low = 0;
  70. while (low < high) {
  71. uint256 mid = Math.average(low, high);
  72. if (ckpts[mid].fromBlock > blockNumber) {
  73. high = mid;
  74. } else {
  75. low = mid + 1;
  76. }
  77. }
  78. return high == 0 ? 0 : ckpts[high - 1].votes;
  79. }
  80. /**
  81. * @dev Delegate votes from the sender to `delegatee`.
  82. */
  83. function delegate(address delegatee) public virtual override {
  84. return _delegate(_msgSender(), delegatee);
  85. }
  86. /**
  87. * @dev Delegates votes from signer to `delegatee`
  88. */
  89. function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s)
  90. public virtual override
  91. {
  92. require(block.timestamp <= expiry, "ERC20Votes::delegateBySig: signature expired");
  93. address signer = ECDSA.recover(
  94. _hashTypedDataV4(keccak256(abi.encode(
  95. _DELEGATION_TYPEHASH,
  96. delegatee,
  97. nonce,
  98. expiry
  99. ))),
  100. v, r, s
  101. );
  102. require(nonce == _useNonce(signer), "ERC20Votes::delegateBySig: invalid nonce");
  103. return _delegate(signer, delegatee);
  104. }
  105. /**
  106. * @dev Change delegation for `delegator` to `delegatee`.
  107. */
  108. function _delegate(address delegator, address delegatee) internal virtual {
  109. address currentDelegate = delegates(delegator);
  110. uint256 delegatorBalance = balanceOf(delegator);
  111. _delegates[delegator] = delegatee;
  112. emit DelegateChanged(delegator, currentDelegate, delegatee);
  113. _moveVotingPower(currentDelegate, delegatee, delegatorBalance);
  114. }
  115. function _moveVotingPower(address src, address dst, uint256 amount) private {
  116. if (src != dst && amount > 0) {
  117. if (src != address(0)) {
  118. uint256 srcCkptLen = _checkpoints[src].length;
  119. uint256 srcCkptOld = srcCkptLen == 0 ? 0 : _checkpoints[src][srcCkptLen - 1].votes;
  120. uint256 srcCkptNew = srcCkptOld - amount;
  121. _writeCheckpoint(src, srcCkptLen, srcCkptOld, srcCkptNew);
  122. }
  123. if (dst != address(0)) {
  124. uint256 dstCkptLen = _checkpoints[dst].length;
  125. uint256 dstCkptOld = dstCkptLen == 0 ? 0 : _checkpoints[dst][dstCkptLen - 1].votes;
  126. uint256 dstCkptNew = dstCkptOld + amount;
  127. _writeCheckpoint(dst, dstCkptLen, dstCkptOld, dstCkptNew);
  128. }
  129. }
  130. }
  131. function _writeCheckpoint(address delegatee, uint256 pos, uint256 oldWeight, uint256 newWeight) private {
  132. if (pos > 0 && _checkpoints[delegatee][pos - 1].fromBlock == block.number) {
  133. _checkpoints[delegatee][pos - 1].votes = SafeCast.toUint224(newWeight);
  134. } else {
  135. _checkpoints[delegatee].push(Checkpoint({
  136. fromBlock: SafeCast.toUint32(block.number),
  137. votes: SafeCast.toUint224(newWeight)
  138. }));
  139. }
  140. emit DelegateVotesChanged(delegatee, oldWeight, newWeight);
  141. }
  142. function _mint(address account, uint256 amount) internal virtual override {
  143. super._mint(account, amount);
  144. require(totalSupply() <= type(uint224).max, "ERC20Votes: total supply exceeds 2**224");
  145. }
  146. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
  147. _moveVotingPower(delegates(from), delegates(to), amount);
  148. }
  149. }