EnumerableSet.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. const format = require('../format-lines');
  2. const { fromBytes32, toBytes32 } = require('./conversion');
  3. const { TYPES } = require('./EnumerableSet.opts');
  4. const header = `\
  5. pragma solidity ^0.8.20;
  6. import {Hashes} from "../cryptography/Hashes.sol";
  7. /**
  8. * @dev Library for managing
  9. * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
  10. * types.
  11. *
  12. * Sets have the following properties:
  13. *
  14. * - Elements are added, removed, and checked for existence in constant time
  15. * (O(1)).
  16. * - Elements are enumerated in O(n). No guarantees are made on the ordering.
  17. *
  18. * \`\`\`solidity
  19. * contract Example {
  20. * // Add the library methods
  21. * using EnumerableSet for EnumerableSet.AddressSet;
  22. *
  23. * // Declare a set state variable
  24. * EnumerableSet.AddressSet private mySet;
  25. * }
  26. * \`\`\`
  27. *
  28. * As of v3.3.0, sets of type \`bytes32\` (\`Bytes32Set\`), \`address\` (\`AddressSet\`)
  29. * and \`uint256\` (\`UintSet\`) are supported.
  30. *
  31. * [WARNING]
  32. * ====
  33. * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
  34. * unusable.
  35. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
  36. *
  37. * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
  38. * array of EnumerableSet.
  39. * ====
  40. */
  41. `;
  42. const defaultSet = `\
  43. // To implement this library for multiple types with as little code
  44. // repetition as possible, we write it in terms of a generic Set type with
  45. // bytes32 values.
  46. // The Set implementation uses private functions, and user-facing
  47. // implementations (such as AddressSet) are just wrappers around the
  48. // underlying Set.
  49. // This means that we can only create new EnumerableSets for types that fit
  50. // in bytes32.
  51. struct Set {
  52. // Storage of set values
  53. bytes32[] _values;
  54. // Position is the index of the value in the \`values\` array plus 1.
  55. // Position 0 is used to mean a value is not in the set.
  56. mapping(bytes32 value => uint256) _positions;
  57. }
  58. /**
  59. * @dev Add a value to a set. O(1).
  60. *
  61. * Returns true if the value was added to the set, that is if it was not
  62. * already present.
  63. */
  64. function _add(Set storage set, bytes32 value) private returns (bool) {
  65. if (!_contains(set, value)) {
  66. set._values.push(value);
  67. // The value is stored at length-1, but we add 1 to all indexes
  68. // and use 0 as a sentinel value
  69. set._positions[value] = set._values.length;
  70. return true;
  71. } else {
  72. return false;
  73. }
  74. }
  75. /**
  76. * @dev Removes a value from a set. O(1).
  77. *
  78. * Returns true if the value was removed from the set, that is if it was
  79. * present.
  80. */
  81. function _remove(Set storage set, bytes32 value) private returns (bool) {
  82. // We cache the value's position to prevent multiple reads from the same storage slot
  83. uint256 position = set._positions[value];
  84. if (position != 0) {
  85. // Equivalent to contains(set, value)
  86. // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
  87. // the array, and then remove the last element (sometimes called as 'swap and pop').
  88. // This modifies the order of the array, as noted in {at}.
  89. uint256 valueIndex = position - 1;
  90. uint256 lastIndex = set._values.length - 1;
  91. if (valueIndex != lastIndex) {
  92. bytes32 lastValue = set._values[lastIndex];
  93. // Move the lastValue to the index where the value to delete is
  94. set._values[valueIndex] = lastValue;
  95. // Update the tracked position of the lastValue (that was just moved)
  96. set._positions[lastValue] = position;
  97. }
  98. // Delete the slot where the moved value was stored
  99. set._values.pop();
  100. // Delete the tracked position for the deleted slot
  101. delete set._positions[value];
  102. return true;
  103. } else {
  104. return false;
  105. }
  106. }
  107. /**
  108. * @dev Returns true if the value is in the set. O(1).
  109. */
  110. function _contains(Set storage set, bytes32 value) private view returns (bool) {
  111. return set._positions[value] != 0;
  112. }
  113. /**
  114. * @dev Returns the number of values on the set. O(1).
  115. */
  116. function _length(Set storage set) private view returns (uint256) {
  117. return set._values.length;
  118. }
  119. /**
  120. * @dev Returns the value stored at position \`index\` in the set. O(1).
  121. *
  122. * Note that there are no guarantees on the ordering of values inside the
  123. * array, and it may change when more values are added or removed.
  124. *
  125. * Requirements:
  126. *
  127. * - \`index\` must be strictly less than {length}.
  128. */
  129. function _at(Set storage set, uint256 index) private view returns (bytes32) {
  130. return set._values[index];
  131. }
  132. /**
  133. * @dev Return the entire set in an array
  134. *
  135. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  136. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  137. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  138. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  139. */
  140. function _values(Set storage set) private view returns (bytes32[] memory) {
  141. return set._values;
  142. }
  143. `;
  144. const customSet = ({ name, type }) => `\
  145. // ${name}
  146. struct ${name} {
  147. Set _inner;
  148. }
  149. /**
  150. * @dev Add a value to a set. O(1).
  151. *
  152. * Returns true if the value was added to the set, that is if it was not
  153. * already present.
  154. */
  155. function add(${name} storage set, ${type} value) internal returns (bool) {
  156. return _add(set._inner, ${toBytes32(type, 'value')});
  157. }
  158. /**
  159. * @dev Removes a value from a set. O(1).
  160. *
  161. * Returns true if the value was removed from the set, that is if it was
  162. * present.
  163. */
  164. function remove(${name} storage set, ${type} value) internal returns (bool) {
  165. return _remove(set._inner, ${toBytes32(type, 'value')});
  166. }
  167. /**
  168. * @dev Returns true if the value is in the set. O(1).
  169. */
  170. function contains(${name} storage set, ${type} value) internal view returns (bool) {
  171. return _contains(set._inner, ${toBytes32(type, 'value')});
  172. }
  173. /**
  174. * @dev Returns the number of values in the set. O(1).
  175. */
  176. function length(${name} storage set) internal view returns (uint256) {
  177. return _length(set._inner);
  178. }
  179. /**
  180. * @dev Returns the value stored at position \`index\` in the set. O(1).
  181. *
  182. * Note that there are no guarantees on the ordering of values inside the
  183. * array, and it may change when more values are added or removed.
  184. *
  185. * Requirements:
  186. *
  187. * - \`index\` must be strictly less than {length}.
  188. */
  189. function at(${name} storage set, uint256 index) internal view returns (${type}) {
  190. return ${fromBytes32(type, '_at(set._inner, index)')};
  191. }
  192. /**
  193. * @dev Return the entire set in an array
  194. *
  195. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  196. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  197. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  198. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  199. */
  200. function values(${name} storage set) internal view returns (${type}[] memory) {
  201. bytes32[] memory store = _values(set._inner);
  202. ${type}[] memory result;
  203. assembly ("memory-safe") {
  204. result := store
  205. }
  206. return result;
  207. }
  208. `;
  209. const memorySet = ({ name, type }) => `\
  210. struct ${name} {
  211. // Storage of set values
  212. ${type}[] _values;
  213. // Position is the index of the value in the \`values\` array plus 1.
  214. // Position 0 is used to mean a value is not in the self.
  215. mapping(bytes32 valueHash => uint256) _positions;
  216. }
  217. /**
  218. * @dev Add a value to a self. O(1).
  219. *
  220. * Returns true if the value was added to the set, that is if it was not
  221. * already present.
  222. */
  223. function add(${name} storage self, ${type} memory value) internal returns (bool) {
  224. if (!contains(self, value)) {
  225. self._values.push(value);
  226. // The value is stored at length-1, but we add 1 to all indexes
  227. // and use 0 as a sentinel value
  228. self._positions[_hash(value)] = self._values.length;
  229. return true;
  230. } else {
  231. return false;
  232. }
  233. }
  234. /**
  235. * @dev Removes a value from a self. O(1).
  236. *
  237. * Returns true if the value was removed from the set, that is if it was
  238. * present.
  239. */
  240. function remove(${name} storage self, ${type} memory value) internal returns (bool) {
  241. // We cache the value's position to prevent multiple reads from the same storage slot
  242. bytes32 valueHash = _hash(value);
  243. uint256 position = self._positions[valueHash];
  244. if (position != 0) {
  245. // Equivalent to contains(self, value)
  246. // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
  247. // the array, and then remove the last element (sometimes called as 'swap and pop').
  248. // This modifies the order of the array, as noted in {at}.
  249. uint256 valueIndex = position - 1;
  250. uint256 lastIndex = self._values.length - 1;
  251. if (valueIndex != lastIndex) {
  252. ${type} memory lastValue = self._values[lastIndex];
  253. // Move the lastValue to the index where the value to delete is
  254. self._values[valueIndex] = lastValue;
  255. // Update the tracked position of the lastValue (that was just moved)
  256. self._positions[_hash(lastValue)] = position;
  257. }
  258. // Delete the slot where the moved value was stored
  259. self._values.pop();
  260. // Delete the tracked position for the deleted slot
  261. delete self._positions[valueHash];
  262. return true;
  263. } else {
  264. return false;
  265. }
  266. }
  267. /**
  268. * @dev Returns true if the value is in the self. O(1).
  269. */
  270. function contains(${name} storage self, ${type} memory value) internal view returns (bool) {
  271. return self._positions[_hash(value)] != 0;
  272. }
  273. /**
  274. * @dev Returns the number of values on the self. O(1).
  275. */
  276. function length(${name} storage self) internal view returns (uint256) {
  277. return self._values.length;
  278. }
  279. /**
  280. * @dev Returns the value stored at position \`index\` in the self. O(1).
  281. *
  282. * Note that there are no guarantees on the ordering of values inside the
  283. * array, and it may change when more values are added or removed.
  284. *
  285. * Requirements:
  286. *
  287. * - \`index\` must be strictly less than {length}.
  288. */
  289. function at(${name} storage self, uint256 index) internal view returns (${type} memory) {
  290. return self._values[index];
  291. }
  292. /**
  293. * @dev Return the entire set in an array
  294. *
  295. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  296. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  297. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  298. * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
  299. */
  300. function values(${name} storage self) internal view returns (${type}[] memory) {
  301. return self._values;
  302. }
  303. `;
  304. const hashes = `\
  305. function _hash(bytes32[2] memory value) private pure returns (bytes32) {
  306. return Hashes.efficientKeccak256(value[0], value[1]);
  307. }
  308. `;
  309. // GENERATE
  310. module.exports = format(
  311. header.trimEnd(),
  312. 'library EnumerableSet {',
  313. format(
  314. [].concat(
  315. defaultSet,
  316. TYPES.filter(({ size }) => size == undefined).map(details => customSet(details)),
  317. TYPES.filter(({ size }) => size != undefined).map(details => memorySet(details)),
  318. hashes,
  319. ),
  320. ).trimEnd(),
  321. '}',
  322. );