简体   繁体   中英

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

}

I'm very new to solidity and I'm trying to code a simple bank system which shows the balance and updates the balance according to the deposits and withdraws. I want to display an error in withdraw function when the amount to be withdrawn is greater than the balance but it shows an error saying:

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

Is there a way to possibly show the error from the same function?

If not, Please let me know an alternative.

Thanks in advance!!.

A view function promises not to modify the contract state - such as not to modify storage variables. See the docs for more info.

But your code modifies the balance variable, which is a storage variable.

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

Since one of your requirements is to actually update the storage variable, you need to remove the view modifier in order to be able to do that.

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

Users will then need to send a transaction (not a call) to execute the withdraw() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM