5

In this answer, it was stated:

You wouldn't want to iterate over the voters in the contract in any case because that would put an upper bound on the number of voters before the system stops working - due to rising transaction cost hitting the block gas limit.

I'm a little confused by this. Aren't read operations gas-free? So if I call a function that iterates through a long list and perform basic calculations, how can this cause transaction costs to hit the gas limit? In some tests on remix, long for loops seem to slow things down, but don't cost the sender any gas:

    function checkAllCounts() public view returns (uint) {
    uint total = 0;
    for (uint i; i<addresses.length; i++) {
        address _address = addresses[i];
        total += counts[_address];
    }
    return total;
}

I'm sure I'm missing something. What's stopping someone writing a malicious contract that slows down the EVM with a broken loop?

1 Answer 1

5

There are to types of contract interactions: real transactions and local static calls. Real transactions always cost gas (even when they call view functions), local static calls do not cost gas.

The difference is that transactions are sent to the blockchain and they are processed by the whole blockchain. But local static calls are only issued to the node you use, and the data is only read from the node - the call is not propagated to the rest of the blockchain.

So, if you want to abuse your local node (or whichever node provider you use) with lots of calls and/or lots of looping, feel free to do so, but it only hurts your own node.

5
  • So, function calls on the javascript VM will always be treated as local static calls? To be honest, now I'm really confused because it seems like gas-free view functions happen all of the time. I can't recall a time where I've ever been asked to pay gas to, e.g. view my staking balance in a DAPP. What am I missing here? Commented Jan 29, 2022 at 19:08
  • Yes, all read-only calls are gas free, such as checking balance. I'm quite sure Remix uses 'real' transaction also in the JS VM: you'll see your address balance go down. Commented Jan 29, 2022 at 19:56
  • You said above "Real transactions always cost gas (even when they call view functions)". Is a view function not by definition read-only? Commented Jan 30, 2022 at 3:39
  • They are free only if called statically. Anything you do in a transaction costs. Commented Jan 30, 2022 at 7:14
  • Gotcha. I'd be interested to know more about the theoretical limitations on how much processing power can be used per block and the mechanisms through which these resources are shared. Can you recommend any good resources? Commented Jan 30, 2022 at 13:11

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.