Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article examines EIP8024, a proposal for three new instructions that overcome the 16-slot access limit of EVM stack manipulation instructions (SWAP*/DUP*) while maintaining backward compatibility.

This article explains the specification linked below.

I have also covered various EIPs, BIPs, SLIPs, CAIPs, ENSIPs, RFCs, and ACPs.

Overview

EIP8024 proposes adding three new stack manipulation instructions to the EVM: DUPN, SWAPN, and EXCHANGE.

The EVM currently provides DUP1 through DUP16 and SWAP1 through SWAP16, but direct access is limited to depths of 16 (with SWAP using an offset from the top). Although the EVM stack can hold up to 1024 items, the easily accessible range is limited to 16. This constraint contributes to the familiar Solidity stack too deep error and has forced compilers to implement complex workarounds.

EIP8024 addresses this longstanding limitation with new instructions that can reach depth 235. The proposal is designed to preserve backward compatibility, without changing existing contracts' behavior or jump targets.

The following diagram compares the accessible ranges of the existing SWAP/DUP instructions and the new instructions. The original diagrams and code examples are retained; some labels and comments remain in Japanese.

Comparison of accessible stack depths

Relationship to EIP663

This proposal builds on EIP663, originally proposed as part of EOF (EVM Object Format). EIP663 defines the same SWAPN/DUPN/EXCHANGE instructions but depends on the EOF bytecode format change, so it cannot be used until EOF is introduced. EIP8024 removes the EOF dependency and redesigns the instructions to work with existing EVM bytecode.

Specifically, EIP663 allows arbitrary byte values for immediate operands, whereas EIP8024 excludes byte values that collide with JUMPDEST (0x5b) and PUSH instructions (0x60 through 0x7f). The new instructions can therefore be introduced without modifying existing JUMPDEST analysis.

Property EIP663 EIP8024
EOF dependency Yes No
Forbidden immediate range None 0x5b–0x7f
Changes to JUMPDEST analysis Required Not required
Deployment prerequisite EOF must be introduced Can be introduced independently

Motivation

Compiler complexity caused by the 16-slot limit

The EVM stack has a capacity of 1024 items, but DUP*/SWAP* instructions directly address only the top 16 depths. To access items beyond that range, the compiler must either spill the value to memory or rearrange the stack to bring it within reach.

This technique, referred to as stack to memory elevation, complicates compiler output and reduces gas efficiency. Even operations that could otherwise be performed entirely on the stack must go through memory using MSTORE/MLOAD.

Constraints on function arguments and return values

Implementing high-level language constructs such as function calls on the EVM involves placing input parameters, output parameters, return addresses, and other values on the stack. The number of items can easily exceed 16, forcing the compiler to carefully manage their layout so all items remain accessible.

In Solidity, many local variables or function arguments can trigger the compilation error Stack too deep, try removing local variables. This has frustrated developers and forced them to restructure code in ways that the intended program design would not otherwise require.

Stack scheduling optimization

Stack scheduling is a compiler optimization technique. It is the stack-machine equivalent of register allocation on a register machine. It analyzes variable usage patterns and optimizes instruction order to minimize movement on the stack (stack traffic).

The current EVM, however, only has SWAP instructions that exchange the first and an Nth item. Swapping the third and fifth items requires three instructions, for example: SWAP2 SWAP4 SWAP2. Within an EVM implementation these operations amount to pointer swaps, making it inefficient to split an operation that could be performed in one instruction into three.

The EXCHANGE instruction in EIP8024 addresses this issue by allowing two addressable stack items to be swapped in a single instruction.

Specification

The following diagram shows how the three new instructions manipulate the stack.

Stack operations performed by the three new instructions

EIP8024 introduces three new instructions.

Instruction Opcode Function
DUPN 0xe6 Duplicate the nth stack item onto the top
SWAPN 0xe7 Swap the (n+1)th item with the top item
EXCHANGE 0xe8 Swap the (n+1)th and (m+1)th items

