solidity基础-修饰器


  修饰器,通过定义一个方法,使用该方法去修饰其他方法。

  用个没有用修饰器的例子说明,onlyOwner 是一个校验地址是不是原来账号的地址的方法。

  将该合约部署

contract Test {
    
    address public owner;
    uint256 public price;

    constructor(){
        owner = msg.sender;
    }

    function onlyOwner() public view{ 
        require(
            msg.sender == owner,
            "Only seller can call this."
        );   
    }

    function setPrice(uint256 _price) public{
        onlyOwner();
        price = _price;
    }
}

此时的地址是第一个地址,调用 setPrice 方法,再查看 price 可以看到 123 的输出。

换一个地址

再调用,setPrice, 可以看到 console 输出,报错。

使用modifier

先定义一个 modifier 

再在方法中修饰  

contract ModifierTest {
    
    address public owner;
    uint256 public price;

    constructor(){
        owner = msg.sender;
    }

    modifier onlyOwner(){ // Modifier
        require( msg.sender == owner,  "Only Owner can call this."  );   
        _;
    }

    function setPrice(uint256 _price) public
       onlyOwner
    {     
        price = _price;
    }
}

部署测试

输出报错

是可以校验的

相关