Skip to main content

> cat ./posts/evm-deep-dive.md

[terminal_mode]
cat: Blockchain Development|date: 2018-10-01|rt: 5 min

EVM Deep Dive: Understanding the Ethereum Virtual Machine Architecture

Comprehensive deep dive into EVM architecture covering opcodes, gas mechanics, storage patterns, call data handling, bytecode optimization, EIP standards, alternative EVM-compatible chains, and the ecosystem of tools supporting EVM development.

#evm#ethereum#virtual-machine#bytecode#solidity

The Ethereum Virtual Machine (EVM) represents a cornerstone of modern blockchain architecture, providing a standardized execution environment for smart contracts across numerous networks. Understanding the EVM's internals enables developers to write more efficient contracts, debug complex issues, and architect systems leveraging Ethereum's unique capabilities. This comprehensive examination covers every critical aspect of EVM architecture and operation.

The EVM's design reflects careful trade-offs between flexibility, security, and determinism. As a quasi-Turing complete machine operating on a blockchain, the EVM enables arbitrary computations while maintaining network consensus through predictable execution and state transitions.

EVM Architecture Overview

Stack-Based Execution Model

The EVM operates as a stack-based virtual machine with a 1024-item maximum stack depth. Each stack item is a 256-bit word (32 bytes), matching Ethereum's native word size. This 256-bit architecture enables efficient cryptographic operations and arithmetic on large values.

┌─────────────────────────────────────────────────────────────────┐ │ EVM ARCHITECTURE │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ CALL DATA (Calldata) │ │ │ │ - Function selector (4 bytes) │ │ │ │ - Encoded arguments │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ PROGRAM COUNTER (PC) │ │ │ │ - Tracks current execution position │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ STACK (1024 items) │ │ │ │ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ... │ │ │ │ │ 256 │ │ 256 │ │ 256 │ │ 256 │ │ 256 │ │ │ │ │ │ bit │ │ bit │ │ bit │ │ bit │ │ bit │ │ │ │ │ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ MEMORY (Byte-addressable) │ │ │ │ - Volatile, byte-addressable array │ │ │ │ - Expands in 32-byte chunks │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ STORAGE (Persistent) │ │ │ │ - Key-value store, 256-bit to 256-bit │ │ │ │ - Most expensive operation │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘

Memory and Storage Distinction

The EVM maintains distinct data locations, each with different characteristics:

  • Stack: Free to use, limited to 1024 items, volatile
  • Memory: Byte-addressable, expands in 32-byte chunks, volatile
  • Storage: Key-value store, persistent, most expensive
  • Calldata: Immutable function input data, most gas-efficient for read

Opcodes Reference

Arithmetic and Logical Operations

Opcodes define the EVM's instruction set. Arithmetic operations include ADD, SUB, MUL, DIV, MOD, and variants for signed integers (SDIV, SMOD). Logical operations include AND, OR, XOR, NOT for bitwise manipulation.

OpcodeGas CostDescription
ADD3Integer addition
MUL5Integer multiplication
SUB3Integer subtraction
DIV5Unsigned division
MOD5Modulo operation
ADDMOD8Add modulo
MULMOD8Multiply modulo
AND3Bitwise AND
OR3Bitwise OR
XOR3Bitwise XOR
NOT3Bitwise NOT
SHL3Shift left
SHR3Logical shift right
SAR3Arithmetic shift right

Environmental Information

These opcodes provide context about the execution environment:

SOLIDITY
// These opcodes enable various environment queries // GASPRICE (2 gas): Current transaction gas price // COINBASE (2 gas): Current block miner address // TIMESTAMP (2 gas): Current block timestamp // NUMBER (2 gas): Current block number // DIFFICULTY (2 gas): Current block difficulty // GASLIMIT (2 gas): Current block gas limit // CHAINID (2 gas): Current chain ID // BASEFEE (2 gas): Current block base fee (EIP-1559)

Block Information Opcodes

SOLIDITY
// Example: Random number generation using block properties function generateRandom() public view returns (uint256) { return uint256( keccak256(abi.encodePacked( block.timestamp, // Current block timestamp block.difficulty, // Current block difficulty block.gaslimit, // Current block gas limit msg.sender // Caller address )) ); }

