舊版本就不探討了,建議大家用新的。
參考
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.5.0/contracts/access/Ownable.sol
Ownership and Ownable
transferOwnership 從所有者帳戶到新帳戶 (資產轉移)
renounceOwnership 為所有者放棄此管理特權,這是在集中管理初始階段結束後的常見模式
1. 使用這個 function 請特別小心,如果控制不好會整個權限都不見。 2. 一開始只有創建合約的人能使用。
// 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()!
}
}
Role-Based Access Control (RBAC) 基於角色的權限控制
AccessControl
Granting()
授權Revoking()
撤銷// 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