OpenZeppelin Part 2: Access Control

Access Control

What is It?

The first category of contracts is access control. Access control allows a developer to regulate who can use certain features of the contract. Examples are: minting tokens, voting on proposals, ownership, etc. This feature is useful for creating a restrictive contract.

How to Use

OpenZeppelin provides two contracts: Ownable.sol and Roles.sol for access control. Both methods are useful in different scenarios depending on how restrictive you want the contract to be.

Ownership

Ownership is the most basic form of access control. It's the best method to use when you have one administrative user. To incorporate ownership, add an import statement at the beginning of your contract.

import "openzeppelin-solidity/contracts/ownership/Ownable.sol";

Importing the Ownable.sol contract allows you to use functions such as transferOwnership(address newOwner) to transfer ownership to different users and renounceOwnership() to renounce ownership of the contract all together. Keep in mind that once a contract is renounced it cannot be claimed again.

The default owner of the contract is the msg.sender of the contract. You can change the owner in the Ownable.sol file.

Ownable contracts have an is Ownable statement. To specify which functions you only want the administrator to have access to, add onlyOwner.

Ownable.sol is a basic implementation of access control that is optimal for a smaller group of users as well as one administrator.

Roles

Access control is also utilized through the contracts/access/Roles.sol contract. This contract allows you to assign roles to different users as well as control who can use certain functions. This is the best method when you have a multiple of users with varying levels of authority.

Add import "openzeppelin-solidity/contracts/access/Roles.sol"; to the top of your contract. Create your different roles Role private "your_Role". A require statement in your function states which users have access.

OpenZeppelin Roles

Within the access folder, there are premade roles for you to use: Capper, Minter,Pauser,Signer,Whitelist Admin,and Whitelisted. To use any of these premade roles, import them. They contain functions to assign the role to your users, renounce the role, and restrict access for functions. All six contracts are identical to each other, except for their names. Thus if you want, you can create your own role contract using one of them as a template.The benefit of doing this would be that it provides a more detailed role and it also makes your code shorter.