Storage Operations

Storage operations are the most expensive EVM operations due to their persistent nature:

OpcodeGas CostDescription
SLOAD2100Load word from storage
SSTORE20000/5000Store word to storage (cold/warm)
SHA330Compute Keccak-256 hash

Gas Costs Evolution

Gas costs have evolved through multiple EIPs to address security concerns and economic balancing:

  • EIP-150: Increased CALL costs to prevent reentrancy attacks
  • EIP-1884: Repriced SLOAD based on Trie size increases
  • EIP-2929: Cold storage access costs (2600 cold, 100 warm)
  • EIP-3529: Reduced SSTORE refunds and removed SELFDESTRUCT gas

Gas Mechanics Deep Dive

Gas Calculation

Every EVM operation consumes a specific amount of gas, priced in Gwei (10^-9 ETH). The total gas cost equals the sum of all operation costs plus data costs.

SOLIDITY
// Gas cost calculation example for a transaction // Base gas (21000) + Data costs + Execution costs // Zero bytes: 4 gas // Non-zero bytes: 16 gas // Function call example function expensiveOperation() public { // SLOAD: 2100 cold (first access) uint256 value = storageVariable; // SSTORE: 20000 (new value) storageVariable = value + 1; // External call: ~2600 + calldata costs (bool success, ) = externalContract.call(data); }

Gas Refunds

Certain operations provide gas refunds:

  • SSTORE to zero: 15000 gas refund
  • SELFDESTRUCT: 24000 gas refund
  • Refunds applied at end of transaction, capped at half gas consumed

EIP-1559 Gas Model

The London upgrade introduced EIP-1559, changing gas economics:

SOLIDITY
// EIP-1559 concepts // Base fee: Adjusted by network congestion // Priority fee: Goes to miner/validator // Max fee: User's maximum willingness to pay function sendWithPriority(address to) public payable { // User specifies priority fee // Base fee burned, priority fee goes to validator (bool success, ) = to.call{value: msg.value}(""); require(success); }

Gas Estimation Patterns

SOLIDITY
// Gas estimation for external calls function estimateGas(address target, bytes memory data) public view returns (uint256 estimatedGas) { // Simulate the call using eth_estimateGas RPC // This is handled by the RPC provider, not in Solidity } // Gas optimization pattern: Packing structs struct PackedData { uint128 a; // First 16 bytes uint64 b; // Next 8 bytes uint64 c; // Last 8 bytes } // Instead of separate storage slots: struct UnpackedData { uint256 a; uint256 b; uint256 c; }

Call Data Handling

Function Selector

The first 4 bytes of calldata specify which function to call:

SOLIDITY
// Function selector calculation // keccak256("transfer(address,uint256)")[0:4] // In assembly: bytes4 selector = bytes4(keccak256("transfer(address,uint256)")); // Result: 0xa9059cbb // Calldata layout for transfer(address,uint256) // [0x00000000]: 0xa9059cbb (function selector) // [0x00000004]: 0x000000000000000000000000dead... (address padded) // [0x00000024]: 0x0000000000000000000000000000000000000000000000000de0b6b3a7640000 (uint256 padded)

Calldata Processing

SOLIDITY
// Efficient calldata reading function processCalldata( bytes calldata data ) external pure returns (bytes32 result) { assembly { // Direct calldata access is cheaper than abi.decode // Return first 32 bytes result := calldataload(4) } } // Multiple values function multiArg( uint256 a, uint256 b, address c ) external pure returns (uint256 sum) { // abi.decode is convenient but has overhead // Manual parsing can be more efficient assembly { sum := add( calldataload(0x04), // a calldataload(0x24) // b + offset for address ) } }

Variable-Length Data

SOLIDITY
// Dynamic types require offset tracking function decodeDynamic(bytes calldata data) external pure { // data layout: // [0x00]: offset to first dynamic array (uint256) // [0x20]: offset value (uint256) // [0x40]: dynamic array length (uint256) // [0x60]: dynamic array elements... uint256 offset = abi.decode(data[0:32], (uint256)); uint256 length = abi.decode(data[offset:offset+32], (uint256)); }

