I have a function:

function test(uint value) {
    if (balances[msg.sender] < value)

    balances[msg.sender] -= value;

I understand that reading from the blockchain only consume 0 gas, for View and Pure function.

So my question is: For the function above will I have to pay for gas if I have insufficient balance and return early (no transaction made).

  • pure and view function are functions that just read data or do calculation without changing the state(storage). Your function is changing the balances (storage) and therefore it require a transaction and fees
    – Majd TL
    Feb 27, 2022 at 15:09

1 Answer 1


Since the function code you provided is not defined as view or pure, this becomes "write" function. Meaning that you have to make transaction to call this function.

And now your question, "where it will cost gas even though it returns early?"

Then answer is YES.

Regardless how quick you return, all "send" or "write" transactions will cost gas.

Now, your title of this thread, "what is use of pure and view?"

well, both pure and view are for the "read" functions. And it will not cost any gas.

You can read more about that, here

  • 2
    Mostly correct, just a few notes: wallet will prevent the transaction if there are not enough funds, so it doesn't cost anything. Also, it is possible to call a non-readonly function as a readonly function, which doesn't cost gas (but also doesn't modify state then). Also, readonly functions will cost gas if they are called as par of a transaction. Feb 27, 2022 at 14:28
  • Thanks for comment. It is interesting to know that we can call non-readonly function as readonly function. I had tried it calling via web3, but it did not work. can you please share some example or doc link which gives code sample of calling write functions as read function? Thanks again for your input :) Feb 28, 2022 at 4:14
  • At least ethers.js allows that, don't know why other libraries wouldn't. But that's basically what eth_estimateGas does to estimate gas usage: runs the same transaction as readonly. It not only detects gas usage, but also detects whether the wannabe-transaction reverts. Feb 28, 2022 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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