Checkpoints.js 10 KB

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