Opcodes · stack · enabled

OP_SWAP (0x7c)

Swaps the top two items.

Verified
Stack in → out
a b → b a
Since
Original Bitcoin script
Cost
Base instruction cost 100 plus bytes pushed (2025 VM limits).
Bitcoin status
Same in Bitcoin (BTC)

Example

OP_2 OP_10 OP_SWAP OP_SUB OP_8 OP_EQUAL
Step Stack after (top on the right) What happens
OP_2 2
OP_10 2 10
OP_SWAP 10 2 Without the swap, OP_SUB would compute 2 − 10 = −8.
OP_SUB 8 Second item minus top item: 10 − 2.
OP_8 8 8
OP_EQUAL 1

Step through it opcode by opcode in Bitauth IDE, the in-browser BCH VM debugger.

Where OP_SWAP is used

  • Contracts CashScript compiler : The compiler emits OP_SWAP when a variable is reassigned inside a branch or loop, and when it builds OP_RETURN data.
  • Upgrade May 2020: SigChecks and OP_REVERSEBYTES : Before OP_REVERSEBYTES, contracts reversed byte order with chains of OP_SPLIT, OP_SWAP and OP_CAT.

Sources

  1. Libauth BCH_2023_05 opcodes (bch-2023-opcodes.ts)