Checkpoints.js 9.9 KB

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