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

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.

主站蜘蛛池模板: 汕头市| 平武县| 元阳县| 吉水县| 夏邑县| 阳信县| 黄石市| 晋州市| 剑川县| 平山县| 西乌珠穆沁旗| 台湾省| 揭阳市| 大同县| 奉节县| 新营市| 许昌县| 武宁县| 温州市| 慈利县| 喀喇沁旗| 绥滨县| 榆林市| 麦盖提县| 即墨市| 岑溪市| 阿坝| 抚顺县| 云龙县| 山东省| 敦化市| 马公市| 井陉县| 博客| 靖边县| 思茅市| 望都县| 兰西县| 台江县| 营山县| 汾西县|