Checkpoints.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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} oldValue, ${opts.valueTypeName} newValue) {
  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) internal view returns (bool exists, ${opts.keyTypeName} ${opts.keyFieldName}, ${opts.valueTypeName} ${opts.valueFieldName}) {
  96. uint256 pos = self.${opts.checkpointFieldName}.length;
  97. if (pos == 0) {
  98. return (false, 0, 0);
  99. } else {
  100. ${opts.checkpointTypeName} storage ckpt = _unsafeAccess(self.${opts.checkpointFieldName}, pos - 1);
  101. return (true, ckpt.${opts.keyFieldName}, ckpt.${opts.valueFieldName});
  102. }
  103. }
  104. /**
  105. * @dev Returns the number of checkpoints.
  106. */
  107. function length(${opts.historyTypeName} storage self) internal view returns (uint256) {
  108. return self.${opts.checkpointFieldName}.length;
  109. }
  110. /**
  111. * @dev Returns checkpoint at given position.
  112. */
  113. function at(${opts.historyTypeName} storage self, uint32 pos) internal view returns (${opts.checkpointTypeName} memory) {
  114. return self.${opts.checkpointFieldName}[pos];
  115. }
  116. /**
  117. * @dev Pushes a (\`key\`, \`value\`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
  118. * or by updating the last one.
  119. */
  120. function _insert(
  121. ${opts.checkpointTypeName}[] storage self,
  122. ${opts.keyTypeName} key,
  123. ${opts.valueTypeName} value
  124. ) private returns (${opts.valueTypeName} oldValue, ${opts.valueTypeName} newValue) {
  125. uint256 pos = self.length;
  126. if (pos > 0) {
  127. ${opts.checkpointTypeName} storage last = _unsafeAccess(self, pos - 1);
  128. ${opts.keyTypeName} lastKey = last.${opts.keyFieldName};
  129. ${opts.valueTypeName} lastValue = last.${opts.valueFieldName};
  130. // Checkpoint keys must be non-decreasing.
  131. if (lastKey > key) {
  132. revert CheckpointUnorderedInsertion();
  133. }
  134. // Update or push new checkpoint
  135. if (lastKey == key) {
  136. last.${opts.valueFieldName} = value;
  137. } else {
  138. self.push(${opts.checkpointTypeName}({${opts.keyFieldName}: key, ${opts.valueFieldName}: value}));
  139. }
  140. return (lastValue, value);
  141. } else {
  142. self.push(${opts.checkpointTypeName}({${opts.keyFieldName}: key, ${opts.valueFieldName}: value}));
  143. return (0, value);
  144. }
  145. }
  146. /**
  147. * @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or \`high\`
  148. * if there is none. \`low\` and \`high\` define a section where to do the search, with inclusive \`low\` and exclusive
  149. * \`high\`.
  150. *
  151. * WARNING: \`high\` should not be greater than the array's length.
  152. */
  153. function _upperBinaryLookup(
  154. ${opts.checkpointTypeName}[] storage self,
  155. ${opts.keyTypeName} key,
  156. uint256 low,
  157. uint256 high
  158. ) private view returns (uint256) {
  159. while (low < high) {
  160. uint256 mid = Math.average(low, high);
  161. if (_unsafeAccess(self, mid).${opts.keyFieldName} > key) {
  162. high = mid;
  163. } else {
  164. low = mid + 1;
  165. }
  166. }
  167. return high;
  168. }
  169. /**
  170. * @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or \`high\`
  171. * if there is none. \`low\` and \`high\` define a section where to do the search, with inclusive \`low\` and exclusive
  172. * \`high\`.
  173. *
  174. * WARNING: \`high\` should not be greater than the array's length.
  175. */
  176. function _lowerBinaryLookup(
  177. ${opts.checkpointTypeName}[] storage self,
  178. ${opts.keyTypeName} key,
  179. uint256 low,
  180. uint256 high
  181. ) private view returns (uint256) {
  182. while (low < high) {
  183. uint256 mid = Math.average(low, high);
  184. if (_unsafeAccess(self, mid).${opts.keyFieldName} < key) {
  185. low = mid + 1;
  186. } else {
  187. high = mid;
  188. }
  189. }
  190. return high;
  191. }
  192. /**
  193. * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
  194. */
  195. function _unsafeAccess(
  196. ${opts.checkpointTypeName}[] storage self,
  197. uint256 pos
  198. ) private pure returns (${opts.checkpointTypeName} storage result) {
  199. assembly {
  200. mstore(0, self.slot)
  201. result.slot := add(keccak256(0, 0x20), pos)
  202. }
  203. }
  204. `;
  205. // GENERATE
  206. module.exports = format(
  207. header.trimEnd(),
  208. 'library Checkpoints {',
  209. format(
  210. [].concat(
  211. errors,
  212. OPTS.map(opts => template(opts)),
  213. ),
  214. ).trimEnd(),
  215. '}',
  216. );