Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a modifier do in Solidity?

Reading the docs it says to "add semantics to a function in a declarative ways"

Can I understand it as an "interface" in Java?

like image 587
metalbean Avatar asked Jul 08 '17 04:07

metalbean


1 Answers

Modifiers let you wrap additional functionality to a method, so they're kind of like the decorator pattern in OOP.

Modifiers are typically used in smart contracts to make sure that certain conditions are met before proceeding to executing the rest of the body of code in the method.

For example, isOwner is often used to make sure that the caller of the method is the owner of the contract:

modifier isOwner() {
   if (msg.sender != owner) {
        throw;
    }

    _; // continue executing rest of method body
}

doSomething() isOwner {
  // will first check if caller is owner

  // code
}

You can also stack multiple modifiers to streamline your procedures:

enum State { Created, Locked, Inactive }

modifier isState(State _state) {
    require(state == _state);

    _; // run rest of code
}

modifier cleanUp() {
    _; // finish running rest of method body

    // clean up code
}

doSomething() isOwner isState(State.Created) cleanUp {
  // code
}

Modifiers express what actions are occurring in a declarative and readable manner.

like image 200
Miguel Mota Avatar answered Oct 26 '22 12:10

Miguel Mota