Search code examples
blockchainethereumsoliditysmartcontractsremix

i'm addming a value to the contract but i recevie this error "VM error revert"


enter image description here

contract Bank {


    address public admin;

    constructor() {
       admin = msg.sender;
    }

   mapping (address => uint) balance;
   mapping (address => bool) AccountActive;

    function closeAccount() public  payable{
    AccountActive[msg.sender] = false;
        //trasfer all the money from an account closed to the admin
        payable(admin).transfer(balance[msg.sender]);
        
    }

    function viewbalance() public view returns(uint) {
        return balance[msg.sender];
        
    }}

when inserting a value before deployment, I get this error, and if I don't do it in this way the balance is 0, why? (sorry for this noob question)


Solution

  • The issue is here:

    payable(admin).transfer(balance[msg.sender]);
    

    You want to transfer money from the admin but the admin has no balance. So you need to send money. For this write this function:

      function depositMoneyToAdmin() payable public {
            // since it is payable, the money that you send would be stored in msg.value
            (bool success,) = admin.call{value: msg.value}("");
            // then add the owner's balance to the mapping so when u call viewBalance, you get the balance of owner
            balance[admin]+=msg.value;
             require(success,"Transfer failed!");
        }
    

    enter image description here

    Avoid using transfer.

    https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/