【以太坊 Solidity】管理员读写权限/访问控制/角色控制

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

摘要

在 Solidity 语言的多继承中若多个合约共同继承一个父合约则这多个合约 共享 父合约中的变量和函数。

1.测试的智能合约

合约继承路线如下

权限管理合约Authority
基类合约A
基类合约B
测试合约Test

1.1 权限管理合约

// SPDX-License-Identifier: GPL-3.0
// filename: authority.sol
pragma solidity ^0.8.18;  

contract Authority {
    address private OWNER;
    mapping(address => bool) private ADMIN;

    constructor() {
        OWNER = msg.sender;
        ADMIN[OWNER] = true; // !注意此处意为授予合约拥有者管理员权限
    }

    modifier isOwner() {
        require(msg.sender == OWNER, unicode"非合约拥有者");
        _;
    }
    // 修饰函数被修饰的函数仅管理员才可调用
    modifier isAdmin() {
        require(ADMIN[msg.sender] == true, unicode"无管理员权限");
        _;
    }

    function addAdmin(address addrs) public isOwner {
        ADMIN[addrs] = true;
    } 
    function removeAdmin(address addrs) public isOwner { 
        ADMIN[addrs] = false;
    }
}

1.2 继承权限管理合约的基类合约

// SPDX-License-Identifier: GPL-3.0
// filename: base.sol
pragma solidity ^0.8.18;  
import { Authority } from "./authority.sol";

// 继承 Authority 合约继而使用 isAdmin() 修饰函数
contract A is Authority {
    string a = "aaa";
	// 仅管理员才可调用 getAstring()
    function getAstring() isAdmin public view returns (string memory) {
        return a;
    }
}

contract B is Authority {
    string b = "bbb"; 
    function getBstring() isAdmin public view returns (string memory) {
        return b;
    }
}

1.3 待测试的合约

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;  
import { A, B } from "./base.sol"; 

contract Test is A, B {  
    // 合约 Test 继承了 A 中的 a, getAstring() 以及
    //  B 中的 b, getBstring()
}

2.权限管理合约测试

2.1 正向测试合约拥有者OWNER具有管理员权限

此时 合约 Authority 中的 构造函数 constructor() 中的 ADMIN[OWNER] = true意为 OWNER 具有管理员权限。
经 Remix 中测试Test 合约的部署者具有管理员权限能正常调用继承的函数如下
在这里插入图片描述

2.2 反向测试合约拥有者OWNER没有管理员权限

此步测试中将 合约 Authority 中的 构造函数 constructor() 中改为 ADMIN[OWNER] = false意为 用户 OWNER 没有了管理员权限测试测试结果如下
在这里插入图片描述

3.总结

合约继承图

权限管理合约Authority
基类合约A
基类合约B
测试合约Test

虽然 合约 ABTest 都直接或间接继承了 合约 Authority但是 合约 ABTest 都 “ 共享 ” 了 合约 Authority 中的 变量 ADMIN 函数 isAdmin() 等。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: 区块链