$234.87 6.43%
ETH · 141w

How to write clean, elegant Solidity code using function modifiers — Colony

How to write clean, elegant Solidity code using function modifiers

One of the most interesting features in Solidity are function modifiers. When added to a function body they extend it, allowing us to abstract parts of our code and write functions with fewer conditionals checks intertwined with state changes.

Creating a function modifier

The syntax looks similar to declaring a function, except it uses the modifier keyword. The underscore on indicates how the original function is changed:

modifier assertValueIsOne(uint value) { assert(value == 1); _; // original function goes at this point} function doSomething(uint value) assertValueIsOne(value){ } Use cases

Checking for invariants or conditions using require, revert (throw is deprecated, see more here) or assert accordingly:

// For parameterless modifiers, we can omit parenthesismodifier isAllowed { assert(msg.sender == owner); // contract state _;} modifier isValidAddress(address target) { require(target != 0x0); _;} modifier isValueBiggerThanZero(uint value) { require(value > 0); _;} function isOwner(address target) constant returns (bool) { return target == owner;} function simpleFunction(address target) isValidAddress(target) isValueBiggerThanZero(msg.value) isAllowed // omitted parenthesis for parameterless modifiers payable{ // do something} Please note that modifiers are applied to the original function in the order they are presented on the function declaration, i.e: isValidAddress, isValueBiggerThanZero, isAllowed and then payable.

Checking for msg.sender permissions:

modifier isOwner { assert(owner == msg.sender); _;} function finalize() isOwner { finalized = true;}

Raising events before or after a function is called:

event StartEvent();event FinishEvent(); modifier logEvents { StartEvent(); _; FinishEvent();} function toggle () logEvents { } Conclusion

Before formal verification or code coverag...

Continue on
Recent news
ETH +6.43% · · 1h

Bullish. Bullish indeed.

This was deleted before, I don't know why. Perhaps I have not written enough content. Or someone was offended by the simplicity of my idea. I am no pro trader, but I know there are fractals and certai...
ETH +6.43% · · 13h


Get Ethereum Money (ETHMNY) price, charts, volume, market cap, exchange list and more.
ETH +6.43% · · 17h

Where in the world is Bitfinex?

Where is Bitfinex? The question had long been nagging Cas Piancey (pronounced “Caspian Sea”), an online persona, who tweets relentlessly about the exchange. He became so obsessed about the firm's opaq...
ETH +6.43% · · 20h

Infura May 2020 Update

An update on our Beacon Chain API, a recap of the recent IPFS Pinning Summit, how to create a Compound smart contract API with Infura, Gnosis, and more.