Storage Patterns and Optimization

Storage Layout

Solidity arranges storage in 32-byte slots:

SOLIDITY
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; contract StorageLayout { // Slot 0: Takes first 32 bytes uint256 public slot0; // Slot 1: Next 32 bytes (sparse packing not automatic) // Each uint128 takes full slot unless using packed struct uint128 public slot1_a; uint128 public slot1_b; // Slot 2: Takes full slot address public owner; // Slot 3: Dynamic array starts here // Contains array length, elements at keccak256(slot) uint256[] public array; // Slot 4: Mapping // keccak256(key . slot) for each value mapping(address => uint256) public balances; // Slot 5: String storage // If len <= 31: len | data in same slot // Else: len in slot, data at keccak256(slot) string public name; // Struct packing struct User { uint128 id; uint64 created; bool active; uint8 role; } // All four fit in single slot (128 + 64 + 1 + 1 = 194 bits) mapping(address => User) public users; }

Mapping and Array Storage

SOLIDITY
// Mapping storage location // Value at: keccak256(h(k) . slot) // Where h(k) is key padded to 32 bytes mapping(address => uint256) public balances; // For key = 0x1234...: // slot = 4 (mapping's slot) // position = keccak256(0x0000...1234... . 0x04) // value = storage[position] // Array storage location // Length at: slot // Elements at: keccak256(slot) + index uint256[] public arr; // arr[0] at keccak256(0x03) // arr[1] at keccak256(0x03) + 1

Packing and Unpacking

SOLIDITY
// Efficient storage with bit packing struct PackedConfig { uint128 totalSupply; // 128 bits uint64 rate; // 64 bits uint32 minPeriod; // 32 bits bool initialized; // 1 bit } // 128 + 64 + 32 + 1 = 225 bits (fits in 256-bit slot) // Reading packed values function getConfig(address user) public view returns ( uint128, uint64, uint32, bool ) { bytes32 data = packedStorage[user]; return ( uint128(data), // First 128 bits uint64(data >> 128), // Next 64 bits uint32(data >> 192), // Next 32 bits bool(data >> 224) // Remaining as bool ); } // Writing packed values function setConfig( address user, uint128 _totalSupply, uint64 _rate, uint32 _minPeriod, bool _initialized ) public { bytes32 data = bytes32(_totalSupply) | (bytes32(uint256(_rate)) << 128) | (bytes32(uint256(_minPeriod)) << 192) | (bytes32(uint256(_initialized ? 1 : 0)) << 224); packedStorage[user] = data; }

Bytecode Optimization

Assembly Patterns

SOLIDITY
// Unchecked math (Solidity 0.8+) function add(uint256 a, uint256 b) public pure returns (uint256) { unchecked { return a + b; } // No overflow check } // Assembly optimization for addition function addAssembly(uint256 a, uint256 b) public pure returns (uint256 result) { assembly { result := add(a, b) } } // Loop optimization function sumArray(uint256[] memory arr) public pure returns (uint256 total) { // Check length once uint256 length = arr.length; // Unroll loop or use unchecked for (uint256 i = 0; i < length; ) { total += arr[i]; unchecked { i++; } } }

Yul Optimization

SOLIDITY
// Using Yul for low-level optimization function optimizedKeccak(bytes memory data) public pure returns (bytes32 hash) { assembly { // Free memory pointer tracking let memPtr := mload(0x40) // Store data at memory pointer mstore(memPtr, 32) // String length mstore(add(memPtr, 32), add(data, 32)) // Compute hash hash := keccak256(memPtr, add(mload(data), 32)) } }

Deployment Cost Optimization

SOLIDITY
// Constructor arguments affect deployment cost // Constructor: runs once during deployment // initcode: includes constructor + deployment code // Cheap initialization pattern function initialize() public { require(!initialized); initialized = true; owner = msg.sender; } // Using CREATE2 for deterministic addresses address predictedAddress = address( keccak256( abi.encodePacked( bytes1(0xff), factoryAddress, salt, keccak256(initCode) ) ) );

EIP Standards and Evolution

Key EIPs for EVM Development

EIPTitleImpact
EIP-20Token StandardERC-20, foundational for DeFi
EIP-721NFT StandardERC-721, non-fungible tokens
EIP-1155Multi-tokenSingle contract multiple token types
EIP-2535Diamond StandardModular proxy pattern
EIP-2981Royalty StandardNFT royalty information
EIP-4626Vault StandardYield-bearing token vaults
EIP-4844Blob TransactionsProto-Danksharding, L2 scaling

EVM Object Format (EOF)

SOLIDITY
// EIP-3540: EOF container structure // Validation-time executable format // EOF sections: // - Version // - Type section // - Code section // - Data section // Benefits: // - Separates code from data // - Validates at deployment time // - Enables future EVM improvements

Account Abstraction (EIP-4337)

SOLIDITY
// EIP-4337: Bypasses EIP-2930 for flexible validation // Entry point contract handles all validation // UserOperation struct replaces traditional transactions struct UserOperation { address sender; uint256 nonce; bytes initCode; bytes callData; uint256 callGasLimit; uint256 verificationGasLimit; uint256 preVerificationGas; uint256 maxFeePerGas; uint256 maxPriorityFeePerGas; bytes paymasterAndData; bytes signature; }

Alternative EVM-Compatible Chains

EVM Compatibility Layers

Multiple chains implement EVM compatibility for deployment portability:

  • BNB Smart Chain: EVM-compatible, lower fees, BSC bridge
  • Avalanche (C-Chain): Subnet-based, custom gas token
  • Fantom Opera: Lachesis consensus, EVM+ compatibility
  • Cronos: Crypto.com ecosystem, EVM compatibility
  • KCC: KuCoin community chain

Chain-Specific Differences

ChainChainIDGas TokenConsensusFinality
Ethereum1ETHPoS~15 min
BNB Chain56BNBPoSA~3 sec
Avalanche43114AVAXSnowman~1 sec
Fantom250FTMLachesis~1.2 sec
Polygon137MATICPoS~2 sec

Cross-Chain Deployment

SOLIDITY
// Multi-chain deployment considerations contract MultiChainToken { address public admin; mapping(uint256 => uint256) public chainIds; constructor() { admin = msg.sender; } function setChainId(uint256[] memory chainIds_, uint256[] memory ids) public { require(msg.sender == admin); for (uint256 i = 0; i < chainIds_.length; i++) { chainIds[chainIds_[i]] = ids[i]; } } // Chain-specific addresses set post-deployment mapping(uint256 => address) public implementations; function getChainAddress(uint256 chainId) public view returns (address) { return implementations[chainId]; } }

Development Tools and Ecosystem

Disassembler Output Example

PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH2 0x0010 JUMPI PUSH1 0x00 DUP1 REVERT JUMPDEST POP ...

Bytecode Analysis Tools

ToolPurposeKey Features
ethers.jsContract interactionABI encoding, contract deployment
viemType-safe ethers alternativeTypeScript first, lightweight
FoundryTesting frameworkForge, Cast, Anvil
HardhatDevelopment environmentPlugins, task system
SlitherStatic analysisVulnerability detection
RemixWeb IDEDebugging, compilation

Decompilation

SOLIDITY
// Decompiled pattern recognition // CALLDATALOAD + SHR 224 often = function selector extraction // JUMPI after PUSH4 = function dispatch // Common patterns: // - Push + Swap = stack manipulation // - SLOAD + SSTORE = storage access // - CALL + RETURNDATASIZE = external calls

Conclusion

The EVM's architecture enables consistent smart contract execution across heterogeneous networks. Understanding opcodes, gas mechanics, storage patterns, and bytecode optimization enables developers to write more efficient contracts and diagnose complex issues. The evolving EIP standards and growing ecosystem of EVM-compatible chains ensure continued relevance of EVM development skills.

The EVM's quasi-Turing completeness, combined with gas economics, provides a unique execution model balancing flexibility with resource constraints. This architecture enables the rich smart contract ecosystems while maintaining network-wide consensus on state transitions.

Share this post