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);
}
}
}
总结
日拱一卒。
本文介绍了Solidity 8.0中函数修饰符的重要概念和应用,包括用于限制访问、验证输入和防止重入攻击的功能。通过示例代码展示了如何使用`onlyOwner`、`validAddress`和`noReentrancy`等修饰符来确保智能合约的安全性和正确性。了解这些修饰符对于编写安全的智能合约至关重要。
760

被折叠的 条评论
为什么被折叠?