Each instruction has a one-byte immediate operand immediately following its opcode. Decoding this byte determines the stack positions to manipulate.

The DUPN instruction

DUPN duplicates the nth stack item onto the top of the stack. While DUP1 through DUP16 access items 1–16, DUPN can access items 17–235.

javascript
// DUPN の実行フロー(擬似コード)
// 1. ガス3を消費
// 2. 即値 x = code[pc + 1] を読み取る
// 3. x が禁止範囲(91〜127)の場合、異常終了
// 4. n = decode_single(x) でスタック位置を算出
// 5. n > スタックの長さ の場合、異常終了
// 6. stack[top - n + 1] をスタックトップにプッシュ
// 7. pc = pc + 2 に進める

The gas cost is 3, the same as for existing DUP* instructions. Internally, a pointer operation references the stack item, so computational cost does not depend on its depth.

The SWAPN instruction

SWAPN swaps the (n+1)th item with the top item. It extends SWAP1 through SWAP16 to allow items 18–236 to be exchanged with the top.

javascript
// SWAPN の実行フロー(擬似コード)
// 1. ガス3を消費
// 2. 即値 x = code[pc + 1] を読み取る
// 3. x が禁止範囲(91〜127)の場合、異常終了
// 4. n = decode_single(x) でスタック位置を算出
// 5. n + 1 > スタックの長さ の場合、異常終了
// 6. stack[top - n] と stack[top] を入れ替え
// 7. pc = pc + 2 に進める

The (n+1)th notation for SWAPN maintains consistency with existing SWAP instructions. SWAP1 exchanges the second (1+1) item with the top; the hypothetical notation SWAPN 1 would denote the same operation, although the new instruction's actual encoding starts at 17.

The EXCHANGE instruction

EXCHANGE directly swaps two addressable items without going through the top of the stack. Unlike DUPN or SWAPN, it specifies two stack positions: the (n+1)th and (m+1)th items.

javascript
// EXCHANGE の実行フロー(擬似コード)
// 1. ガス3を消費
// 2. 即値 x = code[pc + 1] を読み取る
// 3. x が禁止範囲(82〜127)の場合、異常終了
// 4. (n, m) = decode_pair(x) でスタック位置を算出
// 5. m + 1 > スタックの長さ の場合、異常終了
// 6. stack[top - n] と stack[top - m] を入れ替え
// 7. pc = pc + 2 に進める

The operands of EXCHANGE use the same off-by-one convention as SWAP/SWAPN. In other words, EXCHANGE n m achieves the same effect as SWAP{n} SWAP{m} SWAP{n} in one instruction.

Consider EXCHANGE 2 4, which swaps the third and fifth items. If the stack is [a, b, c, d, e, ...] from the top down, the three instructions SWAP2 SWAP4 SWAP2 operate as follows.

  • SWAP2 (swap the first and third items) → [c, b, a, d, e, ...]
  • SWAP4 (swap the first and fifth items) → [e, b, a, d, c, ...]
  • SWAP2 (swap the first and third items) → [a, b, e, d, c, ...]

Only the third and fifth items have been exchanged. EXCHANGE 2 4 achieves the effect of these three instructions in one. Since the operation is implemented using pointer swaps, the instruction's gas cost can be reduced to one third.

Encoding

All three instructions use a one-byte immediate operand, but their decoding scheme is unusual. For backward compatibility, certain byte values (0x5b through 0x7f) cannot be used as immediates.

The decode_single function

DUPN and SWAPN use decode_single to decode their immediate operands.

python
def decode_single(x: int) -> int:
    """17 <= n <= 235 の範囲の値を返す"""
    assert 0 <= x <= 90 or 128 <= x <= 255
    return (x + 145) % 256

Valid values for x are 0–90 and 128–255; 91–127 are forbidden. The function adds 145 to x and takes the result modulo 256, mapping it to stack positions 17–235.

The compiler encodes these positions using the following inverse function.

