🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

EVM Deep Dive

Ethereum Deep DiveđŸŸĸ Free Lesson

EVM Deep Dive

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 ArchitectureExecution 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

OpcodeGasDescriptionStack Effect
POP2Remove top item[a] → []
DUP1-163Duplicate item[a] → [a, a]
SWAP1-163Swap top two items[a, b] → [b, a]
PUSH1-323Push data to stack[] → [data]
MLOAD3Load from memory[offset] → [value]
MSTORE3Store to memory[offset, value] → []
SLOAD2100/100Load from storage[key] → [value]
SSTORE5000-20000Store to storage[key, value] → []

Arithmetic Operations

OpcodeGasDescription
ADD3a + b
SUB3a - b
MUL5a × b
DIV5a / b
SDIV5Signed division
MOD5a % b
ADDMOD8(a + b) % n
MULMOD8(a × b) % n
EXP10 + 50×byte_sizea^b
SIGNEXTEND5Extend sign bit

Comparison & Bitwise

OpcodeGasDescription
LT3a < b
GT3a > b
SLT3Signed a < b
SGT3Signed a > b
EQ3a == b
ISZERO3a == 0
AND3a & b
OR3a | b
XOR3a ^ b
NOT3~a
BYTE3a[i]
SHL3a << b
SHR3a >> b
SAR3a >> b (arithmetic)

Memory, Storage, and Calldata

Memory ModelMemory (RAM)â€ĸ Volatile (cleared per call)â€ĸ Byte-addressableâ€ĸ Grows dynamicallyâ€ĸ Cost: 3 gas + expansionâ€ĸ Max: 256 MB practicalâ€ĸ Used for: intermediatesStorage (HDD)â€ĸ Persistent (contract-level)â€ĸ 2^256 slotsâ€ĸ 32-byte valuesâ€ĸ Cost: 2100/100 (cold/warm)â€ĸ Writes: 5000-20000 gasâ€ĸ Used for: state variablesCalldata (ROM)â€ĸ Read-only inputâ€ĸ Provided by callerâ€ĸ Cost: 4 gas per wordâ€ĸ No expansion costâ€ĸ Used for: function argsâ€ĸ Efficient for dataStorage 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

TierOpcodesGasRationale
ZeroSTOP, RETURN0No computation
BaseADD, SUB, PUSH2-3Simple operations
Very LowAND, OR, XOR3Bitwise ops
LowMUL, DIV, MOD5Arithmetic
MidADDBIG, MULMOD8Complex arithmetic
HighEXP, BYTE10-50Exponentiation
Very HighSHA330+6/wordHashing
SLOAD (cold)SLOAD2100First access
SLOAD (warm)SLOAD100Subsequent access
SSTORESSTORE5000-20000State writes
CreateCREATE32000Contract creation
CallCALL700External calls

Gas Refund Rules

python
# 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

python
# 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

python
# 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

FeatureCREATECREATE2
Address Derivationsender + noncesender + salt + init_code
DeterministicNoYes
PredictabilityLowHigh
Use CaseRegular deploymentCounterfactual deployment
Gas Cost32,00032,000
Refund on Failure21,00021,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 SwitchingProxy ContractStorage: A, B, CCode: delegatecallmsg.sender: Useraddress(this): ProxyImplementation ContractStorage: (ignored)Code: logicmsg.sender: Useraddress(this): ProxyCode 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

VariantChainFeatures
EVM (Mainnet)EthereumFull opcodes
EVM (Cancun)EthereumBlob support
Arbitrum VMArbitrumArbOS precompiles
Optimism VMOptimismOVM 2.0
zkEVMPolygon zkEVMZK-provable execution
Scroll zkEVMScrollZK-provable execution
BNB Chain EVMBSCEVM-compatible
Avalanche C-ChainAvalancheEVM-compatible
Polygon PoSPolygonEVM-compatible
FantomFantomEVM-compatible

zkEVM Comparison

TypeProving SpeedCompatibilityExample
Type 1SlowFullEthereum L1 (research)
Type 2MediumHighScroll, Polygon zkEVM
Type 3FastMediumSome opcodes modified
Type 4Very FastLowCustom languages

Real-World Gas Optimization

Common Optimizations

OptimizationGas SavedTechnique
Storage Packing5,000-20,000Pack multiple variables in one slot
Short-circuitingVariableEvaluate cheap conditions first
Cached Storage2,000-5,000Use memory for repeated reads
Immutable Variables2,100/callReplace SLOAD with PUSH
Custom Errors50+Replace require strings with errors
AssemblyVariableDirect 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

FeatureEVMWASM
MaturityHighGrowing
ToolingExcellentGood
Gas EfficiencyMediumHigh
Security AuditExtensiveLimited
AdoptionDominantEmerging
Compilation TargetSolidityRust, C++, Go

Memory vs Storage vs Calldata

AspectMemoryStorageCalldata
PersistencePer-callPermanentPer-call
Read Cost3 gas100-2100 gas4 gas/word
Write Cost3 gas5000-20000 gasN/A
Use CaseIntermediatesStateInput data
GrowthDynamicFixed slotsFixed

Interview Questions

  1. 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).
  2. 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.
  3. 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

  1. What is the maximum depth of the EVM stack?

    • A) 256
    • B) 1024 ✓
    • C) 65536
    • D) Unlimited
  2. Which opcode provides deterministic contract addresses?

    • A) CREATE
    • B) CREATE2 ✓
    • C) DELEGATECALL
    • D) STATICCALL
  3. 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

  1. Implement a simple EVM interpreter in Python (stack machine)
  2. Optimize a Solidity contract for gas efficiency
  3. Build a gas estimator for common operations
  4. Compare gas costs across EVM variants
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement