14-Solidity8.0函数修饰符

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
        }
    }
}


总结

日拱一卒。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值