python
def encode_single(n: int) -> int:
    assert 17 <= n <= 235
    return (n + 111) % 256

The range starts at 17 because depths 1–16 are already accessible using DUP1 through DUP16/SWAP1 through SWAP16, so DUPN/SWAPN do not need to cover them.

The decode_pair function

EXCHANGE must recover two stack positions (n, m) from a one-byte immediate, which requires a more complex decoding scheme.

python
def decode_pair(x: int) -> tuple[int, int]:
    """(n, m) を返す(1 <= n <= 14, n < m <= 30 - n)"""
    assert 0 <= x <= 81 or 128 <= x <= 255
    k = x ^ 143
    q, r = divmod(k, 16)
    if q < r:
        return q + 1, r + 1
    else:
        return r + 1, 29 - q

The function recovers n and m from a one-byte immediate. The range of n is 1–14, and m is greater than n and at most 30−n. This allows exchanges involving stack items from the second up to the 30th position.

The compiler encodes the pair using the following function.

python
def encode_pair(n: int, m: int) -> int:
    assert 1 <= n < m and n + m <= 30
    if m <= 16:
        q, r = n - 1, m - 1
    else:
        q, r = 29 - m, n - 1
    k = 16 * q + r
    return k ^ 143
Encoding design choices

The design of decode_pair reflects several trade-offs.

An earlier formulation of EXCHANGE only allowed swaps between stack items within a certain distance of each other. For instance, it allowed an exchange between indices 30 and 29 but could not move the item at index 30 to index 2 in one instruction. The current formulation prioritizes moving items closer to the top. Moving an item from a deep position to a shallow one is generally more useful to compilers than rearranging items deep in the stack.

The decode_pair function is designed to use basic arithmetic, bitwise operations, and minimal branching. Sacrificing a small number of addressable pairs keeps decoding complexity low.

Forbidden immediate ranges

The forbidden immediate values for each instruction are as follows.

Instruction Forbidden range Valid range
DUPN 91–127 0–90, 128–255
SWAPN 91–127 0–90, 128–255
EXCHANGE 82–127 0–81, 128–255

These ranges include 0x5b (JUMPDEST, decimal 91) and 0x60 through 0x7f (PUSH1 through PUSH32, decimal 96–127).

If a forbidden immediate appears in the code, executing that instruction immediately causes an exceptional halt. A disassembler decodes the opcode as INVALID (or a name such as INVALID_DUPN) and continues interpreting subsequent bytes normally.

Relationship to JUMPDEST analysis

An important property of the EVM is that execution cannot jump into the middle of an instruction. Even if the immediate operand of a PUSH1 through PUSH32 instruction contains 0x5b (the opcode for JUMPDEST), that byte is not considered a valid jump target. This is ensured by JUMPDEST analysis.

EIP8024 does not change JUMPDEST analysis. Instead, it maintains the same safety property by excluding immediate byte values including 0x5b from the new instructions.

The following examples illustrate why this design matters.

Take the byte sequence e6 5b. Before EIP8024, e6 is an undefined opcode (INVALID), and 5b is interpreted as JUMPDEST. If JUMPDEST analysis were changed to mask (ignore) the byte immediately following e6, 5b would no longer be a valid jump target. This could break existing contracts.

The reverse situation can also occur. Before the proposal, e6 60 5b is interpreted as INVALID PUSH1 0x5b, and 5b is not a jump target because it is the immediate operand of PUSH1. Changing JUMPDEST analysis could instead make it appear as DUPN 0x60 JUMPDEST, potentially creating a new jump target at 5b.

Under EIP8024, immediate values including 0x5b are forbidden, so e6 5b is decoded as INVALID_DUPN JUMPDEST. 5b remains a valid jump target, preserving existing contracts' behavior.

The following flowchart illustrates how the interpretation of the byte sequence changes (or remains unchanged).

