Skip to content

Instantly share code, notes, and snippets.

Last active October 5, 2022 22:14
What would you like to do?
NFT Roles description
// SPDX-License-Identifier: MIT
// by
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
contract Roles is ERC1155, AccessControl {
// errors
error NoDuplicateRoles();
error TokenTransferProhibited();
// role storage
bytes32 public constant URI_SETTER_ROLE = keccak256("URI_SETTER_ROLE");
mapping(bytes32 => uint256) public nftRoles;
constructor() ERC1155("") {
//add roles to mapping
nftRoles[URI_SETTER_ROLE] = 1;
//grant initial roles
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(URI_SETTER_ROLE, msg.sender);
function setURI(string memory newuri) public onlyRole(URI_SETTER_ROLE) {
function _grantRole(bytes32 role, address account) internal override {
// check if users already has the role, if so don't mint or grant
if (hasRole(role, account)) {
revert NoDuplicateRoles();
// mint the role
_mint(account, nftRoles[role], 1, "");
// grant the role
super._grantRole(role, account);
function _revokeRole(bytes32 role, address account) internal override {
// burn the role
_burn(account, nftRoles[role], 1);
// revoke the role
super._revokeRole(role, account);
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal override {
// prevent roles from being transfered like NFTs
if(from != address(0)){
revert TokenTransferProhibited();
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId) public view override(ERC1155, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment