EVM opcodes, gas mechanics, memory/storage/calldata, contract creation, DELEGATECALL, CREATE2, and EVM variants.
Overview
The Ethereum Virtual Machine (EVM) is the runtime environment for smart contracts. Understanding its internals is crucial for gas optimization and security.
EVM Architecture
EVM Architecture Execution Environment âĸ PC (Program Counter) âĸ Gas Available âĸ Stack (1024 max depth) âĸ Memory (byte array) âĸ Storage (key-value store) âĸ Calldata (read-only input) Execution Context âĸ Address (current contract) âĸ Sender (msg.sender) âĸ Value (msg.value) âĸ Data (calldata) âĸ Code (bytecode) âĸ Depth (call depth ⤠1024) Opcodes: ~140 opcodes | EVM Version: Cancun (2024) Key Differences from Traditional VMs âĸ Gas metering (every opcode costs gas) | âĸ No overflow protection (checked in Solidity) âĸ Stack-based (not register-based) | âĸ 256-bit word size | âĸ Deterministic execution
Core Opcodes
Stack Operations
Opcode Gas Description Stack Effect POP 2 Remove top item [a] â [] DUP1-16 3 Duplicate item [a] â [a, a] SWAP1-16 3 Swap top two items [a, b] â [b, a] PUSH1-32 3 Push data to stack [] â [data] MLOAD 3 Load from memory [offset] â [value] MSTORE 3 Store to memory [offset, value] â [] SLOAD 2100/100 Load from storage [key] â [value] SSTORE 5000-20000 Store to storage [key, value] â []
Arithmetic Operations
Opcode Gas Description ADD 3 a + b SUB 3 a - b MUL 5 a à b DIV 5 a / b SDIV 5 Signed division MOD 5 a % b ADDMOD 8 (a + b) % n MULMOD 8 (a à b) % n EXP 10 + 50Ãbyte_size a^b SIGNEXTEND 5 Extend sign bit
Comparison & Bitwise
Opcode Gas Description LT 3 a < b GT 3 a > b SLT 3 Signed a < b SGT 3 Signed a > b EQ 3 a == b ISZERO 3 a == 0 AND 3 a & b OR 3 a | b XOR 3 a ^ b NOT 3 ~a BYTE 3 a[i] SHL 3 a << b SHR 3 a >> b SAR 3 a >> b (arithmetic)
Memory, Storage, and Calldata
Memory Model Memory (RAM) âĸ Volatile (cleared per call) âĸ Byte-addressable âĸ Grows dynamically âĸ Cost: 3 gas + expansion âĸ Max: 256 MB practical âĸ Used for: intermediates Storage (HDD) âĸ Persistent (contract-level) âĸ 2^256 slots âĸ 32-byte values âĸ Cost: 2100/100 (cold/warm) âĸ Writes: 5000-20000 gas âĸ Used for: state variables Calldata (ROM) âĸ Read-only input âĸ Provided by caller âĸ Cost: 4 gas per word âĸ No expansion cost âĸ Used for: function args âĸ Efficient for data Storage is most expensive â Memory is cheaper â Calldata is cheapest
Memory Expansion Cost
Where
Storage Layout
contract StorageLayout {
uint256 a; // slot 0
uint256 b; // slot 1
uint128 c; // slot 2 (packed with d)
uint128 d; // slot 2
uint256[] e; // slot 3 (length), keccak256(3) + i (elements)
mapping(uint => uint) f; // slot 4, keccak256(key . 4) (value)
}
Gas Mechanics
Gas Cost Tiers
Tier Opcodes Gas Rationale Zero STOP, RETURN 0 No computation Base ADD, SUB, PUSH 2-3 Simple operations Very Low AND, OR, XOR 3 Bitwise ops Low MUL, DIV, MOD 5 Arithmetic Mid ADDBIG, MULMOD 8 Complex arithmetic High EXP, BYTE 10-50 Exponentiation Very High SHA3 30+6/word Hashing SLOAD (cold) SLOAD 2100 First access SLOAD (warm) SLOAD 100 Subsequent access SSTORE SSTORE 5000-20000 State writes Create CREATE 32000 Contract creation Call CALL 700 External calls
Gas Refund Rules
# Storage clearing refunds
SSTORE_SET â SSTORE_RESET: 4800 gas refund
SSTORE_SET â SSTORE_CLEAR: 19800 gas refund
SSTORE_RESET â SSTORE_CLEAR: 4800 gas refund
# Max refund: 20% of gas used (post-EIP-3529)
max_refund = gas_used // 5
Contract Creation
CREATE Opcode
# CREATE: address = keccak256(rlp(sender, nonce))[12:]
sender = "0x1234..."
nonce = get_nonce(sender)
address = keccak256(rlp(sender, nonce))[12:]
# Contract code execution
init_code = calldata # Constructor code
ret = evm_execute(init_code, value, gas)
runtime_code = ret # Stored at address
CREATE2 Opcode
# CREATE2: address = keccak256(0xff + sender + salt + keccak256(init_code))[12:]
sender = "0x1234..."
salt = "0x0000...0001" # 32 bytes
init_code = constructor_bytecode
address = keccak256(
0xff +
sender +
salt +
keccak256(init_code)
)[12:]
# Deterministic: same sender + salt + init_code = same address
CREATE vs CREATE2
Feature CREATE CREATE2 Address Derivation sender + nonce sender + salt + init_code Deterministic No Yes Predictability Low High Use Case Regular deployment Counterfactual deployment Gas Cost 32,000 32,000 Refund on Failure 21,000 21,000
DELEGATECALL
CALL vs DELEGATECALL vs STATICCALL
// CALL: Execute code in context of target
(bool success, bytes memory data) = target.call{value: msg.value}(data);
// msg.sender = caller | storage = target's
// DELEGATECALL: Execute code in context of caller
(bool success, bytes memory data) = target.delegatecall(data);
// msg.sender = original caller | storage = caller's
// STATICCALL: Read-only execution
(bool success, bytes memory data) = target.staticcall(data);
// Cannot modify state
DELEGATECALL Context
DELEGATECALL Context Switching Proxy Contract Storage: A, B, C Code: delegatecall msg.sender: User address(this): Proxy Implementation Contract Storage: (ignored) Code: logic msg.sender: User address(this): Proxy Code runs from Implementation, Storage written to Proxy
Proxy Pattern Example
contract Proxy {
address public implementation;
uint256 public value; // Storage slot matches implementation
fallback() external payable {
address impl = implementation;
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
EVM Variants
Variant Chain Features EVM (Mainnet) Ethereum Full opcodes EVM (Cancun) Ethereum Blob support Arbitrum VM Arbitrum ArbOS precompiles Optimism VM Optimism OVM 2.0 zkEVM Polygon zkEVM ZK-provable execution Scroll zkEVM Scroll ZK-provable execution BNB Chain EVM BSC EVM-compatible Avalanche C-Chain Avalanche EVM-compatible Polygon PoS Polygon EVM-compatible Fantom Fantom EVM-compatible
zkEVM Comparison
Type Proving Speed Compatibility Example Type 1 Slow Full Ethereum L1 (research) Type 2 Medium High Scroll, Polygon zkEVM Type 3 Fast Medium Some opcodes modified Type 4 Very Fast Low Custom languages
Real-World Gas Optimization
Common Optimizations
Optimization Gas Saved Technique Storage Packing 5,000-20,000 Pack multiple variables in one slot Short-circuiting Variable Evaluate cheap conditions first Cached Storage 2,000-5,000 Use memory for repeated reads Immutable Variables 2,100/call Replace SLOAD with PUSH Custom Errors 50+ Replace require strings with errors Assembly Variable Direct opcode manipulation
Storage Packing Example
// Bad: 3 storage slots
struct Bad {
uint128 a; // slot 0
uint256 b; // slot 1
uint128 c; // slot 2
}
// Good: 2 storage slots
struct Good {
uint128 a; // slot 0
uint128 c; // slot 0 (packed)
uint256 b; // slot 1
}
Trade-offs
EVM vs WASM
Feature EVM WASM Maturity High Growing Tooling Excellent Good Gas Efficiency Medium High Security Audit Extensive Limited Adoption Dominant Emerging Compilation Target Solidity Rust, C++, Go
Memory vs Storage vs Calldata
Aspect Memory Storage Calldata Persistence Per-call Permanent Per-call Read Cost 3 gas 100-2100 gas 4 gas/word Write Cost 3 gas 5000-20000 gas N/A Use Case Intermediates State Input data Growth Dynamic Fixed slots Fixed
Interview Questions
Why does EVM use 256-bit words instead of standard 32-bit integers?
Answer: 256-bit enables native hashing (keccak256), large number arithmetic for financial calculations, and efficient address handling (20-byte addresses fit in one word).
How does DELEGATECALL prevent storage collision between proxy and implementation?
Answer: Storage layout must match exactly. Proxy stores implementation address in a specific slot that doesn't collide with implementation's storage slots.
What is the gas refund mechanism and why was EIP-3529 needed?
Answer: Refunds incentivize clearing storage. EIP-3529 reduced max refund from 50% to 20% of gas used because high refunds were enabling gas manipulation attacks.
Quiz Questions
What is the maximum depth of the EVM stack?
A) 256
B) 1024 â
C) 65536
D) Unlimited
Which opcode provides deterministic contract addresses?
A) CREATE
B) CREATE2 â
C) DELEGATECALL
D) STATICCALL
What is the gas cost of SSTORE from zero to non-zero?
A) 5,000
B) 15,000
C) 20,000 â
D) 30,000
Practice
Implement a simple EVM interpreter in Python (stack machine)
Optimize a Solidity contract for gas efficiency
Build a gas estimator for common operations
Compare gas costs across EVM variants