ERC20Snapshot.sol 7.8 KB

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