Access control with roles
A single owner is simple but risky. If that one key is lost or stolen, everything is lost, and the owner can do everything. Role-based access control gives different addresses different powers, such as minting or pausing, and lets you revoke them without redeploying.
A role is just a name, usually a bytes32 value made with keccak256, plus a mapping that says which addresses hold it. A modifier checks the mapping before the function runs. The contract below builds this from scratch so you can see how it works.
In real projects, use OpenZeppelin's AccessControl, which is audited and already has events, admin roles and helper functions. The ideas are identical to the example here.
Follow the principle of least privilege: give each address only the powers it needs. Keep the most powerful role in a multisig wallet that needs several people to approve each action, and consider a timelock so users have time to react to sensitive changes.
Emit an event whenever a role is granted or revoked, because users and monitoring tools rely on these logs to notice when someone's powers change. Also make sure there is a safe way to hand over the admin role, and to give it up on purpose if the contract should become fully decentralized.
contract Roles { bytes32 public constant ADMIN = keccak256("ADMIN"); bytes32 public constant MINTER = keccak256("MINTER"); mapping(bytes32 => mapping(address => bool)) public hasRole; mapping(address => uint256) public balanceOf; event RoleGranted(bytes32 indexed role, address indexed who); event RoleRevoked(bytes32 indexed role, address indexed who); constructor() { hasRole[ADMIN][msg.sender] = true; emit RoleGranted(ADMIN, msg.sender); } modifier onlyRole(bytes32 role) { require(hasRole[role][msg.sender], "Missing role"); _; } function grant(bytes32 role, address who) external onlyRole(ADMIN) { hasRole[role][who] = true; emit RoleGranted(role, who); } function revoke(bytes32 role, address who) external onlyRole(ADMIN) { hasRole[role][who] = false; emit RoleRevoked(role, who); } function mint(address to, uint256 amount) external onlyRole(MINTER) { balanceOf[to] += amount; } }
Try it yourself
Add a PAUSER role and a paused flag, and make mint revert while paused. Only an address with the PAUSER role should be able to change the flag.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.