flowchart TD
    A["バイト列: e6 5b"] --> B{"EIP8024導入前"}
    A --> C{"EIP8024導入後"}
    B --> D["INVALID + JUMPDEST\n(5bはジャンプ可能)"]
    C --> E["INVALID_DUPN + JUMPDEST\n(5bはジャンプ可能)"]
    D --> F["動作は同じ ✅"]
    E --> F

Behavior at the end of code

If code[pc + 1] is beyond the end of the code, its value is treated as zero. This is consistent with the existing behavior of PUSH instructions.

Additional notes

Why use immediate operands?

An alternative considered for DUPN/SWAPN/EXCHANGE was to obtain target positions dynamically from the stack (using the top value as an index for an instruction such as DUP), but this was not adopted.

Allowing dynamic arguments makes it difficult to analyze stack contents statically before execution. Static analysis is an important tool for security auditors, and determining stack manipulation patterns statically helps ensure safety. Target positions are therefore specified using immediate operands embedded directly in the code rather than values that can change dynamically.

Choice of immediate size

Two-byte immediates for DUPN and SWAPN could cover the entire stack (1024 items), but one-byte operands were chosen for the following reasons.

First, two bytes would require an additional bounds check (n < 1024). Second, increasing the existing range from 16 to 235 is already a substantial improvement and does not justify increasing code size by adding a second byte.

Similarly, while EXCHANGE can address only a finite number of pairs with one byte, coverage up to the 30th item is considered sufficient in practice.

Future reuse of forbidden immediate ranges

The encoding in EIP8024 can be reused for future instructions with immediate operands. However, if the operand range naturally excludes 0x5b (JUMPDEST) and 0x60 through 0x7f (PUSH1 through PUSH32), masking is unnecessary.

The EXCHANGE instruction sacrifices some addressable pairs to keep the decoding complexity of decode_pair low. A future network upgrade could allocate the unused range to a dozen or more additional pairs in exchange for greater decoding complexity.

Rationale for the gas cost

The new instructions have a gas cost of 3, the same as existing DUP*/SWAP* instructions. Stack operations inside an EVM implementation use pointer swaps, with the same computational cost regardless of stack depth. Decoding the immediate involves simple arithmetic, and its additional cost is negligible.

Why EXCHANGE is needed in addition to SWAPN

As noted earlier, swapping two items other than the top requires three SWAP operations. The original article illustrates this with SWAP2 SWAP3 SWAP2 when discussing moving the third item to the second position (the stated sequence actually swaps the third and fourth items). Internally, the operation amounts to a pointer swap, and executing it as one instruction does not change the client's fundamental execution cost.

The EXCHANGE instruction is particularly important for compiler stack scheduling algorithms. It can reduce the instruction count needed to move deeply positioned variables to where they are consumed to one third, saving code size and gas.

Backward compatibility

EIP8024 has been carefully designed to avoid affecting existing contracts.

The proposal provides the following backward compatibility guarantees.

For a given byte sequence, provided execution does not attempt to execute a previously undefined opcode, all execution traces produce the same results after EIP8024 is introduced. The new instructions neither create new JUMPDEST locations in existing byte sequences nor remove existing JUMPDEST locations.

Since the EVM has no dedicated data section, arbitrary byte sequences may be embedded in code (for instance, when accessing immutable data using CODECOPY). Backward compatibility must therefore be guaranteed for all byte sequences contained in deployed or not-yet-issued transactions. The encoding design of EIP8024 meets this requirement.

Test cases

Assembly and disassembly examples

The following examples show how byte sequences are decoded.

