How does the view function getPrice consume no gas? #57
-
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I think the computation is done during the process of deploying the contract. So, when you call the function getPrice, it only reading a value that is already determined. |
Beta Was this translation helpful? Give feedback.
-
SummaryIf you don't modify the state of the blockchain, it won't cost any gas. Reading from the blockchain (even reading with some math) is really easy for nodes to do. I think this post explains it well. Additional informationGas is applied when you modify the state of the smart contract, thereby modifying the entire blockchain. If you're simply reading from off-chain and doing some math on it, that won't cost any gas. Only if you modify the state of the contract, it'll cost gas. To add to this, if pure/view functions are called externally (which is the case in our getPrice function), it won't cost any gas, but if you called getPrice from an internal function that updates the state of the chain, then gas will be applicable on both functions, internal as well as pure/view. Patrick Edit: This means that when you call it off-chain, the execution happens wherever your node is running. You make a request to "read" some value, and the node "reads" it, and gives you what the return value is. So if you're using Alchemy, Alchemy does the computation. If you're using ganache, the ganache application does the computation. So yes, they are doing computation "for free" by reading, but they are not modifying the state of the blockchain, which computationally is MUCH cheaper. Additionally, this is why it's so important to make sure only people you want to have access to your node have access, otherwise too many people might make API calls to your node! |
Beta Was this translation helpful? Give feedback.
Summary
If you don't modify the state of the blockchain, it won't cost any gas. Reading from the blockchain (even reading with some math) is really easy for nodes to do.
I think this post explains it well.
https://ethereum.stackexchange.com/questions/52885/view-pure-gas-usage-cost-gas-if-called-internally-by-another-function/52887#52887
Additional information
Gas is applied when you modify the state of the smart contract, thereby modifying the entire blockchain. If you're simply reading from off-chain and doing some math on it, that won't cost any gas. Only if you modify the state of the contract, it'll cost gas.
To add to this, if pure/view functions are called externally (which is the c…