Checkpoints.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. const format = require('../format-lines');
  2. const VALUE_SIZES = [ 224, 160 ];
  3. const header = `\
  4. pragma solidity ^0.8.0;
  5. import "./math/Math.sol";
  6. import "./math/SafeCast.sol";
  7. /**
  8. * @dev This library defines the \`History\` struct, for checkpointing values as they change at different points in
  9. * time, and later looking up past values by block number. See {Votes} as an example.
  10. *
  11. * To create a history of checkpoints define a variable type \`Checkpoints.History\` in your contract, and store a new
  12. * checkpoint for the current transaction block using the {push} function.
  13. *
  14. * _Available since v4.5._
  15. */
  16. `;
  17. const types = opts => `\
  18. struct ${opts.historyTypeName} {
  19. ${opts.checkpointTypeName}[] ${opts.checkpointFieldName};
  20. }
  21. struct ${opts.checkpointTypeName} {
  22. ${opts.keyTypeName} ${opts.keyFieldName};
  23. ${opts.valueTypeName} ${opts.valueFieldName};
  24. }
  25. `;
  26. /* eslint-disable max-len */
  27. const operations = opts => `\
  28. /**
  29. * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
  30. */
  31. function latest(${opts.historyTypeName} storage self) internal view returns (${opts.valueTypeName}) {
  32. uint256 pos = self.${opts.checkpointFieldName}.length;
  33. return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
  34. }
  35. /**
  36. * @dev Pushes a (\`key\`, \`value\`) pair into a ${opts.historyTypeName} so that it is stored as the checkpoint.
  37. *
  38. * Returns previous value and new value.
  39. */
  40. function push(
  41. ${opts.historyTypeName} storage self,
  42. ${opts.keyTypeName} key,
  43. ${opts.valueTypeName} value
  44. ) internal returns (${opts.valueTypeName}, ${opts.valueTypeName}) {
  45. return _insert(self.${opts.checkpointFieldName}, key, value);
  46. }
  47. /**
  48. * @dev Returns the value in the oldest checkpoint with key greater or equal than the search key, or zero if there is none.
  49. */
  50. function lowerLookup(${opts.historyTypeName} storage self, ${opts.keyTypeName} key) internal view returns (${opts.valueTypeName}) {
  51. uint256 length = self.${opts.checkpointFieldName}.length;
  52. uint256 pos = _lowerBinaryLookup(self.${opts.checkpointFieldName}, key, 0, length);
  53. return pos == length ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos).${opts.valueFieldName};
  54. }
  55. /**
  56. * @dev Returns the value in the most recent checkpoint with key lower or equal than the search key.
  57. */
  58. function upperLookup(${opts.historyTypeName} storage self, ${opts.keyTypeName} key) internal view returns (${opts.valueTypeName}) {
  59. uint256 length = self.${opts.checkpointFieldName}.length;
  60. uint256 pos = _upperBinaryLookup(self.${opts.checkpointFieldName}, key, 0, length);
  61. return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
  62. }
  63. `;
  64. const legacyOperations = opts => `\
  65. /**
  66. * @dev Returns the value in the latest checkpoint, or zero if there are no checkpoints.
  67. */
  68. function latest(${opts.historyTypeName} storage self) internal view returns (uint256) {
  69. uint256 pos = self.${opts.checkpointFieldName}.length;
  70. return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
  71. }
  72. /**
  73. * @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one
  74. * before it is returned, or zero otherwise.
  75. */
  76. function getAtBlock(${opts.historyTypeName} storage self, uint256 blockNumber) internal view returns (uint256) {
  77. require(blockNumber < block.number, "Checkpoints: block not yet mined");
  78. uint32 key = SafeCast.toUint32(blockNumber);
  79. uint256 length = self.${opts.checkpointFieldName}.length;
  80. uint256 pos = _upperBinaryLookup(self.${opts.checkpointFieldName}, key, 0, length);
  81. return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
  82. }
  83. /**
  84. * @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one
  85. * before it is returned, or zero otherwise. Similar to {upperLookup} but optimized for the case when the searched
  86. * checkpoint is probably "recent", defined as being among the last sqrt(N) checkpoints where N is the number of
  87. * checkpoints.
  88. */
  89. function getAtProbablyRecentBlock(${opts.historyTypeName} storage self, uint256 blockNumber) internal view returns (uint256) {
  90. require(blockNumber < block.number, "Checkpoints: block not yet mined");
  91. uint32 key = SafeCast.toUint32(blockNumber);
  92. uint256 length = self.${opts.checkpointFieldName}.length;
  93. uint256 low = 0;
  94. uint256 high = length;
  95. if (length > 5) {
  96. uint256 mid = length - Math.sqrt(length);
  97. if (key < _unsafeAccess(self.${opts.checkpointFieldName}, mid)._blockNumber) {
  98. high = mid;
  99. } else {
  100. low = mid + 1;
  101. }
  102. }
  103. uint256 pos = _upperBinaryLookup(self.${opts.checkpointFieldName}, key, low, high);
  104. return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
  105. }
  106. /**
  107. * @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block.
  108. *
  109. * Returns previous value and new value.
  110. */
  111. function push(${opts.historyTypeName} storage self, uint256 value) internal returns (uint256, uint256) {
  112. return _insert(self.${opts.checkpointFieldName}, SafeCast.toUint32(block.number), SafeCast.toUint224(value));
  113. }
  114. /**
  115. * @dev Pushes a value onto a History, by updating the latest value using binary operation \`op\`. The new value will
  116. * be set to \`op(latest, delta)\`.
  117. *
  118. * Returns previous value and new value.
  119. */
  120. function push(
  121. ${opts.historyTypeName} storage self,
  122. function(uint256, uint256) view returns (uint256) op,
  123. uint256 delta
  124. ) internal returns (uint256, uint256) {
  125. return push(self, op(latest(self), delta));
  126. }
  127. `;
  128. const helpers = opts => `\
  129. /**
  130. * @dev Pushes a (\`key\`, \`value\`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
  131. * or by updating the last one.
  132. */
  133. function _insert(
  134. ${opts.checkpointTypeName}[] storage self,
  135. ${opts.keyTypeName} key,
  136. ${opts.valueTypeName} value
  137. ) private returns (${opts.valueTypeName}, ${opts.valueTypeName}) {
  138. uint256 pos = self.length;
  139. if (pos > 0) {
  140. // Copying to memory is important here.
  141. ${opts.checkpointTypeName} memory last = _unsafeAccess(self, pos - 1);
  142. // Checkpoints keys must be increasing.
  143. require(last.${opts.keyFieldName} <= key, "Checkpoint: invalid key");
  144. // Update or push new checkpoint
  145. if (last.${opts.keyFieldName} == key) {
  146. _unsafeAccess(self, pos - 1).${opts.valueFieldName} = value;
  147. } else {
  148. self.push(${opts.checkpointTypeName}({${opts.keyFieldName}: key, ${opts.valueFieldName}: value}));
  149. }
  150. return (last.${opts.valueFieldName}, value);
  151. } else {
  152. self.push(${opts.checkpointTypeName}({${opts.keyFieldName}: key, ${opts.valueFieldName}: value}));
  153. return (0, value);
  154. }
  155. }
  156. /**
  157. * @dev Return the index of the oldest checkpoint whose key is greater than the search key, or \`high\` if there is none.
  158. * \`low\` and \`high\` define a section where to do the search, with inclusive \`low\` and exclusive \`high\`.
  159. *
  160. * WARNING: \`high\` should not be greater than the array's length.
  161. */
  162. function _upperBinaryLookup(
  163. ${opts.checkpointTypeName}[] storage self,
  164. ${opts.keyTypeName} key,
  165. uint256 low,
  166. uint256 high
  167. ) private view returns (uint256) {
  168. while (low < high) {
  169. uint256 mid = Math.average(low, high);
  170. if (_unsafeAccess(self, mid).${opts.keyFieldName} > key) {
  171. high = mid;
  172. } else {
  173. low = mid + 1;
  174. }
  175. }
  176. return high;
  177. }
  178. /**
  179. * @dev Return the index of the oldest checkpoint whose key is greater or equal than the search key, or \`high\` if there is none.
  180. * \`low\` and \`high\` define a section where to do the search, with inclusive \`low\` and exclusive \`high\`.
  181. *
  182. * WARNING: \`high\` should not be greater than the array's length.
  183. */
  184. function _lowerBinaryLookup(
  185. ${opts.checkpointTypeName}[] storage self,
  186. ${opts.keyTypeName} key,
  187. uint256 low,
  188. uint256 high
  189. ) private view returns (uint256) {
  190. while (low < high) {
  191. uint256 mid = Math.average(low, high);
  192. if (_unsafeAccess(self, mid).${opts.keyFieldName} < key) {
  193. low = mid + 1;
  194. } else {
  195. high = mid;
  196. }
  197. }
  198. return high;
  199. }
  200. function _unsafeAccess(${opts.checkpointTypeName}[] storage self, uint256 pos)
  201. private
  202. view
  203. returns (${opts.checkpointTypeName} storage result)
  204. {
  205. assembly {
  206. mstore(0, self.slot)
  207. result.slot := add(keccak256(0, 0x20), pos)
  208. }
  209. }
  210. `;
  211. /* eslint-enable max-len */
  212. // OPTIONS
  213. const defaultOpts = (size) => ({
  214. historyTypeName: `Trace${size}`,
  215. checkpointTypeName: `Checkpoint${size}`,
  216. checkpointFieldName: '_checkpoints',
  217. keyTypeName: `uint${256 - size}`,
  218. keyFieldName: '_key',
  219. valueTypeName: `uint${size}`,
  220. valueFieldName: '_value',
  221. });
  222. const OPTS = VALUE_SIZES.map(size => defaultOpts(size));
  223. const LEGACY_OPTS = {
  224. ...defaultOpts(224),
  225. historyTypeName: 'History',
  226. checkpointTypeName: 'Checkpoint',
  227. keyFieldName: '_blockNumber',
  228. };
  229. // GENERATE
  230. module.exports = format(
  231. header.trimEnd(),
  232. 'library Checkpoints {',
  233. [
  234. // Legacy types & functions
  235. types(LEGACY_OPTS),
  236. legacyOperations(LEGACY_OPTS),
  237. helpers(LEGACY_OPTS),
  238. // New flavors
  239. ...OPTS.flatMap(opts => [
  240. types(opts),
  241. operations(opts),
  242. helpers(opts),
  243. ]),
  244. ],
  245. '}',
  246. );