상세 컨텐츠

본문 제목

Solidity - Function Modifier

Programming Language/Solidity

by Yongari 2022. 12. 28. 22:24

본문

 

Function Modifier
함수 수정자

Modifiers are code that can be run before and / or after a function call.
수정자는 함수 호출 전후에 실행할 수 있는 코드입니다.

Modifiers can be used to:
수정자는 다음과 같이 사용할 수 있다.

 

  • Restrict access
    엑세스 제한, 접근 제한
  • Validate inputs
    입력 유효성 검사
  • Guard against reentrancy hack
    재진입 해킹으로부터 보호



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

contract FunctionModifier {
    // We will use these variables to demonstrate how to use
    // modifiers.
    address public owner;
    uint public x = 10;
    bool public locked;

    constructor() {
        // Set the transaction sender as the owner of the contract.
        owner = msg.sender;
    }

    // Modifier to check that the caller is the owner of
    // the contract.
    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        // Underscore is a special character only used inside
        // a function modifier and it tells Solidity to
        // execute the rest of the code.
        _;
    }

    // Modifiers can take inputs. This modifier checks that the
    // address passed in is not the zero address.
    modifier validAddress(address _addr) {
        require(_addr != address(0), "Not valid address");
        _;
    }

    function changeOwner(address _newOwner) public onlyOwner validAddress(_newOwner) {
        owner = _newOwner;
    }

    // Modifiers can be called before and / or after a function.
    // This modifier prevents a function from being called while
    // it is still executing.
    modifier noReentrancy() {
        require(!locked, "No reentrancy");

        locked = true;
        _;
        locked = false;
    }

    function decrement(uint i) public noReentrancy {
        x -= i;

        if (i > 1) {
            decrement(i - 1);
        }
    }
}

'Programming Language > Solidity' 카테고리의 다른 글

Solidity - Constructor  (0) 2022.12.30
Solidity - Events  (0) 2022.12.29
Solidity - Error  (0) 2022.12.27
Solidity - View and Pure Functions  (0) 2022.12.27
Solidity - Fuction  (0) 2022.12.26

관련글 더보기