ERC20VotesLegacyMock.sol 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {ERC20Permit} from "../../token/ERC20/extensions/ERC20Permit.sol";
  4. import {Math} from "../../utils/math/Math.sol";
  5. import {IVotes} from "../../governance/utils/IVotes.sol";
  6. import {SafeCast} from "../../utils/math/SafeCast.sol";
  7. import {ECDSA} from "../../utils/cryptography/ECDSA.sol";
  8. /**
  9. * @dev Copied from the master branch at commit 86de1e8b6c3fa6b4efa4a5435869d2521be0f5f5
  10. */
  11. abstract contract ERC20VotesLegacyMock is IVotes, ERC20Permit {
  12. struct Checkpoint {
  13. uint32 fromBlock;
  14. uint224 votes;
  15. }
  16. bytes32 private constant _DELEGATION_TYPEHASH =
  17. keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
  18. mapping(address account => address) private _delegatee;
  19. mapping(address delegatee => Checkpoint[]) private _checkpoints;
  20. Checkpoint[] private _totalSupplyCheckpoints;
  21. /**
  22. * @dev Get the `pos`-th checkpoint for `account`.
  23. */
  24. function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
  25. return _checkpoints[account][pos];
  26. }
  27. /**
  28. * @dev Get number of checkpoints for `account`.
  29. */
  30. function numCheckpoints(address account) public view virtual returns (uint32) {
  31. return SafeCast.toUint32(_checkpoints[account].length);
  32. }
  33. /**
  34. * @dev Get the address `account` is currently delegating to.
  35. */
  36. function delegates(address account) public view virtual returns (address) {
  37. return _delegatee[account];
  38. }
  39. /**
  40. * @dev Gets the current votes balance for `account`
  41. */
  42. function getVotes(address account) public view virtual returns (uint256) {
  43. uint256 pos = _checkpoints[account].length;
  44. unchecked {
  45. return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
  46. }
  47. }
  48. /**
  49. * @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
  50. *
  51. * Requirements:
  52. *
  53. * - `blockNumber` must have been already mined
  54. */
  55. function getPastVotes(address account, uint256 blockNumber) public view virtual returns (uint256) {
  56. require(blockNumber < block.number, "ERC20Votes: block not yet mined");
  57. return _checkpointsLookup(_checkpoints[account], blockNumber);
  58. }
  59. /**
  60. * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
  61. * It is NOT the sum of all the delegated votes!
  62. *
  63. * Requirements:
  64. *
  65. * - `blockNumber` must have been already mined
  66. */
  67. function getPastTotalSupply(uint256 blockNumber) public view virtual returns (uint256) {
  68. require(blockNumber < block.number, "ERC20Votes: block not yet mined");
  69. return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
  70. }
  71. /**
  72. * @dev Lookup a value in a list of (sorted) checkpoints.
  73. */
  74. function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
  75. // We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
  76. //
  77. // Initially we check if the block is recent to narrow the search range.
  78. // During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
  79. // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the
  80. // invariant.
  81. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
  82. // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
  83. // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
  84. // out of bounds (in which case we're looking too far in the past and the result is 0).
  85. // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
  86. // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
  87. // the same.
  88. uint256 length = ckpts.length;
  89. uint256 low = 0;
  90. uint256 high = length;
  91. if (length > 5) {
  92. uint256 mid = length - Math.sqrt(length);
  93. if (_unsafeAccess(ckpts, mid).fromBlock > blockNumber) {
  94. high = mid;
  95. } else {
  96. low = mid + 1;
  97. }
  98. }
  99. while (low < high) {
  100. uint256 mid = Math.average(low, high);
  101. if (_unsafeAccess(ckpts, mid).fromBlock > blockNumber) {
  102. high = mid;
  103. } else {
  104. low = mid + 1;
  105. }
  106. }
  107. unchecked {
  108. return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes;
  109. }
  110. }
  111. /**
  112. * @dev Delegate votes from the sender to `delegatee`.
  113. */
  114. function delegate(address delegatee) public virtual {
  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 {
  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 Move voting power when tokens are transferred.
  146. *
  147. * Emits a {IVotes-DelegateVotesChanged} event.
  148. */
  149. function _update(address from, address to, uint256 amount) internal virtual override {
  150. super._update(from, to, amount);
  151. if (from == address(0)) {
  152. require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
  153. _writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
  154. }
  155. if (to == address(0)) {
  156. _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
  157. }
  158. _moveVotingPower(delegates(from), delegates(to), amount);
  159. }
  160. /**
  161. * @dev Change delegation for `delegator` to `delegatee`.
  162. *
  163. * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
  164. */
  165. function _delegate(address delegator, address delegatee) internal virtual {
  166. address currentDelegate = delegates(delegator);
  167. uint256 delegatorBalance = balanceOf(delegator);
  168. _delegatee[delegator] = delegatee;
  169. emit DelegateChanged(delegator, currentDelegate, delegatee);
  170. _moveVotingPower(currentDelegate, delegatee, delegatorBalance);
  171. }
  172. function _moveVotingPower(address src, address dst, uint256 amount) private {
  173. if (src != dst && amount > 0) {
  174. if (src != address(0)) {
  175. (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
  176. emit DelegateVotesChanged(src, oldWeight, newWeight);
  177. }
  178. if (dst != address(0)) {
  179. (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
  180. emit DelegateVotesChanged(dst, oldWeight, newWeight);
  181. }
  182. }
  183. }
  184. function _writeCheckpoint(
  185. Checkpoint[] storage ckpts,
  186. function(uint256, uint256) view returns (uint256) op,
  187. uint256 delta
  188. ) private returns (uint256 oldWeight, uint256 newWeight) {
  189. uint256 pos = ckpts.length;
  190. unchecked {
  191. Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1);
  192. oldWeight = oldCkpt.votes;
  193. newWeight = op(oldWeight, delta);
  194. if (pos > 0 && oldCkpt.fromBlock == block.number) {
  195. _unsafeAccess(ckpts, pos - 1).votes = SafeCast.toUint224(newWeight);
  196. } else {
  197. ckpts.push(
  198. Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})
  199. );
  200. }
  201. }
  202. }
  203. function _add(uint256 a, uint256 b) private pure returns (uint256) {
  204. return a + b;
  205. }
  206. function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
  207. return a - b;
  208. }
  209. /**
  210. * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
  211. */
  212. function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) {
  213. assembly {
  214. mstore(0, ckpts.slot)
  215. result.slot := add(keccak256(0, 0x20), pos)
  216. }
  217. }
  218. }