In this track: Inside the EVM
advanced · 4 MIN READ

PUSH, DUP and SWAP

Introduce, copy and rearrange stack values.

LET’S PICTURE IT

You can add a card, copy a nearby card or exchange the top card with another one.

SEE IT FOR YOURSELF
Watch a stack machine execute a tiny programStep 1 / 4
Watch a stack machine execute a tiny programProgram→ PUSH1 0x02PUSH1 0x03ADD · STOPStackEmptyPC = 0A fixed local model; not a complete EVM implementationPUSH1 0x02Push immediate 2Next PC = 2Stack · top first2PUSH1 occupies one opcode byte plus one immediate bytePUSH1 0x03Push immediate 3Next PC = 4Stack · top first32The first value is below the most recently pushed valueADD3 + 2 = 5Next: STOP at PC 5Stack5No automatic SSTOREStack, memory and persistent storage are different locations

The program bytes are PUSH1 02, PUSH1 03, ADD, STOP. The program counter begins at byte zero.

Animated local teaching model. No wallet, RPC or live blockchain data. Some labels and hashes are abbreviated for readability.

Push an immediate value

PUSH1 through PUSH32 take that many immediate bytes from code and push a word. PUSH0 pushes zero without any following immediate data bytes.

Duplicate without consuming

DUP1 copies the top item. DUP2 copies the next item down. The original value remains in place while the copied value becomes the new top.

Swap with a nearby item

SWAP1 exchanges the top item and the item immediately below it. Numbered swap operations access a limited range rather than arbitrary stack positions.

Keep enough operands

A duplication or swap requires the referenced depth to exist. Stack underflow is a real execution failure, not an automatic request to fill missing entries with zero.

Trace the idea

[2, 3]
DUP1 → [2, 3, 3]
SWAP2 → [3, 3, 2]

Stack examples list the bottom first and the top last. These small traces omit gas and surrounding dispatch unless stated.

QUICK CHECK · NO PRESSURE

What does DUP1 do to [2, 3]?

Your progress stays in this browser.
Keep exploring the original referenceethereum.org ↗

Original explanations by EtherTools. Examples are educational and source-linked; this site is independent of the Ethereum Foundation. Our approach.