1

I have a function:

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

    balances[msg.sender] -= value;
}

*note: the above is for illustrative purposes only. Security and safe maths is not a concern.

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).

2 Answers 2

0

If no transaction is made then there is no fee; however, since there is no transaction, the balances[msg.sender] update wont be saved to the state.

0

You are conflating two issues.

You can .call() it, or you can send a transaction to it. If you call it, the client is explicitly asking for a read-only execution model. That will not cost gas (regardless of the contract), but it cannot possibly alter the state of the contract even though assigning a new value to balances[msg.sender] was rehearsed/evaluated. Nothing was sent to the chain, so no accounting changes and no persistent effects. Ergo, that doesn't cost gas.

That may seem cryptic, so have a look over here for a (hopefully) better introduction to this foundation: https://blog.b9lab.com/calls-vs-transactions-in-ethereum-smart-contracts-62d6b17d0bc2

If you send a transaction, then the contract may or may not have a reason to change the sender's balance. Either way, it costs gas. If (balances[msg.sender] < value) it returns. Even though nothing happened, it still costs gas because the EVM had to:

  • Unpack the transaction
  • Unpack the arguments
  • Find the contract bytecode
  • Find the function
  • Pass the arguments in
  • Run the comparison
  • Decide what to do next
  • Return

These are compute activities that will be performed by every full node on the network to find out what that transaction did (which is, effectively nothing). The compiler composes bytecode from the source and the EVM runs it (each node runs it ot reach eventual agreement with the other nodes). Gas pays for running it.

It is true that SSTORE is the most expensive OPCODE (Write something into persistent storage) but the rest also has costs. So, the "do nothing" case would have a negligible (but not zero) cost, and the "do something" case would have a higher cost owing to the comparatively high cost of writing something to storage.

Hope it helps.

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.