CSC101-Modifier

zeroxlive
Coinmonks
3 min readAug 30, 2022

--

Function Modifiers are used to modify the behavior of a function. For example to add a prerequisite to a function.

Modifier

Modifiers are code that can be run before and / or after a function call.Solidity documentation defined modifier as follow:

“A function modifier is a compile-time source code roll-up.

It can be used to amend the semantics of functions in a declarative way.”

Modifiers can be used to:

  • Restrict access
  • Validate inputs
  • Guard against reentrancy hack

let’s assume we deployed a smart contract on blockchain.everyone can interact to our smart contract and also has access to our contract and functions. in this way everyone can call all of functions and sign a transaction. this is where we use modifiers.Using modifier we can check the conditions before executing functions.

Syntax:

Example:

in the code above , function will be executed if transaction sender is contract owner.

let’s go deeper with other example to better understand.

let’s assume we have a virtual bank.in the example above only contract owner can execute the function.Now we specify the requirement with require. The owner and the message of the creator must be the same. Only the address of the creator is compared with that of the sender. If this statement is true, the code is processed. If this statement is false, nothing happens. Then we set “_” so that the function is always executed first. This will display an error if someone who is not the creator of the smart contract wants to change something. Now we just need to add ownerFunction to each function where we don’t want anyone other than the creator to be able to change anything.

let’s back to previous example:

now we wanna know how does modifier works.

The symbol _; is called a merge wildcard. It merges the function code with the modifier code where the _; is placed.The place where you write the _; symbol will decide if the function has to be executed before, in between or after the modifier code.

Passing arguments to Modifiers

Modifiers can also accept arguments. Like a function, you just have to pass the variable type + name between parentheses in front of the modifier name.

Syntax:

You can write a modifier with or without arguments. If the modifier does not have argument, you can omit the parentheses () .

Example:

New to trading? Try crypto trading bots or copy trading

--

--