舊版本就不探討了,建議大家用新的。

參考

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.5.0/contracts/access/Ownable.sol

Ownership and Ownable

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

import "<https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.5.0/contracts/access/Ownable.sol>";

contract MyContract is Ownable {
    
    int public  i ;
		// 任何人都能呼叫
    function normalThing() public {
        i +=1;
        // anyone can call this normalThing()
    }
		// 只有owner可以呼叫
    function specialThing() public onlyOwner {
         i -=1; 
        // only the owner can call specialThing()!
    }
}

截圖 2022-03-29 下午11.34.33.png

Role-Based Access Control (RBAC) 基於角色的權限控制

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

import "<https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.5.0/contracts/access/AccessControl.sol>";
import "<https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.5.0/contracts//token/ERC20/ERC20.sol>";

contract RBAC is ERC20, AccessControl {
    // 命名角色
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
		//發代幣
    constructor(address minter) ERC20("RBACTOKEN","RBACT"){
        _setupRole(MINTER_ROLE,minter); // 設定角色
    }

    function mint(address to, uint256 amount) public {
				// 判定是不是鑄造人員
        require(hasRole(MINTER_ROLE,msg.sender),"Caller is not a minter");
        _mint(to, amount);
    }
}

建立合約的Owner 是 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4