Managing roles using Roles.sol

Roles.sol is a generic library that stores the access rights that are provided to an address. All the roles-based contracts defined in OpenZeppelin use this library. It also exposes some internal functions that can only be called within the contract. Using this generic library, we can create and define our own roles for different kinds of access controls. In this section, we will look into the different roles that OpenZeppelin provides, such as PauserRole.sol and MinterRole.sol, which also inherit from Roles.sol.

The OpenZeppelin contract present at Chapter09/openzeppelin-solidity/contracts/access/Roles.sol is defined as follows:

library Roles {
struct Role {
mapping (address => bool) bearer;
}

function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));

role.bearer[account] = true;
}

function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));

role.bearer[account] = false;
}

function has(Role storage role, address account) internal view returns
(bool) {
require(account != address(0));
return role.bearer[account];
}
}

Let's review the preceding code in more detail. The library contract contains the following functions and structs:

  • Structs:
  • The Role struct is defined in the library. It has a mapping to store the addresses that have the role enabled or disabled. If the Boolean value is set to true for the respective address, the role is enabled, otherwise disabled.
  • Functions: All of these functions are internal functions that will be called from the contracts using this library:
  • add(): The function to assign the role to a new address
  • remove(): The function to revoke the assigned role from an existing address
  • has(): The view function to check whether an address has the role

There are many predefined roles present in the OpenZeppelin library. These roles are also used in other contracts for role-based access. Let's look at these now.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.113.80