Checkpoints.js 7.8 KB

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