1

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?

4

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.

  • Great answer, thank you! I see the returned value would be the same in both cases. Would the second case - aside from also changing state - be more reliable in any way? – user1282931 Aug 22 '18 at 15:14
  • Transactions don't actually have return values, so you would have a tough time getting back the new counter value if you used a transaction. It's hard to say if a transaction is more "reliable" without some definition of what you mean. – smarx Aug 22 '18 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.