> ## Documentation Index
> Fetch the complete documentation index at: https://voltaire.tevm.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# SWAP3 (0x92)

> Swap top with 4th stack item

<Warning>
  **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.
</Warning>

## Overview

**Opcode:** `0x92`
**Introduced:** Frontier (EVM genesis)

SWAP3 exchanges the top stack item with the 4th item from the top. Only these two positions change - all other items remain in place.

## Specification

**Stack Input:**

```
[..., valueN, item2, ..., item1, top]
```

**Stack Output:**

```
[..., top, item2, ..., item1, valueN]
```

**Gas Cost:** 3 (GasFastestStep)

**Operation:**

```
temp = stack[top]
stack[top] = stack[top - 4]
stack[top - 4] = temp
```

## Behavior

SWAP3 exchanges positions of the top item and the item at position 4 from top. Requires stack depth ≥ 4.

Key characteristics:

* Requires stack depth ≥ 4
* Only two items change positions
* Middle items (items 1-3) unchanged
* StackUnderflow if depth \< 4
* Stack depth unchanged

## Examples

### Basic Usage

```typescript theme={null}
import { handler_0x92_SWAP3 } from '@tevm/voltaire/evm/stack/handlers';
import { createFrame } from '@tevm/voltaire/evm/Frame';

// Swap top with 4th item
const frame = createFrame({
  stack: [400n, 300n, 200n, 100n],
  gasRemaining: 1000n
});

const err = handler_0x92_SWAP3(frame);

console.log(frame.stack); // [100n, 300n, 200n, 400n] - positions 0 and 3 swapped
console.log(frame.gasRemaining); // 997n (3 gas consumed)
```

### Solidity Compilation

```solidity theme={null}
contract Example {
    function deepSwap() public pure {
        assembly {
            push1 0x01
            push1 0x02
            push1 0x03
            push1 0x04
            // Stack: [1, 2, 3, 4]
            swap3
            // Stack: [4, 2, 3, 1]
        }
    }
}
```

### Assembly Usage

```solidity theme={null}
assembly {
    push1 0xa
    push1 0xb
    push1 0xc
    push1 0xd
    // Stack: ['a', 'b', 'c', 'd']

    swap3
    // Stack: ['d', 'b', 'c', 'a'] - 'a' and 'd' swapped
}
```

## Gas Cost

**Cost:** 3 gas (GasFastestStep)

All SWAP1-16 operations cost the same despite different stack depths accessed.

**Comparison:**

| Operation | Gas | Note               |
| --------- | --- | ------------------ |
| SWAP3     | 3   | Swap with 4th item |
| DUP1-16   | 3   | Same cost tier     |
| POP       | 2   | Cheaper            |

## Common Usage

### Deep Stack Manipulation

````solidity theme={null}
function complex() public pure {
    assembly {
        let v0 := 0
        let v1 := 1
        let v2 := 2
        let v3 := 3
        // Need v0 at top
        swap3
        // v0 now at top
    }
}```

### Efficient Reordering

```solidity
// Reorder for function call
assembly {
    // 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

```solidity theme={null}
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

```solidity theme={null}
// SWAP3 requires 4 items
assembly {
    push1 0x01
    push1 0x02
    push1 0x03
    // Only 3 items - SWAP3 will fail!
    swap3  // StackUnderflow
}
```

### Safe Usage

```solidity theme={null}
assembly {
    push1 0x01
    push1 0x02
    push1 0x03
    push1 0x04
    // Exactly 4 items - safe
    swap3  // Success
}
```

## Implementation

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    /**
     * SWAP3 opcode (0x92) - Swap top with 4th item
     *
     * Stack: [..., valueN, ..., top] => [..., top, ..., valueN]
     * Gas: 3 (GasFastestStep)
     */
    export function handler_0x92_SWAP3(frame: FrameType): EvmError | null {
      const gasErr = consumeGas(frame, FastestStep);
      if (gasErr) return gasErr;

      if (frame.stack.length <= 3) {
        return { type: "StackUnderflow" };
      }

      const topIdx = frame.stack.length - 1;
      const swapIdx = frame.stack.length - 4;
      const temp = frame.stack[topIdx];
      frame.stack[topIdx] = frame.stack[swapIdx];
      frame.stack[swapIdx] = temp;

      frame.pc += 1;
      return null;
    }
    ```
  </Tab>
</Tabs>

## Edge Cases

### Stack Underflow

```typescript theme={null}
// Insufficient stack depth
const frame = createFrame({
  stack: [100n, 100n, 100n]  // Only 3 items, need 4
});

const err = handler_0x92_SWAP3(frame);
console.log(err); // { type: "StackUnderflow" }
```

### Out of Gas

```typescript theme={null}
// Insufficient gas
const frame = createFrame({
  stack: [100n, 100n, 100n, 100n],
  gasRemaining: 2n  // Need 3
});

const err = handler_0x92_SWAP3(frame);
console.log(err); // { type: "OutOfGas" }
```

### Identity Swap

```typescript theme={null}
// Swap same values
const frame = createFrame({
  stack: new Array(4).fill(42n)
});

handler_0x92_SWAP3(frame);
console.log(frame.stack); // All still 42n
```

### Maximum Values

```typescript theme={null}
// Swap with max uint256
const MAX = (1n << 256n) - 1n;
const frame = createFrame({
  stack: [0n, 0n, 0n, MAX, 1n]
});

handler_0x92_SWAP3(frame);
console.log(frame.stack[0]); // 1n (was at top)
console.log(frame.stack[3]); // MAX (was at bottom)
```

## References

* [Yellow Paper](https://ethereum.github.io/yellowpaper/paper.pdf) - Section 9.1 (Stack Operations)
* [EVM Codes - SWAP3](https://www.evm.codes/#92?fork=cancun)
* [Solidity Assembly - swap3](https://docs.soliditylang.org/en/latest/yul.html#evm-opcodes)
