Checkpoints.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. const format = require('../format-lines');
  2. const { OPTS } = require('./Checkpoints.opts.js');
  3. // TEMPLATE
  4. const header = `\
  5. pragma solidity ^0.8.19;
  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 errors = `\
  19. /**
  20. * @dev A value was attempted to be inserted on a past checkpoint.
  21. */
  22. error CheckpointUnorderedInsertion();
  23. `;
  24. const template = opts => `\
  25. struct ${opts.historyTypeName} {
  26. ${opts.checkpointTypeName}[] ${opts.checkpointFieldName};
  27. }
  28. struct ${opts.checkpointTypeName} {
  29. ${opts.keyTypeName} ${opts.keyFieldName};
  30. ${opts.valueTypeName} ${opts.valueFieldName};
  31. }
  32. /**
  33. * @dev Pushes a (\`key\`, \`value\`) pair into a ${opts.historyTypeName} so that it is stored as the checkpoint.
  34. *
  35. * Returns previous value and new value.
  36. */
  37. function push(
  38. ${opts.historyTypeName} storage self,
  39. ${opts.keyTypeName} key,
  40. ${opts.valueTypeName} value
  41. ) internal returns (${opts.valueTypeName}, ${opts.valueTypeName}) {
  42. return _insert(self.${opts.checkpointFieldName}, key, value);
  43. }
  44. /**
  45. * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if there is none.
  46. */
  47. function lowerLookup(${opts.historyTypeName} storage self, ${opts.keyTypeName} key) internal view returns (${opts.valueTypeName}) {
  48. uint256 len = self.${opts.checkpointFieldName}.length;
  49. uint256 pos = _lowerBinaryLookup(self.${opts.checkpointFieldName}, key, 0, len);
  50. return pos == len ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos).${opts.valueFieldName};
  51. }
  52. /**
  53. * @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.
  54. */
  55. function upperLookup(${opts.historyTypeName} storage self, ${opts.keyTypeName} key) internal view returns (${opts.valueTypeName}) {
  56. uint256 len = self.${opts.checkpointFieldName}.length;
  57. uint256 pos = _upperBinaryLookup(self.${opts.checkpointFieldName}, key, 0, len);
  58. return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
  59. }
  60. /**
  61. * @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.
  62. *
  63. * NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high keys).
  64. */
  65. function upperLookupRecent(${opts.historyTypeName} storage self, ${opts.keyTypeName} key) internal view returns (${opts.valueTypeName}) {
  66. uint256 len = self.${opts.checkpointFieldName}.length;
  67. uint256 low = 0;
  68. uint256 high = len;
  69. if (len > 5) {
  70. uint256 mid = len - Math.sqrt(len);
  71. if (key < _unsafeAccess(self.${opts.checkpointFieldName}, mid)._key) {
  72. high = mid;
  73. } else {
  74. low = mid + 1;
  75. }
  76. }
  77. uint256 pos = _upperBinaryLookup(self.${opts.checkpointFieldName}, key, low, high);
  78. return pos == 0 ? 0 : _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1).${opts.valueFieldName};
  79. }
  80. /**
  81. * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
  82. */
  83. function latest(${opts.historyTypeName} storage self) internal view returns (${opts.valueTypeName}) {
  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 whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value
  89. * in the most recent checkpoint.
  90. */
  91. function latestCheckpoint(${opts.historyTypeName} storage self)
  92. internal
  93. view
  94. returns (
  95. bool exists,
  96. ${opts.keyTypeName} ${opts.keyFieldName},
  97. ${opts.valueTypeName} ${opts.valueFieldName}
  98. )
  99. {
  100. uint256 pos = self.${opts.checkpointFieldName}.length;
  101. if (pos == 0) {
  102. return (false, 0, 0);
  103. } else {
  104. ${opts.checkpointTypeName} memory ckpt = _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1);
  105. return (true, ckpt.${opts.keyFieldName}, ckpt.${opts.valueFieldName});
  106. }
  107. }
  108. /**
  109. * @dev Returns the number of checkpoint.
  110. */
  111. function length(${opts.historyTypeName} storage self) internal view returns (uint256) {
  112. return self.${opts.checkpointFieldName}.length;
  113. }
  114. /**
  115. * @dev Returns checkpoint at given position.
  116. */
  117. function at(${opts.historyTypeName} storage self, uint32 pos) internal view returns (${opts.checkpointTypeName} memory) {
  118. return self.${opts.checkpointFieldName}[pos];
  119. }
  120. /**
  121. * @dev Pushes a (\`key\`, \`value\`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
  122. * or by updating the last one.
  123. */
  124. function _insert(
  125. ${opts.checkpointTypeName}[] storage self,
  126. ${opts.keyTypeName} key,
  127. ${opts.valueTypeName} value
  128. ) private returns (${opts.valueTypeName}, ${opts.valueTypeName}) {
  129. uint256 pos = self.length;
  130. if (pos > 0) {
  131. // Copying to memory is important here.
  132. ${opts.checkpointTypeName} memory last = _unsafeAccess(self, pos - 1);
  133. // Checkpoint keys must be non-decreasing.
  134. if(last.${opts.keyFieldName} > key) {
  135. revert CheckpointUnorderedInsertion();
  136. }
  137. // Update or push new checkpoint
  138. if (last.${opts.keyFieldName} == key) {
  139. _unsafeAccess(self, pos - 1).${opts.valueFieldName} = value;
  140. } else {
  141. self.push(${opts.checkpointTypeName}({${opts.keyFieldName}: key, ${opts.valueFieldName}: value}));
  142. }
  143. return (last.${opts.valueFieldName}, value);
  144. } else {
  145. self.push(${opts.checkpointTypeName}({${opts.keyFieldName}: key, ${opts.valueFieldName}: value}));
  146. return (0, value);
  147. }
  148. }
  149. /**
  150. * @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.
  151. * \`low\` and \`high\` define a section where to do the search, with inclusive \`low\` and exclusive \`high\`.
  152. *
  153. * WARNING: \`high\` should not be greater than the array's length.
  154. */
  155. function _upperBinaryLookup(
  156. ${opts.checkpointTypeName}[] storage self,
  157. ${opts.keyTypeName} key,
  158. uint256 low,
  159. uint256 high
  160. ) private view returns (uint256) {
  161. while (low < high) {
  162. uint256 mid = Math.average(low, high);
  163. if (_unsafeAccess(self, mid).${opts.keyFieldName} > key) {
  164. high = mid;
  165. } else {
  166. low = mid + 1;
  167. }
  168. }
  169. return high;
  170. }
  171. /**
  172. * @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.
  173. * \`low\` and \`high\` define a section where to do the search, with inclusive \`low\` and exclusive \`high\`.
  174. *
  175. * WARNING: \`high\` should not be greater than the array's length.
  176. */
  177. function _lowerBinaryLookup(
  178. ${opts.checkpointTypeName}[] storage self,
  179. ${opts.keyTypeName} key,
  180. uint256 low,
  181. uint256 high
  182. ) private view returns (uint256) {
  183. while (low < high) {
  184. uint256 mid = Math.average(low, high);
  185. if (_unsafeAccess(self, mid).${opts.keyFieldName} < key) {
  186. low = mid + 1;
  187. } else {
  188. high = mid;
  189. }
  190. }
  191. return high;
  192. }
  193. /**
  194. * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
  195. */
  196. function _unsafeAccess(${opts.checkpointTypeName}[] storage self, uint256 pos)
  197. private
  198. pure
  199. returns (${opts.checkpointTypeName} storage result)
  200. {
  201. assembly {
  202. mstore(0, self.slot)
  203. result.slot := add(keccak256(0, 0x20), pos)
  204. }
  205. }
  206. `;
  207. /* eslint-enable max-len */
  208. // GENERATE
  209. module.exports = format(
  210. header.trimEnd(),
  211. 'library Checkpoints {',
  212. errors,
  213. OPTS.flatMap(opts => template(opts)),
  214. '}',
  215. );