智能合约 | 函数修饰符

359 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第15天,点击查看活动详情

函数修饰符

  • 函数修饰符:顾名思义,是用来修饰函数的。我们在编写只能合约部署之后会发现,有些函数按钮是红色,有些是橘红色,有些是蓝色。有些函数会加view,有些不加。

控制访问权限子修饰符

关键字:

  • pubilc:是权限最大的,无论是外部访问、类内访问、子类访问、子类继承都是可以的
  • private:出了能类内访问外,其他访问、继承都不行。
  • external:除了不能类内访问其他都可以
  • internal:除了不能外部访问、其他权限都支持

颜色问题

image.png

  • 红色按钮:是指可支付函数,该类函数涉及资产的转移、该类函数必须加payable关键字,调用时会消耗gas,可以修改状态变量(改变了资产)

  • 橘红色按钮:写函数,调用时消耗gas,改变状态变量(增加了数据)

  • 蓝色按钮:只读函数,使用view关键字,不允许修改状态变量,调用时不会消耗gas,比如查询余额等··· 这是使用remix编译出来的一个payable.sol文件的函数

  • 代码示例:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract Payable {

    // Payable address can receive Ether

    address payable public owner;


    // Payable constructor can receive Ether

    constructor() payable  {

        owner = payable(msg.sender);

    }


    // Function to deposit Ether into this contract.

    // Call this function along with some Ether.

    // The balance of this contract will be automatically updated.

    function deposit() public payable {}


    // Call this function along with some Ether.

    // The function will throw an error since this function is not payable.

    function notPayable() public {}


    //从合约取钱

    function withdraw(uint _amounts) public {

        // 查询合约余额

        uint amount = address(this).balance;

         //输入金额大于合约金额

         require(_amounts>amount,"The contract amount is less than the withdrawal amount");

        //管理员收到以太币

        (bool success, ) = owner.call{value: _amounts}("");

       

        require(success, "Failed to send Ether");

    }

    // Function to transfer Ether from this contract to address from input

    function transfer(address payable _to, uint _amount) public {

        // Note that "to" is declared as payable

        (bool success, ) = _to.call{value: _amount}("");

        require(success, "Failed to send Ether");

    }

}

除了只读的view外,智能合约中还有一个关键字---pure,它及不可以访问状态变量,也不可以更改状态变量.