Checkpoints.js 8.2 KB

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