[Ethereum] What happens if view function calls function that is neither ‘view’ nor ‘pure’

puresolidityview

currently view is not enforced. Calling a function that is neither 'view' nor 'pure' from within a function that is causes a warning, but compiles.

My question is what is the result from externally calling such a function, and is the result well defined? Does it return the correct result but simply not change state?

for example:

contract Test {
    uint counter = 0;
    function A() public returns (uint256) {
        counter++;
        return counter;
    }

    function B() public view returns (uint256) {
        return A();
    }
}

What happens if I call B() externally? does it for sure return the current counter without consuming gas, just without making a state change to the contract?

Best Answer

Functions can be invoked in two different ways:

  1. Via a transaction, which is broadcast to the network and changes blockchain state.
  2. Via a call, which is performed locally on a single Ethereum network and does not change any blockchain state.

It's actually up to the client to decide which to do, but if a function is marked view, the default behavior of most clients (e.g. Remix, web3.js, etc.) is to use a call. That basically means running the transaction but not recording any state changes.

So in the above case, if you call B(), it will in effect give you back the value counter + 1. (During execution, it will increment the counter, but that change will simply be discarded.)

That said, you could invoke B() via a transaction, in which case the counter would truly be incremented in a persistent way. In essence, view is a hint to clients that they should use a call rather than a transaction.

Related Topic