Skip to main content
This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.

Overview

Stack instructions (0x50-0x9f) provide fundamental operations for manipulating the EVM’s 256-bit word stack. These 86 opcodes form the core of EVM computation, enabling value manipulation, duplication, and reordering necessary for all contract execution.

Stack Architecture

The EVM stack has strict constraints:
  • Maximum depth: 1024 items
  • Word size: 256 bits (32 bytes) per item
  • Access limit: Only top 16 items accessible via DUP/SWAP
  • Growth: Downward (item 0 is deepest, item n-1 is top)
  • Errors: StackOverflow (>1024), StackUnderflow (<required depth)

Instruction Categories

Stack Removal (0x50)

POP (0x50) - Remove top stack item
  • Gas: 2
  • Stack: [value] => []
  • Use: Discard unneeded values

Push Operations (0x5f-0x7f)

Push immediate values from bytecode onto stack: Characteristics:
  • PUSH0: Pushes constant 0 (no bytecode reading)
  • PUSH1-32: Read N bytes immediately following opcode
  • Big-endian byte order
  • Zero-padded to 256 bits
  • PC advances by 1 + N bytes

Duplicate Operations (0x80-0x8f)

Duplicate stack items at specific depths: Characteristics:
  • DUP1: Most common, duplicates top
  • DUPn: Requires stack depth ≥ n
  • Result pushed to top
  • Original value unchanged
  • StackUnderflow if depth insufficient

Swap Operations (0x90-0x9f)

Exchange top stack item with items at specific depths: Characteristics:
  • SWAP1: Most common, exchanges top two
  • SWAPn: Requires stack depth ≥ n+1
  • Only top and nth item change positions
  • Middle items unchanged
  • StackUnderflow if depth insufficient

Gas Costs

All stack operations are extremely cheap: Why so cheap?
  • Pure stack operations (no memory/storage access)
  • No external state reads
  • Constant-time execution
  • Critical for EVM performance

Common Patterns

Function Selector Matching

Address Literals

Stack Reordering

Efficient Constants

Stack Depth Management

Safe Patterns

Unsafe Patterns

Workarounds

Security Considerations

Stack Underflow

Protection:

Stack Overflow

Protection:

PUSH0 Availability

Protection:

Optimization Techniques

Minimize Stack Operations

Use PUSH0 (Shanghai+)

Reuse Stack Values

Implementation Reference

Stack instruction handlers implemented in:
  • TypeScript: /src/evm/stack/handlers/
  • Zig: /src/evm/stack/handlers_stack.zig
Each instruction follows standard handler pattern:
  1. Consume gas
  2. Validate stack constraints
  3. Perform operation (pop/push/duplicate/swap)
  4. Increment program counter
  5. Return error or null

All Stack Instructions

Complete opcode reference:

References