EnumerableMap.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. const format = require('../format-lines');
  2. const { fromBytes32, toBytes32 } = require('./conversion');
  3. const { MAP_TYPES } = require('./Enumerable.opts');
  4. const header = `\
  5. pragma solidity ^0.8.20;
  6. import {EnumerableSet} from "./EnumerableSet.sol";
  7. /**
  8. * @dev Library for managing an enumerable variant of Solidity's
  9. * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[\`mapping\`]
  10. * type.
  11. *
  12. * Maps have the following properties:
  13. *
  14. * - Entries are added, removed, and checked for existence in constant time
  15. * (O(1)).
  16. * - Entries are enumerated in O(n). No guarantees are made on the ordering.
  17. * - Map can be cleared (all entries removed) in O(n).
  18. *
  19. * \`\`\`solidity
  20. * contract Example {
  21. * // Add the library methods
  22. * using EnumerableMap for EnumerableMap.UintToAddressMap;
  23. *
  24. * // Declare a set state variable
  25. * EnumerableMap.UintToAddressMap private myMap;
  26. * }
  27. * \`\`\`
  28. *
  29. * The following map types are supported:
  30. *
  31. * - \`uint256 -> address\` (\`UintToAddressMap\`) since v3.0.0
  32. * - \`address -> uint256\` (\`AddressToUintMap\`) since v4.6.0
  33. * - \`bytes32 -> bytes32\` (\`Bytes32ToBytes32Map\`) since v4.6.0
  34. * - \`uint256 -> uint256\` (\`UintToUintMap\`) since v4.7.0
  35. * - \`bytes32 -> uint256\` (\`Bytes32ToUintMap\`) since v4.7.0
  36. * - \`uint256 -> bytes32\` (\`UintToBytes32Map\`) since v5.1.0
  37. * - \`address -> address\` (\`AddressToAddressMap\`) since v5.1.0
  38. * - \`address -> bytes32\` (\`AddressToBytes32Map\`) since v5.1.0
  39. * - \`bytes32 -> address\` (\`Bytes32ToAddressMap\`) since v5.1.0
  40. * - \`bytes -> bytes\` (\`BytesToBytesMap\`) since v5.4.0
  41. *
  42. * [WARNING]
  43. * ====
  44. * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
  45. * unusable.
  46. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
  47. *
  48. * In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
  49. * array of EnumerableMap.
  50. * ====
  51. */
  52. `;
  53. const defaultMap = `\
  54. // To implement this library for multiple types with as little code repetition as possible, we write it in
  55. // terms of a generic Map type with bytes32 keys and values. The Map implementation uses private functions,
  56. // and user-facing implementations such as \`UintToAddressMap\` are just wrappers around the underlying Map.
  57. // This means that we can only create new EnumerableMaps for types that fit in bytes32.
  58. /**
  59. * @dev Query for a nonexistent map key.
  60. */
  61. error EnumerableMapNonexistentKey(bytes32 key);
  62. struct Bytes32ToBytes32Map {
  63. // Storage of keys
  64. EnumerableSet.Bytes32Set _keys;
  65. mapping(bytes32 key => bytes32) _values;
  66. }
  67. /**
  68. * @dev Adds a key-value pair to a map, or updates the value for an existing
  69. * key. O(1).
  70. *
  71. * Returns true if the key was added to the map, that is if it was not
  72. * already present.
  73. */
  74. function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool) {
  75. map._values[key] = value;
  76. return map._keys.add(key);
  77. }
  78. /**
  79. * @dev Removes a key-value pair from a map. O(1).
  80. *
  81. * Returns true if the key was removed from the map, that is if it was present.
  82. */
  83. function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {
  84. delete map._values[key];
  85. return map._keys.remove(key);
  86. }
  87. /**
  88. * @dev Removes all the entries from a map. O(n).
  89. *
  90. * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
  91. * function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
  92. */
  93. function clear(Bytes32ToBytes32Map storage map) internal {
  94. uint256 len = length(map);
  95. for (uint256 i = 0; i < len; ++i) {
  96. delete map._values[map._keys.at(i)];
  97. }
  98. map._keys.clear();
  99. }
  100. /**
  101. * @dev Returns true if the key is in the map. O(1).
  102. */
  103. function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
  104. return map._keys.contains(key);
  105. }
  106. /**
  107. * @dev Returns the number of key-value pairs in the map. O(1).
  108. */
  109. function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
  110. return map._keys.length();
  111. }
  112. /**
  113. * @dev Returns the key-value pair stored at position \`index\` in the map. O(1).
  114. *
  115. * Note that there are no guarantees on the ordering of entries inside the
  116. * array, and it may change when more entries are added or removed.
  117. *
  118. * Requirements:
  119. *
  120. * - \`index\` must be strictly less than {length}.
  121. */
  122. function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32 key, bytes32 value) {
  123. bytes32 atKey = map._keys.at(index);
  124. return (atKey, map._values[atKey]);
  125. }
  126. /**
  127. * @dev Tries to return the value associated with \`key\`. O(1).
  128. * Does not revert if \`key\` is not in the map.
  129. */
  130. function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool exists, bytes32 value) {
  131. bytes32 val = map._values[key];
  132. if (val == bytes32(0)) {
  133. return (contains(map, key), bytes32(0));
  134. } else {
  135. return (true, val);
  136. }
  137. }
  138. /**
  139. * @dev Returns the value associated with \`key\`. O(1).
  140. *
  141. * Requirements:
  142. *
  143. * - \`key\` must be in the map.
  144. */
  145. function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
  146. bytes32 value = map._values[key];
  147. if (value == 0 && !contains(map, key)) {
  148. revert EnumerableMapNonexistentKey(key);
  149. }
  150. return value;
  151. }
  152. /**
  153. * @dev Returns an array containing all the keys
  154. *
  155. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  156. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  157. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  158. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  159. */
  160. function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) {
  161. return map._keys.values();
  162. }
  163. /**
  164. * @dev Returns an array containing a slice of the keys
  165. *
  166. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  167. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  168. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  169. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  170. */
  171. function keys(Bytes32ToBytes32Map storage map, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
  172. return map._keys.values(start, end);
  173. }
  174. `;
  175. const customMap = ({ name, key, value }) => `\
  176. // ${name}
  177. struct ${name} {
  178. Bytes32ToBytes32Map _inner;
  179. }
  180. /**
  181. * @dev Adds a key-value pair to a map, or updates the value for an existing
  182. * key. O(1).
  183. *
  184. * Returns true if the key was added to the map, that is if it was not
  185. * already present.
  186. */
  187. function set(${name} storage map, ${key.type} key, ${value.type} value) internal returns (bool) {
  188. return set(map._inner, ${toBytes32(key.type, 'key')}, ${toBytes32(value.type, 'value')});
  189. }
  190. /**
  191. * @dev Removes a value from a map. O(1).
  192. *
  193. * Returns true if the key was removed from the map, that is if it was present.
  194. */
  195. function remove(${name} storage map, ${key.type} key) internal returns (bool) {
  196. return remove(map._inner, ${toBytes32(key.type, 'key')});
  197. }
  198. /**
  199. * @dev Removes all the entries from a map. O(n).
  200. *
  201. * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that
  202. * using it may render the function uncallable if the map grows to the point where clearing it consumes too much
  203. * gas to fit in a block.
  204. */
  205. function clear(${name} storage map) internal {
  206. clear(map._inner);
  207. }
  208. /**
  209. * @dev Returns true if the key is in the map. O(1).
  210. */
  211. function contains(${name} storage map, ${key.type} key) internal view returns (bool) {
  212. return contains(map._inner, ${toBytes32(key.type, 'key')});
  213. }
  214. /**
  215. * @dev Returns the number of elements in the map. O(1).
  216. */
  217. function length(${name} storage map) internal view returns (uint256) {
  218. return length(map._inner);
  219. }
  220. /**
  221. * @dev Returns the element stored at position \`index\` in the map. O(1).
  222. * Note that there are no guarantees on the ordering of values inside the
  223. * array, and it may change when more values are added or removed.
  224. *
  225. * Requirements:
  226. *
  227. * - \`index\` must be strictly less than {length}.
  228. */
  229. function at(${name} storage map, uint256 index) internal view returns (${key.type} key, ${value.type} value) {
  230. (bytes32 atKey, bytes32 val) = at(map._inner, index);
  231. return (${fromBytes32(key.type, 'atKey')}, ${fromBytes32(value.type, 'val')});
  232. }
  233. /**
  234. * @dev Tries to return the value associated with \`key\`. O(1).
  235. * Does not revert if \`key\` is not in the map.
  236. */
  237. function tryGet(${name} storage map, ${key.type} key) internal view returns (bool exists, ${value.type} value) {
  238. (bool success, bytes32 val) = tryGet(map._inner, ${toBytes32(key.type, 'key')});
  239. return (success, ${fromBytes32(value.type, 'val')});
  240. }
  241. /**
  242. * @dev Returns the value associated with \`key\`. O(1).
  243. *
  244. * Requirements:
  245. *
  246. * - \`key\` must be in the map.
  247. */
  248. function get(${name} storage map, ${key.type} key) internal view returns (${value.type}) {
  249. return ${fromBytes32(value.type, `get(map._inner, ${toBytes32(key.type, 'key')})`)};
  250. }
  251. /**
  252. * @dev Returns an array containing all the keys
  253. *
  254. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  255. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  256. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  257. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  258. */
  259. function keys(${name} storage map) internal view returns (${key.type}[] memory) {
  260. bytes32[] memory store = keys(map._inner);
  261. ${key.type}[] memory result;
  262. assembly ("memory-safe") {
  263. result := store
  264. }
  265. return result;
  266. }
  267. /**
  268. * @dev Returns an array containing a slice of the keys
  269. *
  270. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  271. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  272. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  273. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  274. */
  275. function keys(${name} storage map, uint256 start, uint256 end) internal view returns (${key.type}[] memory) {
  276. bytes32[] memory store = keys(map._inner, start, end);
  277. ${key.type}[] memory result;
  278. assembly ("memory-safe") {
  279. result := store
  280. }
  281. return result;
  282. }
  283. `;
  284. const memoryMap = ({ name, keySet, key, value }) => `\
  285. /**
  286. * @dev Query for a nonexistent map key.
  287. */
  288. error EnumerableMapNonexistent${key.name}Key(${key.type} key);
  289. struct ${name} {
  290. // Storage of keys
  291. EnumerableSet.${keySet.name} _keys;
  292. mapping(${key.type} key => ${value.type}) _values;
  293. }
  294. /**
  295. * @dev Adds a key-value pair to a map, or updates the value for an existing
  296. * key. O(1).
  297. *
  298. * Returns true if the key was added to the map, that is if it was not
  299. * already present.
  300. */
  301. function set(${name} storage map, ${key.typeLoc} key, ${value.typeLoc} value) internal returns (bool) {
  302. map._values[key] = value;
  303. return map._keys.add(key);
  304. }
  305. /**
  306. * @dev Removes a key-value pair from a map. O(1).
  307. *
  308. * Returns true if the key was removed from the map, that is if it was present.
  309. */
  310. function remove(${name} storage map, ${key.typeLoc} key) internal returns (bool) {
  311. delete map._values[key];
  312. return map._keys.remove(key);
  313. }
  314. /**
  315. * @dev Removes all the entries from a map. O(n).
  316. *
  317. * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
  318. * function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
  319. */
  320. function clear(${name} storage map) internal {
  321. uint256 len = length(map);
  322. for (uint256 i = 0; i < len; ++i) {
  323. delete map._values[map._keys.at(i)];
  324. }
  325. map._keys.clear();
  326. }
  327. /**
  328. * @dev Returns true if the key is in the map. O(1).
  329. */
  330. function contains(${name} storage map, ${key.typeLoc} key) internal view returns (bool) {
  331. return map._keys.contains(key);
  332. }
  333. /**
  334. * @dev Returns the number of key-value pairs in the map. O(1).
  335. */
  336. function length(${name} storage map) internal view returns (uint256) {
  337. return map._keys.length();
  338. }
  339. /**
  340. * @dev Returns the key-value pair stored at position \`index\` in the map. O(1).
  341. *
  342. * Note that there are no guarantees on the ordering of entries inside the
  343. * array, and it may change when more entries are added or removed.
  344. *
  345. * Requirements:
  346. *
  347. * - \`index\` must be strictly less than {length}.
  348. */
  349. function at(
  350. ${name} storage map,
  351. uint256 index
  352. ) internal view returns (${key.typeLoc} key, ${value.typeLoc} value) {
  353. key = map._keys.at(index);
  354. value = map._values[key];
  355. }
  356. /**
  357. * @dev Tries to return the value associated with \`key\`. O(1).
  358. * Does not revert if \`key\` is not in the map.
  359. */
  360. function tryGet(
  361. ${name} storage map,
  362. ${key.typeLoc} key
  363. ) internal view returns (bool exists, ${value.typeLoc} value) {
  364. value = map._values[key];
  365. exists = ${value.memory ? 'bytes(value).length != 0' : `value != ${value.type}(0)`} || contains(map, key);
  366. }
  367. /**
  368. * @dev Returns the value associated with \`key\`. O(1).
  369. *
  370. * Requirements:
  371. *
  372. * - \`key\` must be in the map.
  373. */
  374. function get(${name} storage map, ${key.typeLoc} key) internal view returns (${value.typeLoc} value) {
  375. bool exists;
  376. (exists, value) = tryGet(map, key);
  377. if (!exists) {
  378. revert EnumerableMapNonexistent${key.name}Key(key);
  379. }
  380. }
  381. /**
  382. * @dev Returns an array containing all the keys
  383. *
  384. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  385. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  386. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  387. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  388. */
  389. function keys(${name} storage map) internal view returns (${key.type}[] memory) {
  390. return map._keys.values();
  391. }
  392. /**
  393. * @dev Returns an array containing a slice of the keys
  394. *
  395. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  396. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  397. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  398. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  399. */
  400. function keys(${name} storage map, uint256 start, uint256 end) internal view returns (${key.type}[] memory) {
  401. return map._keys.values(start, end);
  402. }
  403. `;
  404. // GENERATE
  405. module.exports = format(
  406. header.trimEnd(),
  407. 'library EnumerableMap {',
  408. format(
  409. [].concat(
  410. 'using EnumerableSet for *;',
  411. '',
  412. defaultMap,
  413. MAP_TYPES.filter(({ key, value }) => !(key.memory || value.memory)).map(customMap),
  414. MAP_TYPES.filter(({ key, value }) => key.memory || value.memory).map(memoryMap),
  415. ),
  416. ).trimEnd(),
  417. '}',
  418. );