`

AccessControl

 
阅读更多
// SPDX-License-Identifier: MIT
pragma solidity >= 0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "hardhat/console.sol";

contract MyAccessControl is Ownable,AccessControl,ERC20{
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE");

    //name,symbol
    constructor() ERC20("MyToken","AAA"){
        _setupRole(DEFAULT_ADMIN_ROLE,msg.sender);
    }

    function mint(address addr,uint256 amount) public{
        bool ret = hasRole(MINTER_ROLE,msg.sender);
        console.logBool(ret);
        require(hasRole(MINTER_ROLE,msg.sender),"need miner role");
        _mint(addr,amount);
    }

    function burn(address addr,uint256 amount) public{
        require(hasRole(BURN_ROLE,msg.sender),"need burn role");
        _burn(addr,amount);
    }
}


const { ethers } = require("hardhat")
const web3 = require("web3")

contractName = "MyAccessControl";

describe(contractName, function () {
  it("test ", async function () {
    const Contract = await ethers.getContractFactory(contractName);
    const contract = await Contract.deploy();
    console.log("owner:",await contract.owner());
    [owner1, owner2,owner3] = await ethers.getSigners();
    //owner1是管理员,同样没有mint和burn的权限,但它可以给其它地址加权限
    await contract.connect(owner1).grantRole(web3.utils.soliditySha3("MINTER_ROLE"),owner2.address);
    
    //给owner3添加mint权限
    await contract.connect(owner2).mint(owner3.address,100);
    console.log("after mint,owner3 balance:",await contract.balanceOf(owner3.address));

    //给owner3添加burn权限
    await contract.connect(owner1).grantRole(web3.utils.soliditySha3("BURN_ROLE"),owner3.address);
    await contract.connect(owner3).burn(owner3.address,10);
    console.log("after burn,owner3 balance:",await contract.balanceOf(owner3.address));

    //修改owner
    await contract.connect(owner1).transferOwnership(owner2.address);
    console.log("new owner:",await contract.owner());
  });
});


MyAccessControl
owner: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
true
after mint,owner3 balance: BigNumber { value: "100" }
after burn,owner3 balance: BigNumber { value: "90" }
new owner: 0x70997970C51812dc3A010C7d01b50e0d17dc79C8
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics