0
0
Blockchain / Solidityprogramming~5 mins

Function modifiers in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Function modifiers help change how functions work without changing their code. They add extra checks or actions before or after a function runs.

To check if a user has permission before running a function.
To make sure a function runs only once or under certain conditions.
To add logging or tracking around function calls.
To reuse common code like validation in many functions.
To protect functions from being called by unauthorized users.
Syntax
Blockchain / Solidity
modifier modifierName() {
    // code to run before function
    _; // placeholder for the function body
    // code to run after function
}

function someFunction() modifierName() public {
    // function code
}

The underscore _; is where the original function's code runs.

Modifiers can run code before and/or after the function.

Examples
This modifier checks if the caller is the owner before running the function.
Blockchain / Solidity
modifier onlyOwner() {
    require(msg.sender == owner, "Not owner");
    _;
}
This modifier checks if enough Ether was sent with the call.
Blockchain / Solidity
modifier costs(uint price) {
    require(msg.value >= price, "Not enough Ether");
    _;
}
This modifier runs the function first, then checks if the deadline passed.
Blockchain / Solidity
modifier afterDeadline() {
    _;
    require(block.timestamp > deadline, "Too early");
}
Sample Program

This contract uses a modifier onlyOwner to allow only the owner to increase the count.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract SimpleContract {
    address public owner;
    uint public count;

    constructor() {
        owner = msg.sender;
        count = 0;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }

    function increment() public onlyOwner {
        count += 1;
    }

    function getCount() public view returns (uint) {
        return count;
    }
}
OutputSuccess
Important Notes

Modifiers help keep your code clean by reusing common checks.

Always place _; in the modifier where you want the function code to run.

Modifiers can take parameters to customize their behavior.

Summary

Function modifiers add extra rules or actions around functions.

Use _; inside modifiers to run the original function code.

Modifiers help keep your contract safe and organized.