Previous Module
Security Best Practices Game

⛽ Gas Analysis: Profile & Optimize

Learn how to identify gas-hungry operations

Debug failed transactions and trace execution

⛽ Gas Profiling & Optimization

Out of gas failures waste user money. Transaction runs, consumes gas, then reverts because gas limit too low. User pays for all gas used—gets nothing. Worse, high gas costs make your dApp unusable (who wants to pay $50 for a simple transfer?). Gas profiling identifies expensive operations: unbounded loops, repeated storage writes, inefficient algorithms. Tenderly Gas Profiler shows gas per line of code. Hardhat gas reporter benchmarks function costs during tests. This section teaches you to profile gas usage, identify hotspots (storage writes cost 20,000 gas!), and optimize code to reduce costs by 50-90%.

🎮 Interactive: Gas Cost Calculator

Adjust loop iterations and storage writes to see real-time gas cost calculations. Understand which operations are expensive.

10
150100
5
11020

⚡ Gas Breakdown

Base Transaction21,000 gas
Loop Operations (10 × 500)+5,000 gas
Storage Writes (5 × 20000)+100,000 gas
Total Gas126,000
💸 Cost Estimate
@ 20 gwei:$5.04
@ 50 gwei:$12.60
@ 100 gwei:$25.20
⚠️ Optimization Tips
  • • Storage writes are 100x more expensive than memory operations
  • • Loops over unbounded arrays can easily exceed block gas limit (30M)
  • • Pack storage variables to reduce SSTORE operations
  • • Use events instead of storage for historical data
  • • Batch operations to amortize base transaction cost

📊 EVM Operation Costs

OperationGas CostDescription
ADD/SUB/MUL3Basic arithmetic operations
DIV/MOD5Division and modulo
SLOAD2,100Read from storage (warm)
SSTORE (zero→non-zero)20,000Write to empty storage slot
SSTORE (non-zero→non-zero)5,000Update existing storage
SSTORE (non-zero→zero)5,000Delete storage (refund 15000)
LOG0375Emit event (no topics)
LOG41,500Emit event (4 topics)
CALL700External call (warm address)
CREATE32,000Deploy contract

🛠️ Gas Profiling Tools

Tenderly Gas Profiler

Paste transaction hash → See gas usage per line of code. Visual heatmap shows expensive operations.

1. Go to tenderly.co
2. Paste tx hash
3. Click "Gas Profiler"
4. See per-line costs
Hardhat Gas Reporter

Plugin that shows gas usage for each test. Benchmark function costs during development.

npm install --save-dev
hardhat-gas-reporter

// hardhat.config.js
gasReporter: { enabled: true }

⚡ Optimization Strategies

1. Storage Packing

Pack multiple variables into single storage slot (256 bits)

// Bad: 3 storage slots
uint256 a;
uint128 b;
uint128 c;

// Good: 2 storage slots (saves ~20k gas)
uint256 a;
uint128 b;
uint128 c; // packed with b
2. Memory Instead of Storage

Use memory for temporary data, storage only for persistent state

// Bad: 5 storage writes (100k gas)
for (uint i = 0; i < 5; i++) {
  tempArray[i] = i; // SSTORE
}

// Good: 5 memory writes (500 gas)
uint[] memory temp = new uint[](5);
for (uint i = 0; i < 5; i++) {
  temp[i] = i; // MSTORE
}
3. Batch Operations

Single transaction with array parameter beats N separate transactions

// Bad: N transactions × 21k gas base = 210k for 10 calls
transfer(user1, 100)
transfer(user2, 100)
...

// Good: 1 transaction base + processing = ~50k total
batchTransfer([user1, user2, ...], [100, 100, ...])
4. Short-Circuit Logic

Put cheap checks first, expensive checks last (AND/OR short-circuits)

// Bad: Always checks balance (2100 gas)
require(balanceOf[msg.sender] >= amount && amount > 0)

// Good: Checks cheap condition first, skips balance if amount=0
require(amount > 0 && balanceOf[msg.sender] >= amount)