Let's say I have a smart contract with branch, where each branch has a different number of operations.
if (someCondition) {
// do operations costing 10 gas
} else {
//do operations costing 100 gas
}
When a user goes to call this function from their client, say metamask, how do they know how much gas their transaction will cost? Do they just have to guess and include enough gas for the most expensive path?
The client app is almost always able to calculate the gas usage. Either by running their own EVM emulator, or by querying an external API that emulates the transaction and returns the result.
All blockchain data is publicly available for reading (even values of private properties - just not with Solidity, but with using more low-level approach and querying the storage slots), and the gas cost of each operation is predetermined.
So the client knows, that the transaction is going to
And it also knows that one MLOAD
costs 3 gas, one SSTORE
costs 5,000 gas, etc.
It can use all this data to calculate the final cost.
The exception is when the decision tree is based on block data such as block.timestamp
, that is unknown beforehand. Then it depends on the client, but my guess is that most suggest the most expensive combination, so that they lower the risk of having the transaction reverted due to insufficient gas.
Example:
if (block.timestamp % 2 == 0) {
// even second, do operations costing 10 gas
} else {
// odd second, do operations costing 100 gas
}