EnumerableMap.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 returns 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: Developers should keep in mind that this function has an unbounded cost and using it may render the
  202. * function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
  203. */
  204. function clear(${name} storage map) internal {
  205. clear(map._inner);
  206. }
  207. /**
  208. * @dev Returns true if the key is in the map. O(1).
  209. */
  210. function contains(${name} storage map, ${key.type} key) internal view returns (bool) {
  211. return contains(map._inner, ${toBytes32(key.type, 'key')});
  212. }
  213. /**
  214. * @dev Returns the number of elements in the map. O(1).
  215. */
  216. function length(${name} storage map) internal view returns (uint256) {
  217. return length(map._inner);
  218. }
  219. /**
  220. * @dev Returns the element stored at position \`index\` in the map. O(1).
  221. * Note that there are no guarantees on the ordering of values inside the
  222. * array, and it may change when more values are added or removed.
  223. *
  224. * Requirements:
  225. *
  226. * - \`index\` must be strictly less than {length}.
  227. */
  228. function at(${name} storage map, uint256 index) internal view returns (${key.type} key, ${value.type} value) {
  229. (bytes32 atKey, bytes32 val) = at(map._inner, index);
  230. return (${fromBytes32(key.type, 'atKey')}, ${fromBytes32(value.type, 'val')});
  231. }
  232. /**
  233. * @dev Tries to returns the value associated with \`key\`. O(1).
  234. * Does not revert if \`key\` is not in the map.
  235. */
  236. function tryGet(${name} storage map, ${key.type} key) internal view returns (bool exists, ${value.type} value) {
  237. (bool success, bytes32 val) = tryGet(map._inner, ${toBytes32(key.type, 'key')});
  238. return (success, ${fromBytes32(value.type, 'val')});
  239. }
  240. /**
  241. * @dev Returns the value associated with \`key\`. O(1).
  242. *
  243. * Requirements:
  244. *
  245. * - \`key\` must be in the map.
  246. */
  247. function get(${name} storage map, ${key.type} key) internal view returns (${value.type}) {
  248. return ${fromBytes32(value.type, `get(map._inner, ${toBytes32(key.type, 'key')})`)};
  249. }
  250. /**
  251. * @dev Return the an array containing all the keys
  252. *
  253. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  254. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  255. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  256. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  257. */
  258. function keys(${name} storage map) internal view returns (${key.type}[] memory) {
  259. bytes32[] memory store = keys(map._inner);
  260. ${key.type}[] memory result;
  261. assembly ("memory-safe") {
  262. result := store
  263. }
  264. return result;
  265. }
  266. /**
  267. * @dev Return the an array containing a slice of the keys
  268. *
  269. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  270. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  271. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  272. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  273. */
  274. function keys(${name} storage map, uint256 start, uint256 end) internal view returns (${key.type}[] memory) {
  275. bytes32[] memory store = keys(map._inner, start, end);
  276. ${key.type}[] memory result;
  277. assembly ("memory-safe") {
  278. result := store
  279. }
  280. return result;
  281. }
  282. `;
  283. const memoryMap = ({ name, keySet, key, value }) => `\
  284. /**
  285. * @dev Query for a nonexistent map key.
  286. */
  287. error EnumerableMapNonexistent${key.name}Key(${key.type} key);
  288. struct ${name} {
  289. // Storage of keys
  290. EnumerableSet.${keySet.name} _keys;
  291. mapping(${key.type} key => ${value.type}) _values;
  292. }
  293. /**
  294. * @dev Adds a key-value pair to a map, or updates the value for an existing
  295. * key. O(1).
  296. *
  297. * Returns true if the key was added to the map, that is if it was not
  298. * already present.
  299. */
  300. function set(${name} storage map, ${key.typeLoc} key, ${value.typeLoc} value) internal returns (bool) {
  301. map._values[key] = value;
  302. return map._keys.add(key);
  303. }
  304. /**
  305. * @dev Removes a key-value pair from a map. O(1).
  306. *
  307. * Returns true if the key was removed from the map, that is if it was present.
  308. */
  309. function remove(${name} storage map, ${key.typeLoc} key) internal returns (bool) {
  310. delete map._values[key];
  311. return map._keys.remove(key);
  312. }
  313. /**
  314. * @dev Removes all the entries from a map. O(n).
  315. *
  316. * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
  317. * function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
  318. */
  319. function clear(${name} storage map) internal {
  320. uint256 len = length(map);
  321. for (uint256 i = 0; i < len; ++i) {
  322. delete map._values[map._keys.at(i)];
  323. }
  324. map._keys.clear();
  325. }
  326. /**
  327. * @dev Returns true if the key is in the map. O(1).
  328. */
  329. function contains(${name} storage map, ${key.typeLoc} key) internal view returns (bool) {
  330. return map._keys.contains(key);
  331. }
  332. /**
  333. * @dev Returns the number of key-value pairs in the map. O(1).
  334. */
  335. function length(${name} storage map) internal view returns (uint256) {
  336. return map._keys.length();
  337. }
  338. /**
  339. * @dev Returns the key-value pair stored at position \`index\` in the map. O(1).
  340. *
  341. * Note that there are no guarantees on the ordering of entries inside the
  342. * array, and it may change when more entries are added or removed.
  343. *
  344. * Requirements:
  345. *
  346. * - \`index\` must be strictly less than {length}.
  347. */
  348. function at(
  349. ${name} storage map,
  350. uint256 index
  351. ) internal view returns (${key.typeLoc} key, ${value.typeLoc} value) {
  352. key = map._keys.at(index);
  353. value = map._values[key];
  354. }
  355. /**
  356. * @dev Tries to returns the value associated with \`key\`. O(1).
  357. * Does not revert if \`key\` is not in the map.
  358. */
  359. function tryGet(
  360. ${name} storage map,
  361. ${key.typeLoc} key
  362. ) internal view returns (bool exists, ${value.typeLoc} value) {
  363. value = map._values[key];
  364. exists = ${value.memory ? 'bytes(value).length != 0' : `value != ${value.type}(0)`} || contains(map, key);
  365. }
  366. /**
  367. * @dev Returns the value associated with \`key\`. O(1).
  368. *
  369. * Requirements:
  370. *
  371. * - \`key\` must be in the map.
  372. */
  373. function get(${name} storage map, ${key.typeLoc} key) internal view returns (${value.typeLoc} value) {
  374. bool exists;
  375. (exists, value) = tryGet(map, key);
  376. if (!exists) {
  377. revert EnumerableMapNonexistent${key.name}Key(key);
  378. }
  379. }
  380. /**
  381. * @dev Returns an array containing all the keys
  382. *
  383. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  384. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  385. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  386. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  387. */
  388. function keys(${name} storage map) internal view returns (${key.type}[] memory) {
  389. return map._keys.values();
  390. }
  391. /**
  392. * @dev Returns an array containing a slice of the keys
  393. *
  394. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  395. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  396. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  397. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  398. */
  399. function keys(${name} storage map, uint256 start, uint256 end) internal view returns (${key.type}[] memory) {
  400. return map._keys.values(start, end);
  401. }
  402. `;
  403. // GENERATE
  404. module.exports = format(
  405. header.trimEnd(),
  406. 'library EnumerableMap {',
  407. format(
  408. [].concat(
  409. 'using EnumerableSet for *;',
  410. '',
  411. defaultMap,
  412. MAP_TYPES.filter(({ key, value }) => !(key.memory || value.memory)).map(customMap),
  413. MAP_TYPES.filter(({ key, value }) => key.memory || value.memory).map(memoryMap),
  414. ),
  415. ).trimEnd(),
  416. '}',
  417. );