Checkpoints.js 8.1 KB

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