Solidity8.0
14-Solidity8.0函数修饰符
前言
函数修饰符
修饰符是可以在函数调用之前和/或之后运行的代码。
修饰符可用于:
限制访问
验证输入
防范重入黑客
一、Solidity函数修饰符
1.函数修饰符
代码如下(示例):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
contract FunctionModifier {
// We will use these variables to demonstrate how to use
// modifiers.
address public owner;
uint public x = 10;
bool public locked;
constructor() {
// Set the transaction sender as the owner of the contract.
owner = msg.sender;
}
// Modifier to check that the caller is the owner of
// the contract.
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
// Modifiers can take inputs. This modifier checks that the
// address passed in is not the zero address.
modifier validAddress(address _addr) {
require(_addr != address(0), "Not valid address");
_;
}
function changeOwner(address _newOwner) public onlyOwner validAddress(_newOwner) {
owner = _newOwner;
}
modifier noReentrancy() {
require(!locked, "No reentrancy");
locked = true;
_;
locked = false;
}
function decrement(uint i) public noReentrancy {
x -= i;
if (i > 1) {
decrement(i - 1);
}
}
}
总结
日拱一卒。