An overview of solidity function modifiers

overview

This article is used to record the function modifiers currently in use.

visibility modifier

决定函数何时和被谁调用。

private : can only be called inside the contract;
internal : can only be called inside the contract or by inherited contracts;

public : can be called anywhere, whether internal or external;
external : can only be called from outside the contract;

status modifier

用来表示函数如何和区块链交互。

view : running this function will not change or save any data;
pure : running this function will not only not write data to the blockchain, nor even read data from the blockchain;
neither of these two types will be used when called from outside the contract Cost any gas, but they will cost gas when called by other internal functions.

Custom modifiers

Custom modifiers such as onlyowner, aboveLevel, etc., for these modifiers, we can customize their constraint logic on functions.

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    
    
    require(msg.sender == owner);
    _;
  }

These modifiers can act on a function definition at the same time, such as:

function test() external view onlyOwner anotherModifier {
    
     /* ... */ }

payable modifier

A special function that can receive ether

contract OnlineStore {
    
    
  function buySomething() external payable {
    
    
    // 检查以确定0.001以太发送出去来运行函数:
    require(msg.value == 0.001 ether);
    // 如果为真,一些用来向函数调用者发送数字内容的逻辑
    transferThing(msg.sender);
  }
}

msg.value is a way to see how much ether was sent to the contract, and ether is a built-in unit.

Note: If a function is not marked as payable and you try to send ether using the above method, the function will reject your transaction.

Guess you like

Origin blog.csdn.net/qq_35784487/article/details/123324276