0
0
Blockchain / Solidityprogramming~5 mins

Access control with OpenZeppelin in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Access control helps decide who can do what in a smart contract. OpenZeppelin makes it easy to add these rules safely.

You want only the owner to change important settings in your contract.
You want to give special permissions to certain users, like admins.
You want to protect functions so only authorized people can call them.
You want to manage roles easily without writing complex code.
You want to keep your contract secure from unauthorized access.
Syntax
Blockchain / Solidity
import "@openzeppelin/contracts/access/AccessControl.sol";

contract MyContract is AccessControl {
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    constructor() {
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _setupRole(ADMIN_ROLE, msg.sender);
    }

    function restrictedFunction() public onlyRole(ADMIN_ROLE) {
        // code only admins can run
    }
}

Use onlyRole(role) modifier to restrict function access.

Roles are identified by bytes32 hashes, usually created with keccak256.

Examples
This example creates a MINTER_ROLE and restricts the mint function to users with that role.
Blockchain / Solidity
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");

function mint() public onlyRole(MINTER_ROLE) {
    // mint tokens
}
This sets the deployer as the default admin who can grant or revoke roles.
Blockchain / Solidity
constructor() {
    _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
Only the default admin can give the ADMIN_ROLE to others.
Blockchain / Solidity
function grantAdmin(address user) public onlyRole(DEFAULT_ADMIN_ROLE) {
    grantRole(ADMIN_ROLE, user);
}
Sample Program

This contract lets only users with the EDITOR_ROLE change the data. The deployer starts with admin and editor roles.

Blockchain / Solidity
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/AccessControl.sol";

contract SimpleAccess is AccessControl {
    bytes32 public constant EDITOR_ROLE = keccak256("EDITOR_ROLE");

    string public data;

    constructor() {
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _setupRole(EDITOR_ROLE, msg.sender);
    }

    function setData(string memory newData) public onlyRole(EDITOR_ROLE) {
        data = newData;
    }

    function getData() public view returns (string memory) {
        return data;
    }
}
OutputSuccess
Important Notes

Remember to assign roles carefully to avoid locking out important functions.

OpenZeppelin's AccessControl is safer and easier than writing your own permission checks.

Use DEFAULT_ADMIN_ROLE to manage other roles.

Summary

Access control restricts who can use certain functions in a contract.

OpenZeppelin provides ready-made tools to add roles and permissions.

Use onlyRole modifier to protect functions easily.