⛽ Gas Metering: Why Every Operation Costs Money

Learn why the EVM charges gas for computation and storage

Previous
EVM Components

⛽ Gas & Execution

Gas is the fuel for computation on Ethereum. Every EVM operation costs gas to prevent spam and infinite loops. You pay miners/validators for executing your code!

💡 Why Gas Exists

🛡️

Prevent Spam

Without gas, attackers could spam network with infinite loops. Gas makes attacks expensive!

💰

Incentivize Validators

Validators get paid in gas fees. This incentivizes them to include your transaction.

⚖️

Fair Resource Allocation

Complex operations cost more. Simple transfers are cheap. Pay for what you use!

🎯

Deterministic Limits

Block gas limit (30M gas) caps computation per block. Prevents network overload.

🎮 Interactive: Gas Calculator

Adjust gas price and see how operation complexity affects cost

10 Gwei (cheap)200 Gwei (expensive)

Simple Transfer

Basic ETH transfer between addresses

Operations Performed:
Transfer ETH
Update balance
Gas Used
21,000
Cost in ETH
0.001050
Cost in USD
$2.10

📊 Operation Gas Costs

OperationOpcodeGas Cost
AdditionADD3
MultiplicationMUL5
Read storageSLOAD2,100
Write storage (new)SSTORE20,000
Write storage (update)SSTORE5,000
Call contractCALL700+
Create contractCREATE32,000+
Log eventLOG0375+

🔍 Gas Limit vs Gas Price

Gas Limit

Maximum gas you're willing to spend.

Set too low:
Transaction fails, you lose gas
Set too high:
Unused gas is refunded

Gas Price

How much you pay per unit of gas (in Gwei).

Set low (10 Gwei):
Slow confirmation
Set high (100+ Gwei):
Fast confirmation

💡 Gas Optimization Tips

1️⃣
Minimize Storage Writes
SSTORE is 20,000 gas! Use memory for temporary data. Batch updates when possible.
2️⃣
Use Events for Logs
Events (LOG) are much cheaper than storage. Don't store data you only need off-chain.
3️⃣
Pack Variables
Store multiple small variables in one 32-byte slot. uint8 + uint8 = one SSTORE instead of two.
4️⃣
Avoid Loops
Loops = multiple operations. Unbounded loops can exceed block gas limit. Use pagination.
5️⃣
Delete Unused Storage
Setting storage to zero refunds gas! Clean up old data for partial refunds.

⚠️ Out of Gas Errors

What happens when gas runs out:

❌ Transaction Reverts
All state changes are undone. Contract returns to pre-transaction state.
💸 Gas is NOT Refunded
You still pay for the gas used before failure. Validators did computational work!
🛡️ Protection Mechanism
Prevents infinite loops from blocking the network. Set gas limit wisely!

🎯 Real Example: NFT Mint

Operation Breakdown:
Base transaction cost21,000 gas
Update owner mapping (SSTORE)20,000 gas
Update token ID counter (SSTORE)5,000 gas
Emit Transfer event (LOG)1,500 gas
Function logic (misc opcodes)2,500 gas
Total Gas Used~50,000 gas
At 50 Gwei gas price:
0.0025 ETH = $5.00