James Bachini

Modifiers in Solidity | Solidity Tips & Examples

modifier solidity

Modifiers in Solidity are a way to add a certain condition to functions within a smart contract. They allow developers to define a piece of code that can be reused across multiple functions and contracts, making your code more modular and easier to read.

A modifier is defined using the modifier keyword, followed by a name, and then a block of code enclosed in curly braces. This code block contains conditions that must be met for the modifier to be applied.

Full code available in the Solidity Snippets Github repo: https://github.com/jamesbachini/Solidity-Snippets/blob/main/contracts/Modifier.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

contract Modifier {
    modifier onlyVitalik() {
        require(msg.sender == 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045);

    function doSomething() external onlyVitalik {
        // Only vitalik's wallet can call this function

In the above example we want to add a modifier condition that checks to see if the msg.sender (person that called the transaction) is Vitalik’s wallet address.

We call this modifier onlyVitalik and we add it to the doSomething() function so that only Vitaliks wallet can access that function.

Modifiers provide a simple, reusable way to add conditional checks before running code. Here are a couple of common examples where they are used are:

  • Ownable.sol – the OpenZeppelin library allows you to add the onlyOwner modifier so that only the contract deployer or a set address can access that functionality
  • ReentrancyGaurd.sol – another OpenZeppelin library that uses a nonReentrant modifier to prevent reentrancy attacks

I hope this quick breakdown of the modifier implementation within Solidity is of interest and it helps you build out your contracts to become the future of finance… or just a fun NFT collection on testnet.

Modifiers in Solidity

Get The Blockchain Sector Newsletter, binge the YouTube channel and connect with me on Twitter

The Blockchain Sector newsletter goes out a few times a month when there is breaking news or interesting developments to discuss. All the content I produce is free, if you’d like to help please share this content on social media.

Thank you.

James Bachini

Disclaimer: Not a financial advisor, not financial advice. The content I create is to document my journey and for educational and entertainment purposes only. It is not under any circumstances investment advice. I am not an investment or trading professional and am learning myself while still making plenty of mistakes along the way. Any code published is experimental and not production ready to be used for financial transactions. Do your own research and do not play with funds you do not want to lose.