Skip to main content

Permissions

Add permissions to your smart contract to control which addresses can perform certain actions.

There are two different contracts you can implement to add permissions:

  • Permissions: Create roles and restrict access to functions based on those roles.
  • PermissionsEnumerable: Permissions plus the capability to view all the addresses holding a specific role (or all roles).

You only need to implement one of the two.

Unlocked Features

Once deployed, you can use the features made available by these contracts on the SDK and dashboard:

Permissions Contract

Implementing the Feature

Import the contract and make your contract inherit it.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@thirdweb-dev/contracts/extension/Permissions.sol";

contract MyContract is Permissions {
// Any `bytes32` value is a valid role. You can create roles by defining them like this.
bytes32 public constant NUMBER_ROLE = keccak256("NUMBER_ROLE");

// See comments for `setNumber`, below.
uint256 public number;

/**
* The `Permissions` contract makes an already defined role available: the `DEFAULT_ADMIN_ROLE`.
*
* As an EXAMPLE, we grant the deployer of the contract this admin role.
*/
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}

/**
* EXAMPLE: here we have a function that we want to restrict only to holders of `NUMBER_ROLE`.
*
* To accomplish this, we use the `onlyRole` modifier made available by `Permissions`, and
* pass it `NUMBER_ROLE` as an argument.
*/
function setNumber(uint256 _newNumber) public onlyRole(NUMBER_ROLE) {
number = _newNumber;
}
}

Permissions Enumerable Contract

The PermissionsEnumberable is built upon the Permissions feature, and exposes convenient methods to fetch all wallets that hold a given role.

Implementing the Feature

Import the contract and make your contract inherit it.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@thirdweb-dev/contracts/extension/PermissionsEnumerable.sol";

// Usage is the same as `extensions/Permissions.sol`

contract MyContract is PermissionsEnumerable {
// Any `bytes32` value is a valid role. You can create roles by defining them like this.
bytes32 public constant NUMBER_ROLE = keccak256("NUMBER_ROLE");

// See comments for `setNumber`, below.
uint256 public number;

/**
* The `Permissions` contract makes an already defined role available: the `DEFAULT_ADMIN_ROLE`.
*
* As an EXAMPLE, we grant the deployer of the contract this admin role.
*/
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}

/**
* EXAMPLE: here we have a function that we want to restrict only to holders of `NUMBER_ROLE`.
*
* To accomplish this, we use the `onlyRole` modifier made available by `Permissions`, and
* pass it `NUMBER_ROLE` as an argument.
*/
function setNumber(uint256 _newNumber) public onlyRole(NUMBER_ROLE) {
number = _newNumber;
}
}