ERC20Snapshot.sol 5.9 KB

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