I know similar questions have been asked before however I could not find an good explanation for the following,
In one of the tutorial it says:
Pure and View functions don't cost any gas to call if they're called
externally from outside the contract. But they do cost gas if called
internally by another function.
- Why do they need gas if they don't update anything?
- How does read cost gas?
- Isn't it read from my local blockchain?
Best Answer
As I understand,
In this type of case, there won't be any transaction initiated because this will be like just querying the blockchain for its current state and nothing will be changed.
This means there's already a transaction to change the state of the blockchain, and that process of changing state need to use that pure function, say for calculations. Gas cost for a transaction depends on the number of EVM opcodes executed while completing it, so executing that pure function is also within that set of opcodes. That's why it's said that it costs gas.
Consider the following contract:
Just calling
addNumbers
won't cost anything. But callingupdateState
will cost including cost toaddNumbers(a,b)
as well. CallingaddThreeNumbers
won't cost gas even if it calledaddNumbers
internally since no transaction is needed throughout the function call.