官术网_书友最值得收藏!

Modifiers

Modifiers are a special type of function that are used to verify data or execute something before the current function execution as a middleware. They are mostly used to verify that the user executing the function has the required permissions and to verify the parameters:

address public owner;
modifier onlyOwner() {
require(msg.sender == owner, ‘You must be the owner');
_;
}

function doSomething() public onlyOwner {}

As you can see, the onlyOwner modifier is used to check if the doSomething function is being executed by the owner of the contract or by another user. If the caller is the owner, the functions gets executed, and if it's an external address, the contract will revert, and an exception will be thrown.

Note that the require() function is a global assert function to verify that the condition inside it it's true or not. If not, it will throw, and it will stop executing the smart contract.

The underscore statement inside the _ modifier is used to indicate where the code of the function will be executed. Sometimes, you want to execute the function before the modifier's checks. The underscore statement is mandatory in modifiers. Also note that the modifier can have parameters optionally. If none are required, you can remove the brackets as follows:

modifier onlyOwner { ... }

Modifiers are very powerful tools that you'll often use whenever you see repetitive code doing the same verifications for several functions.

In the next section, you'll see the types of special modifiers that functions can take for visibility and payments.

主站蜘蛛池模板: 亳州市| 孝昌县| 宜都市| 大庆市| 宿迁市| 博乐市| 吉水县| 惠来县| 佛山市| 龙陵县| 夹江县| 望城县| 田阳县| 自贡市| 甘孜县| 当阳市| 武强县| 上栗县| 波密县| 贺州市| 鄄城县| 江阴市| 镇江市| 惠来县| 阜阳市| 松江区| 博野县| 长寿区| 大庆市| 辽阳市| 永丰县| 宁国市| 乐东| 湘潭市| 北海市| 黔西县| 武威市| 珠海市| 晋城| 平度市| 准格尔旗|