TAGS :Viewed: 14 - Published at: a few seconds ago

[ Solidity Tutorial : all about Modifiers ]

How do modifiers work? Let’s start with some basic examples below. modifier onlyOwner { require(msg.sender == owner); _; } The _; symbol The symbol _; is called a merge wildcard. It merges the function code with the modifier code where the _; is placed. (give example in code). In other terms, the body of the function (to which the modifier is attached to) will be inserted where the special symbol _; appears in the modifier’s definition. Using the terms of the Solidity docs, it “returns the flow of execution to the original function code”. A modifier must have the symbol _; within its body in order to execute. It is mandatory (does Solidity throw an error if it is not the case?). Where to place the _; ? The place where you write the _; symbol will decide if the function has to be executed before, in between or after the modifier code. modifier SomethingBefore { require(/* check something first */); _; // resume with function execution } // Do one where modifier is placed in the middle modifier SomethingAfter { _; // run function first require(/* then check something */) } As shown in the example above, you can place the _; at the beginning, middle or the end of your modifier body. In practice, (especially until you understand how modifiers work really well), the safest usage pattern is to place the _; at the end. In this scenario, the modifier serves for consistent validation check, so to check a condition upfront and then carry on. The code snippet below show show this as example: function isOkay() public view returns(bool) { // do some validation checking return true; } function isAuthorised(address _user) public view returns(bool) { // logic that checks that _user is authorised return true; } modifier OnlyIfOkAndAuthorised { require(isOkay()); require(isAuthorised(msg.sender)); _; }