DEV Community

tawseef nabi
tawseef nabi

Posted on

1

Modifiers in solidity

Modifiers can be used to change the behavior of functions in a declarative way.
For example, you can use a modifier to automatically check a condition prior to executing the function. they can be used for:

  1. Restrict access
  2. Validate inputs
  3. Guard against reentrancy hack
  • use the modifier in the declaration of a function.

Modifier to check that the caller is the owner of the contract

modifier onlyOwner {
   require(msg.sender == owner);
     // Underscore is a special character only used inside
     // a function modifier and it tells Solidity to
     // execute the rest of the code.
   _;
 }
Enter fullscreen mode Exit fullscreen mode

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");
       _;
   }
Enter fullscreen mode Exit fullscreen mode
function changeOwner(address _newOwner) public onlyOwner validAddress(_newOwner) {
       owner = _newOwner;
   }
Enter fullscreen mode Exit fullscreen mode

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);
   }
 }
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Learn how to monitor AWS container environments at scale

In this eBook, Datadog and AWS share insights into the changing state of containers in the cloud and explore why orchestration technologies are an essential part of managing ever-changing containerized workloads.

Download the eBook

Top comments (0)