2

Lets say that I have a view function that has a loop and that I must use this loop. This loop is calling another view function to verify some data per index key.

The view function is free to execute without getting charged for a GAS.

For example, this works

function retrieve() public pure returns (uint256){
    uint256 ret = 0;
    for(uint t=0;t<1000;t++){
        ret = t;
    }
    return ret;
}

However, this does not work

    function retrieve() public pure returns (uint256){
        uint256 ret = 0;
        for(uint t=0;t<1000000000000;t++){
            ret = t;
        }
        return ret;
    }
}

How many times can I iterate this kind of a loop in a view ? In other words, what is the maximum number between 1000 and 1000000000000 (see the code example above) that I can use and make the loop work ? How is this number determined ?

Edit: I was able to make 15000 iterations on a testnet but not 20000, so I would limit it to just 10000 iterations as a max, assuming it is just calling the index and verifying the value (and use try-catch if possible). Regardless, I still don't know what determines the number, and how it is determined.

2 Answers 2

1

Although the view function which only runs on a single full node that you connect to does not cost gas, it has the gas limit as well. Because malicious user can consume the full node computation resources just like what you did.

0

Just to make sure: view and pure functions are gas-free only if called locally. If they are called as part of a transaction, they cost gas normally. The reason local (read-only) calls are for free is that it only consumes your node's resources (or whoever provides you the node) - it doesn't get propagated to the blockchain and nobody else can abuse the resources.

I'm actually not sure if locally called view functions need to obey the same gas limits as transactions. Regardless, if they do, you could just get all of the data and do the processing locally. But if they need to obey the gas limits, then that's the limit you are probably hitting (assuming you are calling it locally). For mainnet, the gas limit is currently around 15 million - for other networks it varies.

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.