EnumerableMap.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. const format = require('../format-lines');
  2. const { fromBytes32, toBytes32 } = require('./conversion');
  3. const TYPES = [
  4. { name: 'UintToUintMap', keyType: 'uint256', valueType: 'uint256' },
  5. { name: 'UintToAddressMap', keyType: 'uint256', valueType: 'address' },
  6. { name: 'AddressToUintMap', keyType: 'address', valueType: 'uint256' },
  7. { name: 'Bytes32ToUintMap', keyType: 'bytes32', valueType: 'uint256' },
  8. ];
  9. /* eslint-disable max-len */
  10. const header = `\
  11. pragma solidity ^0.8.0;
  12. import "./EnumerableSet.sol";
  13. /**
  14. * @dev Library for managing an enumerable variant of Solidity's
  15. * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[\`mapping\`]
  16. * type.
  17. *
  18. * Maps have the following properties:
  19. *
  20. * - Entries are added, removed, and checked for existence in constant time
  21. * (O(1)).
  22. * - Entries are enumerated in O(n). No guarantees are made on the ordering.
  23. *
  24. * \`\`\`
  25. * contract Example {
  26. * // Add the library methods
  27. * using EnumerableMap for EnumerableMap.UintToAddressMap;
  28. *
  29. * // Declare a set state variable
  30. * EnumerableMap.UintToAddressMap private myMap;
  31. * }
  32. * \`\`\`
  33. *
  34. * The following map types are supported:
  35. *
  36. * - \`uint256 -> address\` (\`UintToAddressMap\`) since v3.0.0
  37. * - \`address -> uint256\` (\`AddressToUintMap\`) since v4.6.0
  38. * - \`bytes32 -> bytes32\` (\`Bytes32ToBytes32Map\`) since v4.6.0
  39. * - \`uint256 -> uint256\` (\`UintToUintMap\`) since v4.7.0
  40. * - \`bytes32 -> uint256\` (\`Bytes32ToUintMap\`) since v4.7.0
  41. *
  42. * [WARNING]
  43. * ====
  44. * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.
  45. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
  46. *
  47. * In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an array of EnumerableMap.
  48. * ====
  49. */
  50. `;
  51. /* eslint-enable max-len */
  52. const defaultMap = () => `\
  53. // To implement this library for multiple types with as little code
  54. // repetition as possible, we write it in terms of a generic Map type with
  55. // bytes32 keys and values.
  56. // The Map implementation uses private functions, and user-facing
  57. // implementations (such as Uint256ToAddressMap) are just wrappers around
  58. // the underlying Map.
  59. // This means that we can only create new EnumerableMaps for types that fit
  60. // in bytes32.
  61. struct Bytes32ToBytes32Map {
  62. // Storage of keys
  63. EnumerableSet.Bytes32Set _keys;
  64. mapping(bytes32 => bytes32) _values;
  65. }
  66. /**
  67. * @dev Adds a key-value pair to a map, or updates the value for an existing
  68. * key. O(1).
  69. *
  70. * Returns true if the key was added to the map, that is if it was not
  71. * already present.
  72. */
  73. function set(
  74. Bytes32ToBytes32Map storage map,
  75. bytes32 key,
  76. bytes32 value
  77. ) internal returns (bool) {
  78. map._values[key] = value;
  79. return map._keys.add(key);
  80. }
  81. /**
  82. * @dev Removes a key-value pair from a map. O(1).
  83. *
  84. * Returns true if the key was removed from the map, that is if it was present.
  85. */
  86. function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {
  87. delete map._values[key];
  88. return map._keys.remove(key);
  89. }
  90. /**
  91. * @dev Returns true if the key is in the map. O(1).
  92. */
  93. function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
  94. return map._keys.contains(key);
  95. }
  96. /**
  97. * @dev Returns the number of key-value pairs in the map. O(1).
  98. */
  99. function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
  100. return map._keys.length();
  101. }
  102. /**
  103. * @dev Returns the key-value pair stored at position \`index\` in the map. O(1).
  104. *
  105. * Note that there are no guarantees on the ordering of entries inside the
  106. * array, and it may change when more entries are added or removed.
  107. *
  108. * Requirements:
  109. *
  110. * - \`index\` must be strictly less than {length}.
  111. */
  112. function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
  113. bytes32 key = map._keys.at(index);
  114. return (key, map._values[key]);
  115. }
  116. /**
  117. * @dev Tries to returns the value associated with \`key\`. O(1).
  118. * Does not revert if \`key\` is not in the map.
  119. */
  120. function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool, bytes32) {
  121. bytes32 value = map._values[key];
  122. if (value == bytes32(0)) {
  123. return (contains(map, key), bytes32(0));
  124. } else {
  125. return (true, value);
  126. }
  127. }
  128. /**
  129. * @dev Returns the value associated with \`key\`. O(1).
  130. *
  131. * Requirements:
  132. *
  133. * - \`key\` must be in the map.
  134. */
  135. function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
  136. bytes32 value = map._values[key];
  137. require(value != 0 || contains(map, key), "EnumerableMap: nonexistent key");
  138. return value;
  139. }
  140. /**
  141. * @dev Same as {_get}, with a custom error message when \`key\` is not in the map.
  142. *
  143. * CAUTION: This function is deprecated because it requires allocating memory for the error
  144. * message unnecessarily. For custom revert reasons use {_tryGet}.
  145. */
  146. function get(
  147. Bytes32ToBytes32Map storage map,
  148. bytes32 key,
  149. string memory errorMessage
  150. ) internal view returns (bytes32) {
  151. bytes32 value = map._values[key];
  152. require(value != 0 || contains(map, key), errorMessage);
  153. return value;
  154. }
  155. `;
  156. const customMap = ({ name, keyType, valueType }) => `\
  157. // ${name}
  158. struct ${name} {
  159. Bytes32ToBytes32Map _inner;
  160. }
  161. /**
  162. * @dev Adds a key-value pair to a map, or updates the value for an existing
  163. * key. O(1).
  164. *
  165. * Returns true if the key was added to the map, that is if it was not
  166. * already present.
  167. */
  168. function set(
  169. ${name} storage map,
  170. ${keyType} key,
  171. ${valueType} value
  172. ) internal returns (bool) {
  173. return set(map._inner, ${toBytes32(keyType, 'key')}, ${toBytes32(valueType, 'value')});
  174. }
  175. /**
  176. * @dev Removes a value from a set. O(1).
  177. *
  178. * Returns true if the key was removed from the map, that is if it was present.
  179. */
  180. function remove(${name} storage map, ${keyType} key) internal returns (bool) {
  181. return remove(map._inner, ${toBytes32(keyType, 'key')});
  182. }
  183. /**
  184. * @dev Returns true if the key is in the map. O(1).
  185. */
  186. function contains(${name} storage map, ${keyType} key) internal view returns (bool) {
  187. return contains(map._inner, ${toBytes32(keyType, 'key')});
  188. }
  189. /**
  190. * @dev Returns the number of elements in the map. O(1).
  191. */
  192. function length(${name} storage map) internal view returns (uint256) {
  193. return length(map._inner);
  194. }
  195. /**
  196. * @dev Returns the element stored at position \`index\` in the set. O(1).
  197. * Note that there are no guarantees on the ordering of values inside the
  198. * array, and it may change when more values are added or removed.
  199. *
  200. * Requirements:
  201. *
  202. * - \`index\` must be strictly less than {length}.
  203. */
  204. function at(${name} storage map, uint256 index) internal view returns (${keyType}, ${valueType}) {
  205. (bytes32 key, bytes32 value) = at(map._inner, index);
  206. return (${fromBytes32(keyType, 'key')}, ${fromBytes32(valueType, 'value')});
  207. }
  208. /**
  209. * @dev Tries to returns the value associated with \`key\`. O(1).
  210. * Does not revert if \`key\` is not in the map.
  211. */
  212. function tryGet(${name} storage map, ${keyType} key) internal view returns (bool, ${valueType}) {
  213. (bool success, bytes32 value) = tryGet(map._inner, ${toBytes32(keyType, 'key')});
  214. return (success, ${fromBytes32(valueType, 'value')});
  215. }
  216. /**
  217. * @dev Returns the value associated with \`key\`. O(1).
  218. *
  219. * Requirements:
  220. *
  221. * - \`key\` must be in the map.
  222. */
  223. function get(${name} storage map, ${keyType} key) internal view returns (${valueType}) {
  224. return ${fromBytes32(valueType, `get(map._inner, ${toBytes32(keyType, 'key')})`)};
  225. }
  226. /**
  227. * @dev Same as {get}, with a custom error message when \`key\` is not in the map.
  228. *
  229. * CAUTION: This function is deprecated because it requires allocating memory for the error
  230. * message unnecessarily. For custom revert reasons use {tryGet}.
  231. */
  232. function get(
  233. ${name} storage map,
  234. ${keyType} key,
  235. string memory errorMessage
  236. ) internal view returns (${valueType}) {
  237. return ${fromBytes32(valueType, `get(map._inner, ${toBytes32(keyType, 'key')}, errorMessage)`)};
  238. }
  239. `;
  240. // GENERATE
  241. module.exports = format(
  242. header.trimEnd(),
  243. 'library EnumerableMap {',
  244. [
  245. 'using EnumerableSet for EnumerableSet.Bytes32Set;',
  246. '',
  247. defaultMap(),
  248. TYPES.map(details => customMap(details).trimEnd()).join('\n\n'),
  249. ],
  250. '}',
  251. );