Checkpoints.js 11 KB

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