EnumerableMap.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. const format = require('../format-lines');
  2. const { fromBytes32, toBytes32 } = require('./conversion');
  3. const { TYPES } = require('./EnumerableMap.opts');
  4. /* eslint-disable max-len */
  5. const header = `\
  6. pragma solidity ^0.8.20;
  7. import {EnumerableSet} from "./EnumerableSet.sol";
  8. /**
  9. * @dev Library for managing an enumerable variant of Solidity's
  10. * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[\`mapping\`]
  11. * type.
  12. *
  13. * Maps have the following properties:
  14. *
  15. * - Entries are added, removed, and checked for existence in constant time
  16. * (O(1)).
  17. * - Entries are enumerated in O(n). No guarantees are made on the ordering.
  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. *
  37. * [WARNING]
  38. * ====
  39. * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
  40. * unusable.
  41. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
  42. *
  43. * In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
  44. * array of EnumerableMap.
  45. * ====
  46. */
  47. `;
  48. /* eslint-enable max-len */
  49. const defaultMap = () => `\
  50. // To implement this library for multiple types with as little code repetition as possible, we write it in
  51. // terms of a generic Map type with bytes32 keys and values. The Map implementation uses private functions,
  52. // and user-facing implementations such as \`UintToAddressMap\` are just wrappers around the underlying Map.
  53. // This means that we can only create new EnumerableMaps for types that fit in bytes32.
  54. /**
  55. * @dev Query for a nonexistent map key.
  56. */
  57. error EnumerableMapNonexistentKey(bytes32 key);
  58. struct Bytes32ToBytes32Map {
  59. // Storage of keys
  60. EnumerableSet.Bytes32Set _keys;
  61. mapping(bytes32 key => bytes32) _values;
  62. }
  63. /**
  64. * @dev Adds a key-value pair to a map, or updates the value for an existing
  65. * key. O(1).
  66. *
  67. * Returns true if the key was added to the map, that is if it was not
  68. * already present.
  69. */
  70. function set(
  71. Bytes32ToBytes32Map storage map,
  72. bytes32 key,
  73. bytes32 value
  74. ) 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 Returns true if the key is in the map. O(1).
  89. */
  90. function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
  91. return map._keys.contains(key);
  92. }
  93. /**
  94. * @dev Returns the number of key-value pairs in the map. O(1).
  95. */
  96. function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
  97. return map._keys.length();
  98. }
  99. /**
  100. * @dev Returns the key-value pair stored at position \`index\` in the map. O(1).
  101. *
  102. * Note that there are no guarantees on the ordering of entries inside the
  103. * array, and it may change when more entries are added or removed.
  104. *
  105. * Requirements:
  106. *
  107. * - \`index\` must be strictly less than {length}.
  108. */
  109. function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
  110. bytes32 key = map._keys.at(index);
  111. return (key, map._values[key]);
  112. }
  113. /**
  114. * @dev Tries to returns the value associated with \`key\`. O(1).
  115. * Does not revert if \`key\` is not in the map.
  116. */
  117. function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool, bytes32) {
  118. bytes32 value = map._values[key];
  119. if (value == bytes32(0)) {
  120. return (contains(map, key), bytes32(0));
  121. } else {
  122. return (true, value);
  123. }
  124. }
  125. /**
  126. * @dev Returns the value associated with \`key\`. O(1).
  127. *
  128. * Requirements:
  129. *
  130. * - \`key\` must be in the map.
  131. */
  132. function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
  133. bytes32 value = map._values[key];
  134. if(value == 0 && !contains(map, key)) {
  135. revert EnumerableMapNonexistentKey(key);
  136. }
  137. return value;
  138. }
  139. /**
  140. * @dev Return the an array containing all the keys
  141. *
  142. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  143. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  144. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  145. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  146. */
  147. function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) {
  148. return map._keys.values();
  149. }
  150. `;
  151. const customMap = ({ name, keyType, valueType }) => `\
  152. // ${name}
  153. struct ${name} {
  154. Bytes32ToBytes32Map _inner;
  155. }
  156. /**
  157. * @dev Adds a key-value pair to a map, or updates the value for an existing
  158. * key. O(1).
  159. *
  160. * Returns true if the key was added to the map, that is if it was not
  161. * already present.
  162. */
  163. function set(
  164. ${name} storage map,
  165. ${keyType} key,
  166. ${valueType} value
  167. ) internal returns (bool) {
  168. return set(map._inner, ${toBytes32(keyType, 'key')}, ${toBytes32(valueType, 'value')});
  169. }
  170. /**
  171. * @dev Removes a value from a map. O(1).
  172. *
  173. * Returns true if the key was removed from the map, that is if it was present.
  174. */
  175. function remove(${name} storage map, ${keyType} key) internal returns (bool) {
  176. return remove(map._inner, ${toBytes32(keyType, 'key')});
  177. }
  178. /**
  179. * @dev Returns true if the key is in the map. O(1).
  180. */
  181. function contains(${name} storage map, ${keyType} key) internal view returns (bool) {
  182. return contains(map._inner, ${toBytes32(keyType, 'key')});
  183. }
  184. /**
  185. * @dev Returns the number of elements in the map. O(1).
  186. */
  187. function length(${name} storage map) internal view returns (uint256) {
  188. return length(map._inner);
  189. }
  190. /**
  191. * @dev Returns the element stored at position \`index\` in the map. O(1).
  192. * Note that there are no guarantees on the ordering of values inside the
  193. * array, and it may change when more values are added or removed.
  194. *
  195. * Requirements:
  196. *
  197. * - \`index\` must be strictly less than {length}.
  198. */
  199. function at(${name} storage map, uint256 index) internal view returns (${keyType}, ${valueType}) {
  200. (bytes32 key, bytes32 value) = at(map._inner, index);
  201. return (${fromBytes32(keyType, 'key')}, ${fromBytes32(valueType, 'value')});
  202. }
  203. /**
  204. * @dev Tries to returns the value associated with \`key\`. O(1).
  205. * Does not revert if \`key\` is not in the map.
  206. */
  207. function tryGet(${name} storage map, ${keyType} key) internal view returns (bool, ${valueType}) {
  208. (bool success, bytes32 value) = tryGet(map._inner, ${toBytes32(keyType, 'key')});
  209. return (success, ${fromBytes32(valueType, 'value')});
  210. }
  211. /**
  212. * @dev Returns the value associated with \`key\`. O(1).
  213. *
  214. * Requirements:
  215. *
  216. * - \`key\` must be in the map.
  217. */
  218. function get(${name} storage map, ${keyType} key) internal view returns (${valueType}) {
  219. return ${fromBytes32(valueType, `get(map._inner, ${toBytes32(keyType, 'key')})`)};
  220. }
  221. /**
  222. * @dev Return the an array containing all the keys
  223. *
  224. * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
  225. * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
  226. * this function has an unbounded cost, and using it as part of a state-changing function may render the function
  227. * uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
  228. */
  229. function keys(${name} storage map) internal view returns (${keyType}[] memory) {
  230. bytes32[] memory store = keys(map._inner);
  231. ${keyType}[] memory result;
  232. /// @solidity memory-safe-assembly
  233. assembly {
  234. result := store
  235. }
  236. return result;
  237. }
  238. `;
  239. // GENERATE
  240. module.exports = format(
  241. header.trimEnd(),
  242. 'library EnumerableMap {',
  243. [
  244. 'using EnumerableSet for EnumerableSet.Bytes32Set;',
  245. '',
  246. defaultMap(),
  247. TYPES.map(details => customMap(details).trimEnd()).join('\n\n'),
  248. ],
  249. '}',
  250. );