ERC20Snapshot.sol 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. pragma solidity ^0.6.0;
  2. import "../math/SafeMath.sol";
  3. import "../utils/Arrays.sol";
  4. import "../drafts/Counters.sol";
  5. import "../token/ERC20/ERC20.sol";
  6. /**
  7. * @title ERC20 token with snapshots.
  8. * @dev Inspired by Jordi Baylina's
  9. * https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol[MiniMeToken]
  10. * to record historical balances.
  11. *
  12. * When a snapshot is made, the balances and total supply at the time of the snapshot are recorded for later
  13. * access.
  14. *
  15. * To make a snapshot, call the {snapshot} function, which will emit the {Snapshot} event and return a snapshot id.
  16. * To get the total supply from a snapshot, call the function {totalSupplyAt} with the snapshot id.
  17. * To get the balance of an account from a snapshot, call the {balanceOfAt} function with the snapshot id and the
  18. * account address.
  19. * @author Validity Labs AG <info@validitylabs.org>
  20. */
  21. contract ERC20Snapshot is ERC20 {
  22. using SafeMath for uint256;
  23. using Arrays for uint256[];
  24. using Counters for Counters.Counter;
  25. // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
  26. // Snapshot struct, but that would impede usage of functions that work on an array.
  27. struct Snapshots {
  28. uint256[] ids;
  29. uint256[] values;
  30. }
  31. mapping (address => Snapshots) private _accountBalanceSnapshots;
  32. Snapshots private _totalSupplySnapshots;
  33. // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
  34. Counters.Counter private _currentSnapshotId;
  35. event Snapshot(uint256 id);
  36. // Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a
  37. // balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid
  38. // when required, but is also flexible enough that it allows for e.g. daily snapshots.
  39. function snapshot() public virtual returns (uint256) {
  40. _currentSnapshotId.increment();
  41. uint256 currentId = _currentSnapshotId.current();
  42. emit Snapshot(currentId);
  43. return currentId;
  44. }
  45. function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
  46. (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
  47. return snapshotted ? value : balanceOf(account);
  48. }
  49. function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
  50. (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
  51. return snapshotted ? value : totalSupply();
  52. }
  53. // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
  54. // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
  55. // The same is true for the total supply and _mint and _burn.
  56. function _transfer(address from, address to, uint256 value) internal virtual override {
  57. _updateAccountSnapshot(from);
  58. _updateAccountSnapshot(to);
  59. super._transfer(from, to, value);
  60. }
  61. function _mint(address account, uint256 value) internal virtual override {
  62. _updateAccountSnapshot(account);
  63. _updateTotalSupplySnapshot();
  64. super._mint(account, value);
  65. }
  66. function _burn(address account, uint256 value) internal virtual override {
  67. _updateAccountSnapshot(account);
  68. _updateTotalSupplySnapshot();
  69. super._burn(account, value);
  70. }
  71. // When a valid snapshot is queried, there are three possibilities:
  72. // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
  73. // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
  74. // to this id is the current one.
  75. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
  76. // requested id, and its value is the one to return.
  77. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be
  78. // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
  79. // larger than the requested one.
  80. //
  81. // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
  82. // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
  83. // exactly this.
  84. function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
  85. private view returns (bool, uint256)
  86. {
  87. require(snapshotId > 0, "ERC20Snapshot: id is 0");
  88. // solhint-disable-next-line max-line-length
  89. require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
  90. uint256 index = snapshots.ids.findUpperBound(snapshotId);
  91. if (index == snapshots.ids.length) {
  92. return (false, 0);
  93. } else {
  94. return (true, snapshots.values[index]);
  95. }
  96. }
  97. function _updateAccountSnapshot(address account) private {
  98. _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
  99. }
  100. function _updateTotalSupplySnapshot() private {
  101. _updateSnapshot(_totalSupplySnapshots, totalSupply());
  102. }
  103. function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
  104. uint256 currentId = _currentSnapshotId.current();
  105. if (_lastSnapshotId(snapshots.ids) < currentId) {
  106. snapshots.ids.push(currentId);
  107. snapshots.values.push(currentValue);
  108. }
  109. }
  110. function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
  111. if (ids.length == 0) {
  112. return 0;
  113. } else {
  114. return ids[ids.length - 1];
  115. }
  116. }
  117. }