Gas Mechanism¶
Introduction to Gas¶
Gas is a unit in the Ethereum network used to measure the computational work required to perform specific operations (such as transaction transfers, smart contract computations, and data storage). It is central to Ethereum's economic model and security mechanism, ensuring the network's security, sustainability, and abuse prevention through a market-based resource pricing mechanism.
Core Roles:
The Triple Role of Gas in Ethereum:
1. Unit of Measurement:
- Measures the computational complexity of operations
- Independent of ETH price fluctuations
- Reflects actual resource consumption
2. Economic Incentive:
- Rewards validators for maintaining the network
- Priority fee bidding mechanism
- Base fee burn (deflationary)
3. Security Mechanism:
- Prevents infinite loops (halting problem)
- Defends against DoS attacks
- Limits state explosion
Historical Evolution:
- 2015: Ethereum mainnet launched, introducing the Gas mechanism
- 2017: Gas Limit increased from 4.7 million to 8 million (to handle the ICO boom)
- August 2021: London upgrade (EIP-1559), introduced base fee burning
- September 2022: Post-Merge transition to PoS, validators replaced miners in receiving Gas fees
- 2024: Dencun upgrade introduced Blob Gas, reducing L2 costs
- 2025: Fusaka upgrade designed Blob count as a parameter-controlled value and set a per-transaction gas cap
Problems to Solve¶
As a decentralized world computer, Ethereum faces two critical resource management problems:
Halting Problem¶
The EVM is a Turing-complete virtual machine that can execute arbitrarily complex computations, and Turing proved that no program can predetermine whether another program (contract code) will halt.
Therefore, malicious or buggy contract code could contain infinite loops, causing nodes to be stuck forever, leading to network paralysis.
Example: Infinite Loop Contract
// ❌ Without Gas limits, this would paralyze the network
contract MaliciousContract {
function attack() public {
while (true) {
// Infinite loop
uint x = 1 + 1;
}
}
}
// Gas mechanism protection:
// - Each loop iteration consumes Gas
// - Transaction automatically terminates when Gas runs out
// - Attacker must pay for consumed Gas
// → Attack is costly and unsustainable
Resource Abuse (Spam Prevention)¶
Problem Scenario:
Scarcity of on-chain resources:
Full Node Storage:
- Each full node stores the complete history
- Current Ethereum state: > 1 TB
- Unlimited growth is unsustainable
Computational Resources:
- Validators must re-execute all transactions
- Complex computations consume CPU
- Affects network throughput
Network Bandwidth:
- Transactions propagate across the P2P network
- Too many transactions cause congestion
Gas Protection Mechanism:
Cost Constraints:
Free Scenario (No Gas):
- Attacker sends 1 million spam transactions
- Cost: 0
- Network paralysis
With Gas Mechanism:
- Each transaction costs at least 21,000 Gas
- 1 million transactions = 21 billion Gas
- Cost (50 gwei): 1,050 ETH ≈ $2M+
- Attack is uneconomical
Core Features¶
Gas Metering Mechanism¶
Opcode Gas Costs:
Each EVM opcode has a predefined Gas cost, reflecting its computational complexity and resource usage.
Common Opcode Gas Cost Table (Post-Shanghai Upgrade):
Arithmetic Operations:
ADD, SUB, MUL, DIV, MOD 3 Gas
ADDMOD, MULMOD 8 Gas
EXP (exponentiation) 10 + 50/byte
Memory Operations:
MLOAD (read memory) 3 Gas
MSTORE (write memory) 3 Gas
MSTORE8 3 Gas
Storage Operations (Most Expensive):
SLOAD (read storage) 2,100 Gas
SSTORE (write storage):
- Zero → Non-zero 20,000 Gas
- Non-zero → Non-zero 5,000 Gas
- Non-zero → Zero (refund) -15,000 Gas
Call Operations:
CALL, CALLCODE 100 Gas (base)
DELEGATECALL, STATICCALL 100 Gas
CREATE (create contract) 32,000 Gas
CREATE2 32,000 Gas
Hash Operations:
SHA3 (keccak256) 30 + 6/byte
Practical Example: Simple Transfer
// ETH Transfer: recipient.transfer(amount)
// Gas Consumption Breakdown:
1. Base transaction cost: 21,000 Gas
2. Calldata cost:
- Zero bytes: 4 Gas/byte
- Non-zero bytes: 16 Gas/byte
- Address (20 bytes): 320 Gas
- Amount (32 bytes): 512 Gas
3. Recipient code execution:
- If EOA: 0 Gas
- If contract (has receive/fallback): 2,300 Gas stipend
Total: approximately 21,000 - 23,300 Gas
EIP-1559 Fee Model¶
Fee Structure:
Transaction Fee = (Base Fee + Priority Fee) × Gas Used
Components:
1. Base Fee:
- Automatically adjusted by the protocol
- Based on block congestion level
- Completely burned
- Does not go to validators
2. Priority Fee (Tip):
- User-defined
- Reward for validators
- Incentivizes priority inclusion
3. Max Fee Per Gas:
- Maximum price the user is willing to pay
- Max Fee = Max Base Fee + Max Priority Fee
4. Max Priority Fee Per Gas:
- Maximum tip the user is willing to pay
Base Fee Dynamic Adjustment Algorithm:
Assumption: Target of 15M Gas per block (elastic cap of 30M)
Adjustment Formula:
New Base Fee = Current Base Fee × (1 + 0.125 × (Parent Gas Used - Target) / Target)
Example:
Current Base Fee: 100 gwei
Previous block Gas Used: 20M (exceeds target of 15M)
New Base Fee = 100 × (1 + 0.125 × (20M - 15M) / 15M)
= 100 × (1 + 0.125 × 0.333)
= 100 × 1.0416
= 104.16 gwei
Rules:
- Full block → Base Fee increases by up to 12.5%
- Empty block → Base Fee decreases by up to 12.5%
- Adjusted every 12 seconds (each block)
Actual Transaction Fee Calculation:
// User Settings:
Max Fee Per Gas: 200 gwei
Max Priority Fee Per Gas: 2 gwei
// Current Network State:
Current Base Fee: 50 gwei
// Actual Fee Calculation:
Actual Base Fee = 50 gwei (current base fee)
Actual Priority Fee = min(2 gwei, 200 - 50) = 2 gwei
Effective Gas Price = 50 + 2 = 52 gwei
// Gas Used: 100,000 Gas
Transaction Fee = 100,000 × 52 gwei
= 5,200,000 gwei
= 0.0052 ETH
// Fee Distribution:
Burned (Base Fee): 100,000 × 50 = 0.005 ETH → Permanently burned
To Validator: 100,000 × 2 = 0.0002 ETH → Validator income
// User Refund:
Max Willing to Pay: 100,000 × 200 = 0.02 ETH
Actual Paid: 0.0052 ETH
Refund: 0.0148 ETH
Gas Limit¶
Transaction Gas Limit:
Definition: The maximum Gas consumption set by the user for a single transaction
Purpose:
1. Prevent accidentally consuming too much Gas
2. Control the upper limit of transaction cost
3. Avoid contract bugs draining funds
If actual consumption < Gas Limit:
- Only the actual consumed Gas is charged
- Remaining Gas is refunded to the user
If actual consumption = Gas Limit:
- Transaction may succeed (just enough)
- Or fail (Out of Gas)
- Consumed Gas is not refunded
Block Gas Limit:
Definition: The maximum total Gas allowed in a single block
Current Settings (late 2025):
- Target: 30,000,000 Gas
- Elastic cap: 60,000,000 Gas
Impact:
- Determines block size
- Limits network throughput
- Affects transaction confirmation time
Gas Limit Estimation Methods:
// Method 1: eth_estimateGas (most common)
const gasEstimate = await provider.estimateGas({
to: contractAddress,
data: encodedFunctionCall
});
// Recommend adding 10-20% buffer
const gasLimit = gasEstimate * 1.2;
Gas Cost Details¶
- Storage costs (most expensive): When necessary, optimize Gas through caching to memory and variable packing
- Memory costs: Linear growth initially, quadratic growth later (to prevent abuse)
- Calldata costs: Cheapest
Event Costs¶
LOG Opcode Costs:
Event Gas Cost = Base Cost + Topic Cost + Data Cost
LOG0 (no topics): 375 Gas
LOG1 (1 topic): 375 + 375 = 750 Gas
LOG2 (2 topics): 375 + 375×2 = 1,125 Gas
LOG3 (3 topics): 375 + 375×3 = 1,500 Gas
LOG4 (4 topics): 375 + 375×4 = 1,875 Gas
Data cost: 8 Gas/byte
Example:
event Transfer(address indexed from, address indexed to, uint256 value);
emit Transfer(0xaaa..., 0xbbb..., 100);
Cost Calculation:
- Base: 375 Gas
- 3 topics (event signature + from + to): 375 × 3 = 1,125 Gas
- Data (value, 32 bytes): 32 × 8 = 256 Gas
Total: 1,756 Gas
Event Optimization:
// ❌ Inefficient: Too many indexed parameters
event IneffientEvent(
address indexed user,
address indexed token,
address indexed spender,
uint256 amount
);
// Cost: 375 + 375×4 + 32×8 = 1,881 Gas
// ✅ Efficient: Balance indexed and data
event EfficientEvent(
address indexed user,
address token, // Not indexed
uint256 amount
);
// Cost: 375 + 375×2 + (20+32)×8 = 1,541 Gas
// Savings: 340 Gas
// Trade-off:
// - indexed parameters: Convenient for off-chain queries (filterable)
// - Non-indexed: Saves Gas, but queries require iteration
Contract Deployment Costs¶
CREATE and CREATE2 Costs:
Deployment Cost = Base Cost + Code Storage Cost + Initialization Cost
Base Cost:
CREATE: 32,000 Gas
CREATE2: 32,000 Gas (same)
Code Storage Cost:
200 Gas/byte
Example:
Contract bytecode size: 10,000 bytes
Cost Calculation:
- Base: 32,000 Gas
- Code storage: 10,000 × 200 = 2,000,000 Gas
- Constructor execution: variable (e.g., 500,000 Gas)
Total: approximately 2,532,000 Gas
Actual Cost (50 gwei):
2,532,000 × 50 gwei = 0.1266 ETH ≈ $250
Practical Cost Examples¶
Example 1: Simple **ERC-20 Transfer**
// ERC20.transfer(recipient, 1000)
Gas Consumption Breakdown:
1. Base transaction cost 21,000 Gas
2. Calldata (68 bytes) ~900 Gas
3. SLOAD balances[sender] 2,100 Gas
4. SLOAD balances[recipient] 2,100 Gas
5. SSTORE balances[sender] 5,000 Gas (modify)
6. SSTORE balances[recipient] 5,000 Gas (modify)
7. Transfer event 1,756 Gas
8. Computation and checks ~500 Gas
Total: approximately 65,000 Gas
Cost (50 gwei):
65,000 × 50 gwei = 0.00325 ETH ≈ $6.5
Example 2: **Uniswap V2 Swap**
// swapExactTokensForTokens
Gas Consumption Breakdown:
1. Base transaction 21,000 Gas
2. Router function call ~2,000 Gas
3. Token A transferFrom 65,000 Gas
4. Pair getReserves (SLOAD ×2) 4,200 Gas
5. Pair swap logic:
- Constant product check ~1,000 Gas
- Reserve update (SSTORE ×2) 10,000 Gas
- Sync event 1,756 Gas
6. Token B transfer to user 65,000 Gas
7. Other computations and checks ~5,000 Gas
Total: approximately 175,000 Gas
Cost (50 gwei):
175,000 × 50 gwei = 0.00875 ETH ≈ $17.5
Gas Optimization Techniques¶
Read: Gas Optimization Handbook
Key Features¶
- Decentralized Pricing: Does not rely on centralized institutions, but determines resource prices dynamically through market supply and demand and protocol algorithms.
- Deflationary Mechanism: The Base Fee burn mechanism introduced by EIP-1559 means that during high network activity, the amount of ETH burned may exceed the issuance amount, achieving deflation.
- Fine-Grained Control: Different operations (compute-intensive vs. storage-intensive) are priced differently based on their resource consumption on nodes.
Recommended Reading¶
- Gas Optimization Handbook - Systematic Gas optimization techniques
- EIP-1559: Fee market change for ETH 1.0 chain - Complete EIP-1559 specification
- EVM Opcodes Gas Costs - Complete EVM opcode Gas cost table
- Ethereum Gas Tracker - Real-time Gas price monitoring
- EIP-2929: Gas cost increases for state access opcodes - Cold/hot access mechanism
- EIP-2200: Structured Definitions for Net Gas Metering - SSTORE Gas cost optimization
Related Concepts¶
- Gwei: Common unit for Gas price, 1 Gwei = \(10^{-9}\) ETH
- Wei: Ethereum's smallest unit, 1 ETH = \(10^{18}\) Wei
- Gas Limit (Transaction): Maximum Gas allowed for a single transaction
- Gas Limit (Block): Maximum total Gas allowed in a single block, determines block size
- Base Fee: Base fee introduced by EIP-1559, dynamically adjusted and burned
- Priority Fee: Priority fee/tip, rewarded to validators
- EIP-1559: Fee market reform introduced in the London upgrade
- Out of Gas: Transaction failure due to Gas exhaustion
- Gas Refund: Some operations (such as storage clearing) can receive Gas refunds
- MEV (Maximal Extractable Value): Additional revenue validators extract by reordering transactions
- EVM (Ethereum Virtual Machine): Virtual machine that executes smart contracts
- Opcode: EVM operation codes, each with a fixed Gas cost
- SLOAD/SSTORE: Storage read/write operations, the most expensive
- Calldata: Transaction input data
- Block Gas Target: Target block Gas usage (15M)