Byte sequence Decoded instructions Explanation
e680 DUPN 17 Minimum DUPN depth; duplicates the 17th item
e7db SWAPN 108 Swaps the 109th item with the top
e6805b DUPN 17, JUMPDEST Valid JUMPDEST following DUPN
e75b INVALID_SWAPN, JUMPDEST Immediate 0x5b is forbidden; JUMPDEST remains valid
e6605b INVALID_DUPN, PUSH1 0x5b Immediate 0x60 is forbidden; decoding continues with PUSH1
e7610000 INVALID_SWAPN, PUSH2 0x0000 Immediate 0x61 is forbidden; decoding continues with PUSH2
e65f INVALID_DUPN, PUSH0 Immediate 0x5f is forbidden; decoding continues with PUSH0
e89d EXCHANGE 2 3 Swaps the third and fourth items
e82f EXCHANGE 1 19 Swaps the second and 20th items
e850 EXCHANGE 14 16 Swaps the 15th and 17th items
e851 EXCHANGE 14 15 Swaps the 15th and 16th items
e852 INVALID_EXCHANGE, MSTORE Immediate 0x52 is forbidden; decoding continues with MSTORE

Execution examples

The following examples illustrate each instruction's behavior. The original article's stated stack contents and byte sequences are reproduced for reference; they have not been independently executed for this translation.

Testing DUPN

Executing 60016000808080808080808080808080808080e680 leaves 18 items on the stack. The top and bottom items are both 1, and all 16 items between them are 0. This is the result of DUPN 17 duplicating the 17th item (the bottom item, with value 1) onto the top.

Testing SWAPN

Executing 600160008080808080808080808080808080806002e780 leaves 18 items on the stack. The top item is 1 and the bottom item is 2. This is the result of SWAPN 17 exchanging the 18th item with the top; the original article describes the values involved as 2 and 1.

Testing EXCHANGE

Executing 600060016002e88e leaves three items on the stack. From the top down they are [2, 0, 1]. This is the result of EXCHANGE 1 2 swapping the second item (value 1) and the third item (value 0).

Additional EXCHANGE tests

Executing 600260008080808080600160008080808080808080e8 ultimately leaves 17 items on the stack. The bottom item is 1, the tenth item from the top is 2, and the remaining items are 0. Since the final e8 has no following byte, its immediate is treated as zero and EXCHANGE executes.

Executing 600080808080808080808080808080808080808080808080808080808060016002e88f leaves 30 items on the stack. The top item is 2, the bottom item is 1, and the remaining items are 0. This demonstrates EXCHANGE 1 29 swapping the second item (value 1) with the 30th item (value 0).

Executing 60008080e88e15 leaves three items on the stack, with 1 at the top. After EXCHANGE 1 2 swaps the second and third items, ISZERO (0x15) converts the top value (0) to 1.

Error cases

Executing e75b causes an exceptional halt because immediate 0x5b falls within the forbidden range (the original article calls this a revert). Similarly, e852 causes an exceptional halt because immediate 0x52 falls within the forbidden range (82–127) for EXCHANGE.

Executing 6000808080808080808080808080808080e680 attempts DUPN 17 with only 16 items on the stack, causing an exceptional halt due to stack underflow.

By contrast, 600456e65b executes normally. PUSH1 04 places 4 on the stack, and JUMP jumps to offset 4. The e6 at offset 3 is an INVALID_DUPN but is never executed; 5b at offset 4 remains a valid JUMPDEST.

Security

The authors of EIP8024 state that they are unaware of additional security risks introduced by the proposal.

The EVM stack is fixed at 1024 items, and most implementations keep the entire stack in memory at all times. The proposal merely expands the range accessible in a single instruction without changing the stack size itself.

The new instructions access items within the existing stack range, making it possible to reach items in one instruction that previously required multiple DUP*/SWAP* operations. The likelihood of introducing a new attack vector is therefore considered low.

References

Conclusion

This article examined how EIP8024 extends EVM stack access beyond the 16-slot limit. I hope it helped clarify the proposal.

The limited access range of EVM DUP*/SWAP* instructions is a problem many Ethereum developers have encountered through Solidity's stack too deep error. EIP8024 is a simple but powerful proposal that addresses this limitation without depending on EOF while maintaining backward compatibility. In particular, EXCHANGE can significantly contribute to compiler optimization, reducing both code size and gas costs.

If you have any questions, feel free to contact me by direct message on Twitter.

I also publish on the following platforms.