ERC20Snapshot.sol 8.4 KB

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