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