Search code examples
ethereumsolidityevm

What happens when the sender run out of gas in the middle of a function execution?


Suppose we have a contract with the following defined function:

   function send(address receiver, uint amount) public {
        if (balances[msg.sender] < amount) return;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        emit Sent(msg.sender, receiver, amount);
    }

and suppose that sender runs out of gas just after the following line:

balances[msg.sender] -= amount;

What happened with the state variables? Are incomplete tx included in the block or not?


Solution

  • A transaction that runs out of gas will fail and none of the state variables will be updated. Failed transactions are still included in a block, as you can see in this out of gas example.

    In your example, balances[msg.sender] -= result will not be executed, and balances[msg.sender] will remain the exact same as before the transaction.

    The sender of the transaction will still pay a fee to the miner for including the transaction in the block.

    This post does a good job of walking through various failure scenarios.