ERC20Votes.sol 9.4 KB

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