跳转至

16.FunctionModifier

Modifiers are code that can be run before and / or after a function call.

basic, inputs, sandwich

Modifiers can be used to:

  • Restrict access
  • Validate inputs
  • Guard against reentrancy hack

basic

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

contract FunctionModifier {
    bool public paused;
    uint256 public count;

    function setPause(bool _paused) external {
        paused = _paused;
    }

    function inc() external {
        require(!paused, "paused");
        count += 1;
    }

    function dec() external {
        require(!paused, "paused");
        count -= 1;
    }
}

用function modifier

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

contract FunctionModifier {
    bool public paused;
    uint256 public count;

    function setPause(bool _paused) external {
        paused = _paused;
    }

    // function modifier
    modifier whenNotPaused() {
    // 检查条件后再执行函数
        require(!paused, "paused");
        _;
    }

    function inc() external whenNotPaused {
        count += 1;
    }

    function dec() external whenNotPaused {
        count -= 1;
    }
}

inputs

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

contract FunctionModifier {
    bool public paused;
    uint256 public count;

    function setPause(bool _paused) external {
        paused = _paused;
    }

    // function modifier
    modifier whenNotPaused() {
        require(!paused, "paused");
        _;
    }

    function inc() external whenNotPaused {
        count += 1;
    }

    function dec() external whenNotPaused {
        count -= 1;
    }
    modifier cap(uint x){
        require(x<100,"x>=100");
        _;
    }
    // 检查多个条件
    function incBy(uint _x) external whenNotPaused cap(_x){
        count+=_x;
    }
}

sandwich

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

contract FunctionModifier {
    bool public paused;
    uint256 public count;

    function setPause(bool _paused) external {
        paused = _paused;
    }

    // function modifier
    modifier whenNotPaused() {
        require(!paused, "paused");
        _;
    }

    function inc() external whenNotPaused {
        count += 1;
    }

    function dec() external whenNotPaused {
        count -= 1;
    }
    // 函数夹在中间运行
    modifier sandwich() {
        count += 10;
        _;
        count *= 2;
    }
    // // 调用foo会发生什么?
    // 1. count+=10;
    // 2. count+=1;
    // 3. count*=2
    function foo() external sandwich {
        count += 1;
    }
}