ERC20Snapshot.sol 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Snapshot.sol)
  3. pragma solidity ^0.8.0;
  4. import "../ERC20.sol";
  5. import "../../../utils/Arrays.sol";
  6. import "../../../utils/Counters.sol";
  7. /**
  8. * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
  9. * total supply at the time are recorded for later access.
  10. *
  11. * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
  12. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
  13. * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
  14. * used to create an efficient ERC20 forking mechanism.
  15. *
  16. * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
  17. * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
  18. * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
  19. * and the account address.
  20. *
  21. * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it
  22. * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this
  23. * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
  24. *
  25. * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient
  26. * alternative consider {ERC20Votes}.
  27. *
  28. * ==== Gas Costs
  29. *
  30. * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
  31. * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
  32. * smaller since identical balances in subsequent snapshots are stored as a single entry.
  33. *
  34. * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
  35. * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
  36. * transfers will have normal cost until the next snapshot, and so on.
  37. */
  38. abstract contract ERC20Snapshot is ERC20 {
  39. // Inspired by Jordi Baylina's MiniMeToken to record historical balances:
  40. // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
  41. using Arrays for uint256[];
  42. using Counters for Counters.Counter;
  43. // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
  44. // Snapshot struct, but that would impede usage of functions that work on an array.
  45. struct Snapshots {
  46. uint256[] ids;
  47. uint256[] values;
  48. }
  49. mapping(address => Snapshots) private _accountBalanceSnapshots;
  50. Snapshots private _totalSupplySnapshots;
  51. // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
  52. Counters.Counter private _currentSnapshotId;
  53. /**
  54. * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
  55. */
  56. event Snapshot(uint256 id);
  57. /**
  58. * @dev Creates a new snapshot and returns its snapshot id.
  59. *
  60. * Emits a {Snapshot} event that contains the same id.
  61. *
  62. * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
  63. * set of accounts, for example using {AccessControl}, or it may be open to the public.
  64. *
  65. * [WARNING]
  66. * ====
  67. * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
  68. * you must consider that it can potentially be used by attackers in two ways.
  69. *
  70. * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
  71. * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
  72. * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
  73. * section above.
  74. *
  75. * We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
  76. * ====
  77. */
  78. function _snapshot() internal virtual returns (uint256) {
  79. _currentSnapshotId.increment();
  80. uint256 currentId = _getCurrentSnapshotId();
  81. emit Snapshot(currentId);
  82. return currentId;
  83. }
  84. /**
  85. * @dev Get the current snapshotId
  86. */
  87. function _getCurrentSnapshotId() internal view virtual returns (uint256) {
  88. return _currentSnapshotId.current();
  89. }
  90. /**
  91. * @dev Retrieves the balance of `account` at the time `snapshotId` was created.
  92. */
  93. function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) {
  94. (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
  95. return snapshotted ? value : balanceOf(account);
  96. }
  97. /**
  98. * @dev Retrieves the total supply at the time `snapshotId` was created.
  99. */
  100. function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) {
  101. (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
  102. return snapshotted ? value : totalSupply();
  103. }
  104. // Update balance and/or total supply snapshots before the values are modified. This is implemented
  105. // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
  106. function _beforeTokenTransfer(
  107. address from,
  108. address to,
  109. uint256 amount
  110. ) internal virtual override {
  111. super._beforeTokenTransfer(from, to, amount);
  112. if (from == address(0)) {
  113. // mint
  114. _updateAccountSnapshot(to);
  115. _updateTotalSupplySnapshot();
  116. } else if (to == address(0)) {
  117. // burn
  118. _updateAccountSnapshot(from);
  119. _updateTotalSupplySnapshot();
  120. } else {
  121. // transfer
  122. _updateAccountSnapshot(from);
  123. _updateAccountSnapshot(to);
  124. }
  125. }
  126. function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) {
  127. require(snapshotId > 0, "ERC20Snapshot: id is 0");
  128. require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id");
  129. // When a valid snapshot is queried, there are three possibilities:
  130. // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
  131. // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
  132. // to this id is the current one.
  133. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
  134. // requested id, and its value is the one to return.
  135. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be
  136. // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
  137. // larger than the requested one.
  138. //
  139. // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
  140. // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
  141. // exactly this.
  142. uint256 index = snapshots.ids.findUpperBound(snapshotId);
  143. if (index == snapshots.ids.length) {
  144. return (false, 0);
  145. } else {
  146. return (true, snapshots.values[index]);
  147. }
  148. }
  149. function _updateAccountSnapshot(address account) private {
  150. _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
  151. }
  152. function _updateTotalSupplySnapshot() private {
  153. _updateSnapshot(_totalSupplySnapshots, totalSupply());
  154. }
  155. function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
  156. uint256 currentId = _getCurrentSnapshotId();
  157. if (_lastSnapshotId(snapshots.ids) < currentId) {
  158. snapshots.ids.push(currentId);
  159. snapshots.values.push(currentValue);
  160. }
  161. }
  162. function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
  163. if (ids.length == 0) {
  164. return 0;
  165. } else {
  166. return ids[ids.length - 1];
  167. }
  168. }
  169. }