Access Control Patterns
Access control is the most critical security layer in any smart contract. Most hacks exploit weak or missing access control. Learn the Ownable pattern, role-based access (RBAC), and the OpenZeppelin AccessControl standard.
Ownable → RBAC → AccessControl
Three tiers of access control:
1. Ownable (simple, one admin):
- Single owner address
- onlyOwner modifier gates sensitive functions
- transferOwnership, renounceOwnership
- Use for simple contracts with one operator
2. Multi-role RBAC (custom):
- mapping(address => bool) for each role
- More granular but more code to maintain
3. OpenZeppelin AccessControl (production standard):
- Roles are bytes32 hashes: keccak256("MINTER_ROLE")
- hasRole, grantRole, revokeRole, renounceRole
- DEFAULT_ADMIN_ROLE manages other roles
- Role hierarchies and events built-inCommon Mistakes
- Using tx.origin for access control — tx.origin is the original EOA that started the transaction chain, NOT the immediate caller. Always use msg.sender. tx.origin is exploitable via phishing contracts.
- Deploying without initializing access control — if you forget to set owner/roles in constructor, anyone can call grantRole() on themselves.
- Revoking DEFAULT_ADMIN_ROLE without a replacement — this permanently locks all admin functions. Always ensure at least one admin exists before revoking others.
- Using onlyOwner for everything — large protocols need granular roles. A compromised MINTER key should not also let the attacker pause, upgrade, or drain the treasury.
Tip
Tip
Practice Access Control Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Once deployed, smart contracts are immutable — code is law
Practice Task
Note
Practice Task — (1) Write a working example of Access Control Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Access Control Patterns is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready web3 code.
Key Takeaways
- Access control is the most critical security layer in any smart contract.
- Using tx.origin for access control — tx.origin is the original EOA that started the transaction chain, NOT the immediate caller. Always use msg.sender. tx.origin is exploitable via phishing contracts.
- Deploying without initializing access control — if you forget to set owner/roles in constructor, anyone can call grantRole() on themselves.
- Revoking DEFAULT_ADMIN_ROLE without a replacement — this permanently locks all admin functions. Always ensure at least one admin exists before revoking others.