函数声明为 solidity 中的视图错误

Function declared as view error in solidity

pragma solidity >=0.4.16 <0.9.0;

contract Wallet {

    uint balance = 0;
    
    bool a = true;
    
    
    function deposit(uint dep_amt) public {
        balance += dep_amt;
    }

    function withdraw (uint wdraw_amt) public view returns(string memory error){
        if(wdraw_amt<=balance){
         balance -= wdraw_amt;
        }
        
        else{
        error = "Insufficient Balance";
        return error;
        }

    }

    function getBalnce() public view returns (uint) {
       
        return balance;
    }
    

}

我是 solidity 的新手,我正在尝试编写一个简单的银行系统,该系统显示余额并根据存款和取款更新余额。当要提取的金额大于余额时,我想在提款功能中显示错误,但显示错误消息:

TypeError: Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable.

有没有办法显示同一函数的错误?

如果没有,请告诉我一个替代方案。

提前致谢!!

一个view函数承诺不修改合约状态——比如不修改存储变量。有关详细信息,请参阅 docs

但是你的代码修改了balance变量,它是一个存储变量。

function withdraw (uint wdraw_amt) public view returns(string memory error){
    if(wdraw_amt<=balance){
     balance -= wdraw_amt;    // <-- here
    }

and updates the balance according to the deposits and withdraws

由于您的要求之一是实际更新存储变量,因此您需要删除 view 修饰符才能做到这一点。

function withdraw (uint wdraw_amt) public returns(string memory error){

用户随后需要发送交易(不是调用)来执行 withdraw() 功能。


当你有一个由交易执行的函数(而不是通过调用)时,你可以通过两种方式获得字符串输出。

  1. 还原原因消息

    function withdraw(uint wdraw_amt) public {
        if (wdraw_amt <= balance) {
            balance -= wdraw_amt;
        } else {
            revert("Insufficient Balance");
        }
    }
    
  2. 事件日志

    event Error(string _message);
    
    function withdraw(uint wdraw_amt) public {
        if (wdraw_amt <= balance) {
            balance -= wdraw_amt;
        } else {
            emit Error("Insufficient Balance");
        }
    }