ERC20SnapshotUpgradeable.sol 9.0 KB

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