Skip to content
the poor coder

make a modifier in solidity

Poor Man
Published
Reading time
1 min read
On this page

Modifying in Solidity#

Solidity is a programming language used for developing smart contracts on the Ethereum blockchain. Modifiers in Solidity are used to modify the behavior of a function by adding some conditions or restrictions to it.

Creating a Modifier#

To create a modifier, we use the keyword "modifier" followed by the name of the modifier. Here is an example:

SOLIDITY
modifier onlyAdmin() {
    require(admin == msg.sender, "Only admin can execute this function");
    _;
}

This modifier is called onlyAdmin and it checks if the sender of the transaction is the admin. If it is, then the function will be executed, otherwise, it will revert with an error message.

Using a Modifier#

To use a modifier, we simply add the modifier's name before the function declaration. Here is an example:

SOLIDITY
function changeAdmin() public onlyAdmin {
    // Code to change admin
}

This function can only be executed by the admin because we added the onlyAdmin modifier to it.

Multiple Modifiers#

You can also use multiple modifiers on a function by separating them with commas. Here is an example:

SOLIDITY
modifier onlyAdminAndOwner() {
    require(admin == msg.sender || owner == msg.sender, "Only admin or owner can execute this function");
    _;
}

function changeAdminAndOwner() public onlyAdminAndOwner {
    // Code to change admin and owner
}

This function can only be executed by the admin or the owner because we added the onlyAdminAndOwner modifier to it.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC