Solidity Error – Invalid Opcode for this.balance When Contract Balance > 0

contract-debuggingcontract-developmentinvalid-opcoderemixsolidity

I get an exception when I call getBalance in Remix and the contract balance is greater than 0 (ie. I sent some ether using the fallback function):

Exception during execution. (invalid opcode). Please debug the
transaction for more information.

When contract balance is 0 then getBalance correctly returns 0.

pragma solidity ^0.4.0;

contract Test {

    function() payable {}

    function getBalance() public constant returns(uint bal) {
        bal = this.balance;
        return bal;
    }

} 

Best Answer

There is no error in your code, I think after sending a transaction to your contract using the fallback function you call getbalance function with a non null value. While getbalance isn't a payable function you will get the mentioned error. So after before calling getbalance make sure that the value is 0 in remix transaction value :

enter image description here

Related Topic