Example: Governance And Compliance Library
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev A library to provide governance and compliance functionalities in a DePIN framework.
*/
library GovernanceAndCompliance {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
struct GovernanceData {
mapping(bytes32 => RoleData) roles;
bytes32 DEFAULT_ADMIN_ROLE;
}
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
modifier onlyRole(GovernanceData storage gd, bytes32 role) {
require(hasRole(gd, role, msg.sender), "GovernanceAndCompliance: Access denied");
_;
}
/**
* @dev Initialize the default admin role.
*/
function initialize(GovernanceData storage gd) internal {
gd.DEFAULT_ADMIN_ROLE = 0x00;
}
/**
* @dev Grants a role to an account.
* @param role The role to be granted.
* @param account The account to which the role is granted.
*/
function grantRole(GovernanceData storage gd, bytes32 role, address account) internal onlyRole(gd, gd.roles[role].adminRole) {
if (!hasRole(gd, role, account)) {
gd.roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
/**
* @dev Revokes a role from an account.
* @param role The role to be revoked.
* @param account The account from which the role is revoked.
*/
function revokeRole(GovernanceData storage gd, bytes32 role, address account) internal onlyRole(gd, gd.roles[role].adminRole) {
if (hasRole(gd, role, account)) {
gd.roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
/**
* @dev Checks if an account has a specific role.
* @param role The role to check.
* @param account The account to be checked.
* @return bool True if the account has the role, false otherwise.
*/
function hasRole(GovernanceData storage gd, bytes32 role, address account) internal view returns (bool) {
return gd.roles[role].members[account];
}
/**
* @dev Sets a new admin role for a given role.
* @param role The role for which to set the new admin role.
* @param adminRole The new admin role.
*/
function setRoleAdmin(GovernanceData storage gd, bytes32 role, bytes32 adminRole) internal onlyRole(gd, gd.roles[role].adminRole) {
bytes32 previousAdminRole = gd.roles[role].adminRole;
gd.roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
}Features
Example of Usage:
Explanation
Last updated