Modifier [ solidity]

 Using Modifiers




We can implement the modifier to check if only the owner of the smart contract can call a particular set of functions. A modifier will execute before the function calling it, so it will check and allow only the owner of the contract to make calls to the functions calling the modifier.


We can have multiple modifiers in a smart contract - each modifier dealing with a different check.


Best Practices: Place modifier code after state variable declarations and ideally before function declarations for more legible code.

Code:-

//Modifier without parameters

modifier onlyOwner {

      require(msg.sender == owner);

      _;

//Modifier with parameters

 modifier costs(uint price) {

      if (msg.value >= price) {

         _;

      }

// Program

pragma solidity >=0.7.0 <0.9.0; //solidity version

contract greatestnum{


    uint a;

    uint b;

    uint c;

    uint d;

    address owner;


    constructor(){

        owner = msg.sender;

    }


    modifier onlyOwner { 

        require (owner == msg.sender, "only owner can access");

        _;

    }


    function set (uint _a, uint _b, uint _c, uint _d) public onlyOwner{

        a = _a;

        b = _b;

        c = _c;

        d = _d;

    }


    function get() public view onlyOwner returns(uint){

        if ((a > b) && (a > c) && (a > d)){

        return(a);

        }

        else if ((b >c ) && (b > d) && (b > a)){

            return(b);

        }

        else if ((c > d) && (c > a) && (c > b)){

            return(c);

        }

        else {

            return(d);

        }

    }

}


Comments