Checkpoints.js 10 KB

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