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
Opcode:0x90Introduced: Frontier (EVM genesis)SWAP1 exchanges the top stack item with the 2nd item from the top. Only these two positions change - all other items remain in place.
SWAP1 exchanges positions of the top item and the item at position 2 from top. Requires stack depth ≥ 2.Key characteristics:
Requires stack depth ≥ 2
Only two items change positions
Middle items unchanged
StackUnderflow if depth < 2
Stack depth unchanged
Examples
Basic Usage
import { handler_0x90_SWAP1 } from '@tevm/voltaire/evm/stack/handlers';import { createFrame } from '@tevm/voltaire/evm/Frame';// Swap top with 2nd itemconst frame = createFrame({ stack: [200n, 100n], gasRemaining: 1000n});const err = handler_0x90_SWAP1(frame);console.log(frame.stack); // [100n, 200n] - positions 0 and 1 swappedconsole.log(frame.gasRemaining); // 997n (3 gas consumed)
Solidity Compilation
contract Example { function simpleSwap(uint256 a, uint256 b) public pure returns (uint256, uint256) { // Return in reverse order return (b, a); // Compiler uses SWAP1 // Stack: [a, b] => [b, a] }}
Cost: 3 gas (GasFastestStep)All SWAP1-16 operations cost the same despite different stack depths accessed.Comparison:
Operation
Gas
Note
SWAP1
3
Swap with 2nd item
DUP1-16
3
Same cost tier
POP
2
Cheaper
Common Usage
Argument Reordering
// Function expects (b, a) but has (a, b)assembly { // Stack: [a, b] swap1 // Stack: [b, a] call(...)}```### Efficient Reordering```solidity// Reorder for function callassembly { // Have: [value, to, token] // Need: [token, to, value] swap2 // [token, to, value] // Call transfer(token, to, value) call(gas(), target, 0, 0, 100, 0, 0)}
Storage Optimization
assembly { let slot := 0 let value := 42 // Stack: [slot, value] // SSTORE needs (slot, value) but we have them reversed // No swap needed in this case, but if we did: swap1 // Stack: [value, slot] sstore}
Stack Depth Requirements
Minimum Depth
// SWAP1 requires 2 itemsassembly { push1 0x01 // Only 1 items - SWAP1 will fail! swap1 // StackUnderflow}
// Swap same valuesconst frame = createFrame({ stack: new Array(2).fill(42n)});handler_0x90_SWAP1(frame);console.log(frame.stack); // All still 42n
Maximum Values
// Swap with max uint256const MAX = (1n << 256n) - 1n;const frame = createFrame({ stack: [0n, MAX, 1n]});handler_0x90_SWAP1(frame);console.log(frame.stack[0]); // 1n (was at top)console.log(frame.stack[1]); // MAX (was at bottom)