ERC20Snapshot.sol 8.0 KB

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