Modifer的修飾使用撰寫中比較不會重複

舉例:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.0;

contract ModiferExample {

    address Owner;
    uint account;

    constructor(){
        Owner = msg.sender;
        account = 0;
    }

    function setAccount(uint _account) public{
        if(msg.sender == Owner){
            account = _account;
        }
        
    }

}

上述是一個簡單的設定Account function,我們希望是擁有合約的人才能操作。

所以我們多加了一個判斷權限 if(msg.sender == Owner),但大家可以想想

如果我每次要新增控制權限我都要多加一段判定式,對於閱讀版面其實都會有些複雜,重點別忘了字越多空間越多cost更高

所以可以用Modifer 解決,如下:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.0;

contract ModiferExample {

    address Owner;
    uint account;

    constructor(){
        Owner = msg.sender;
        account = 0;
    }
		// 定義一個modifier 後續都可以使用
		modifier onlyOwner(){
        require(msg.sender == Owner,"Is not Owner");
        _;
    }

    function setAccount(uint _account) public{
        if(msg.sender == Owner){
            account = _account;
        }
        
    }

		function setAccountModifier(uint _account) public onlyOwner{
        account = _account;
    }

輕鬆簡單!!

以下會發現阻擋

截圖 2022-03-18 上午10.41.38.png

9.Event

有任何問題可反饋: [email protected]