AccessControlEnumerable.sol 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. import "./AccessControl.sol";
  4. import "../utils/structs/EnumerableSet.sol";
  5. /**
  6. * @dev Extension of {AccessControl} that allows enumerating the members of each role.
  7. */
  8. abstract contract AccessControlEnumerable is AccessControl {
  9. using EnumerableSet for EnumerableSet.AddressSet;
  10. mapping (bytes32 => EnumerableSet.AddressSet) private _roleMembers;
  11. /**
  12. * @dev Returns one of the accounts that have `role`. `index` must be a
  13. * value between 0 and {getRoleMemberCount}, non-inclusive.
  14. *
  15. * Role bearers are not sorted in any particular way, and their ordering may
  16. * change at any point.
  17. *
  18. * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
  19. * you perform all queries on the same block. See the following
  20. * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
  21. * for more information.
  22. */
  23. function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
  24. return _roleMembers[role].at(index);
  25. }
  26. /**
  27. * @dev Returns the number of accounts that have `role`. Can be used
  28. * together with {getRoleMember} to enumerate all bearers of a role.
  29. */
  30. function getRoleMemberCount(bytes32 role) public view returns (uint256) {
  31. return _roleMembers[role].length();
  32. }
  33. /**
  34. * @dev Overload {grantRole} to track enumerable memberships
  35. */
  36. function grantRole(bytes32 role, address account) public virtual override {
  37. super.grantRole(role, account);
  38. _roleMembers[role].add(account);
  39. }
  40. /**
  41. * @dev Overload {revokeRole} to track enumerable memberships
  42. */
  43. function revokeRole(bytes32 role, address account) public virtual override {
  44. super.revokeRole(role, account);
  45. _roleMembers[role].remove(account);
  46. }
  47. /**
  48. * @dev Overload {_setupRole} to track enumerable memberships
  49. */
  50. function _setupRole(bytes32 role, address account) internal virtual override {
  51. super._setupRole(role, account);
  52. _roleMembers[role].add(account);
  53. }
  54. }